full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/knjname_8472329_raw_ca6ce9b79866970c5955d8784563682391847ef5_testIfSupportingClosure.ps1
knjname_8472329_raw_ca6ce9b79866970c5955d8784563682391847ef5_testIfSupportingClosure.ps1
$givenValue = 10 function testIfSupportingClosure(){ $givenValue = 4 { $givenValue = $givenValue + 1 echo "The givenValue is ${givenValue}." } } $closureA = testIfSupportingClosure $closureA.invoke() # The givenValue is 11. $closureA.invoke() # The givenValue is 11. $closureB = testIfSupportingClosure $closureB.invoke() # The givenValue is 11. $closureB.invoke() # The givenValue is 11. $givenValue = 20 $closureA.invoke() # The givenValue is 21. function testIfSupportingDynamicBinding($prc){ $givenValue = 100 $prc.invoke() } testIfSupportingDynamicBinding $closureA # The givenValue is 101. $closureA.invoke() # The givenValue is 21. # Hence, # We can say that PowerShell supports dynamic scope semantics. echo ($closureA -eq $closureB) # However, this is "False".
PowerShellCorpus/GithubGist/jstangroome_6189660_raw_dc78e4e52a8d58bfd49b7adac303008f5f0bbbf0_ConvertFrom-IISW3CLog.ps1
jstangroome_6189660_raw_dc78e4e52a8d58bfd49b7adac303008f5f0bbbf0_ConvertFrom-IISW3CLog.ps1
function ConvertFrom-IISW3CLog { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('PSPath')] [string[]] $Path ) process { foreach ($SinglePath in $Path) { $FieldNames = $null $Properties = @{} Get-Content -Path $SinglePath | ForEach-Object { if ($_ -match '^#') { #metadata if ($_ -match '^#(?<k>[^:]+):\s*(?<v>.*)$') { #key value pair if ($Matches.k -eq 'Fields') { $FieldNames = @(-split $Matches.v) } } } else { $FieldValues = @(-split $_) $Properties.Clear() for ($Index = 0; $Index -lt $FieldValues.Length; $Index++) { $Properties[$FieldNames[$Index]] = $FieldValues[$Index] } [pscustomobject]$Properties } } } } }
PowerShellCorpus/GithubGist/Iristyle_1178601_raw_481599615c627cd11f73686d2f6fdec53b25fc56_Microsoft.PowerShell_profile.ps1
Iristyle_1178601_raw_481599615c627cd11f73686d2f6fdec53b25fc56_Microsoft.PowerShell_profile.ps1
Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent) # Load posh-hg module from current directory #Import-Module .\posh-hg # If module is installed in a default location ($env:PSModulePath), # use this instead (see about_Modules for more information): Import-Module posh-hg # Set up a simple prompt, adding the hg prompt parts inside hg repos function prompt { Write-Host($pwd) -nonewline # Mercurial Prompt $Global:HgStatus = Get-HgStatus Write-HgStatus $HgStatus return "> " } if(-not (Test-Path Function:\DefaultTabExpansion)) { Rename-Item Function:\TabExpansion DefaultTabExpansion } # Set up tab expansion and include hg expansion function TabExpansion($line, $lastWord) { $lastBlock = [regex]::Split($line, '[|;]')[-1] switch -regex ($lastBlock) { # mercurial and tortoisehg tab expansion '(hg|thg) (.*)' { HgTabExpansion($lastBlock) } # Fall back on existing tab expansion default { DefaultTabExpansion $line $lastWord } } } Pop-Location function Get-Batchfile ($file) { $cmd = "`"$file`" & set" cmd /c $cmd | Foreach-Object { $p, $v = $_.split('=') Set-Item -path env:$p -value $v } } function VsVars32($version = "10.0") { if ([intptr]::size -eq 8) { $key = "HKLM:SOFTWARE\Wow6432Node\Microsoft\VisualStudio\" + $version } else { $key = "HKLM:SOFTWARE\Microsoft\VisualStudio\" + $version } $VsKey = get-ItemProperty $key $VsInstallPath = [System.IO.Path]::GetDirectoryName($VsKey.InstallDir) $VsToolsDir = [System.IO.Path]::GetDirectoryName($VsInstallPath) $VsToolsDir = [System.IO.Path]::Combine($VsToolsDir, "Tools") $BatchFile = [System.IO.Path]::Combine($VsToolsDir, "vsvars32.bat") Get-Batchfile $BatchFile [System.Console]::Title = "Visual Studio " + $version + " Windows Powershell" Set-ConsoleIcon "c:\users\eps\Documents\AwesomeVSIconsYouShouldNotHave\vspowershell.ico" } Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent) # DotSource the Console Icon Stuff . ./Set-ConsoleIcon.ps1 Pop-Location
PowerShellCorpus/GithubGist/pepoluan_5856121_raw_efb845413f57cecdc9242c0c0f103449f937faad_GetU.ps1
pepoluan_5856121_raw_efb845413f57cecdc9242c0c0f103449f937faad_GetU.ps1
Function GetU() { param( $usr, $Order, [switch]$Silent ) $EssentialAttributes = @( "EmployeeID" "Email" "MobilePhone" "Manager" ) # Specifying "-Order" overrides everything else If ($Order -ne $null) { $usr = $u[$Order] } Else { # First, check if we actually specify *something* as parameter If ($usr -eq $null) { # Nothing specified; try recovering the last selected user If ($u) { $usr = $u } Else { Write-Error "`$u not yet defined!"; return } } Else { # Something is specified. Let's check if it's a number $Ord = 0 If ([System.Int32]::TryParse($usr,[ref]$Ord)) { $usr = $u[$Ord] } # At this point, if $usr was a number, it has been converted into a member # of the previously found array. # If $usr is *not* a number, it's passed to the next line unscathed } } # Why do we re-get the $usr if it comes from a previous $u? # Good reason: Just in case there has been a change. # Actual reason: I'm too lazy to put in additional checks. Besides, won't hurt to re-get the $usr $global:u = Get-QADUser $usr -IncludeAllProperties If (!$u) { "$usr not found." return } If ($u.Count -gt 1) { "`r`n========== Multiple users found! ==========`r`n" # Now we create a nice table containing the Ord(inal) of the found users # to assist in selecting one from the list. # (Previously, it was just a dump of the array, and I have to manually count for the order) # (Not fun) $c = 0 $arr = @() foreach ($i in $u) { $props = @{ Ord = $c++ Name = $i.Name Username = $i.LogonName CanonicalName = $i.CanonicalName } $arr += New-Object PSObject -Property $props } $arr | ft -autos return } If ($u.Count -eq 1) { If (!$Silent) { $u | Select Name,LogonName,CanonicalName | ft -autos foreach ($attr in $EssentialAttributes) { " {0} = {1}" -f $attr,$u.$attr } Get-QADMemberOf $u | Select Name,CanonicalName | ft -autos } } }
PowerShellCorpus/GithubGist/amirrajan_3190670_raw_0db10b74e2cf1f0cb556ee9789e64938cb2327eb_gistfile1.ps1
amirrajan_3190670_raw_0db10b74e2cf1f0cb556ee9789e64938cb2327eb_gistfile1.ps1
$foo = @{ Message = "This is a pre-recorded message" } $foo.say = { param([string]$message) $speaker = new-object -com SAPI.SpVoice ($speaker.Speak($message, 1)) | out-null } $foo.SayPreRecordedMessage = { . $foo.say $foo.Message } #Then you can run: . $foo.SayPreRecordedMessage #but, we don't really have a factory, so let's fix that: #fake class function new-foo { $foo = @{} $Message = "This is a pre-recorded message" # use this line if you want $message to be a member of foo #$foo = @{Message = "This is a pre-recorded message" } $foo.say = { param([string]$message) $speaker = new-object -com SAPI.SpVoice ($speaker.Speak($message, 1)) | out-null } $foo.SayPreRecordedMessage = { . $foo.say $Message } $foo } $myFoo = new-foo . $myfoo.SayPreRecordedMessage . $myfoo.say "Hello, World!" # we get new objects: $foo2 = new-foo $myFoo -eq $foo2 #>False
PowerShellCorpus/GithubGist/robertchong_032da878a91c4dce9353_raw_56008363604924ec23206fab08ec7d6e752132c7_Get-PKICertificates.ps1
robertchong_032da878a91c4dce9353_raw_56008363604924ec23206fab08ec7d6e752132c7_Get-PKICertificates.ps1
Function Get-PKICertificates { <# .SYNOPSIS Gets all X.509 Certificates on a local or remote computers Source: http://gallery.technet.microsoft.com/scriptcenter/a2a500e5-1dd2-4898-9721-ed677399679c .DESCRIPTION Gets all X.509 Certificates on a local or remote computers that are from Trusted Root CAs, revoked certificates, person, etc... This also allows you to look at certificates for the LocalMachine or CurrentUser stores. The CurrentUser store can only be accessed on the local machine from where this script is being run. The LocalMachine can be accessed on either the local system or a remote system. .PARAMETER Computer Name of the computer to query for X.509 certificates .PARAMETER StoreLocation Specifies the location of the X.509 certificate store. Acceptable values are "LocalMachine","CurrentUser". The CurrentUser store location can only be accessed on the local machine. LocalMachine can be accessed at either the local machine or a remote machine. .PARAMETER StoreName Specifies the name of the X.509 certificate store to open. Acceptable values are "AddressBook","AuthRoot","CertificateAuthority", "Disallowed","My","Root","TrustedPeople","TrustedPublisher". .PARAMETER OpenFlag Specifies the way to open the X.509 certificate store Acceptable values are "ReadOnly","ReadWrite","MaxAllowed", "OpenExistingOnly","IncludeArchived". .PARAMETER ShowExpired List all certificates that have expired .PARAMETER ExpiresIn Show all certificates that are expiring withing a given number of days .NOTES Author : Boe Prox Created : 03/23/2010 .LINK http://boeprox.wordpress.com http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.openflags.aspx http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.storelocation.aspx http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.storename.aspx http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate.aspx .EXAMPLE Get-PKICertificates -computer 'server1' -StoreLocation LocalMachine -StoreName My -OpenFlag ReadOnly Description ----------- This command will return all of the certificates in the My (personal) store for 'server1' on the LocalMachine store location. .EXAMPLE Get-PKICertificates -computer 'server1' -StoreLocation LocalMachine -StoreName My -OpenFlag ReadOnly -ListExpired Description ----------- This command will return all of the certificates in the My (personal) store for 'server1' on the LocalMachine store location that has expired. .EXAMPLE Get-PKICertificates -computer 'server1' -StoreLocation LocalMachine -StoreName My -OpenFlag ReadOnly -ExpiresIn 14 Description ----------- This command will return all of the certificates in the My (personal) store for 'server1' on the LocalMachine store location that will expire withing 14 days. #> [cmdletbinding( DefaultParameterSetName = 'PKI' )] param( [Parameter( Mandatory = $False, ParameterSetName = '', HelpMessage = "Computer to query certificates.", ValueFromPipeline = $True)] [string[]]$Computer = $Env:Computername, [Parameter( ParameterSetName = '', HelpMessage = "Acceptable values are 'LocalMachine','CurrentUser'. ` CurrentUser can only be access on local machine. LocalMachine can be accessed on local or remote machine.", ValueFromPipeline = $False)] [string][ValidateSet("LocalMachine","CurrentUser")] $StoreLocation = "LocalMachine", [Parameter( ParameterSetName = '', HelpMessage = "Acceptable values are 'AddressBook','AuthRoot','CertificateAuthority','Disallowed','My',` 'Root','TrustedPeople','TrustedPublisher'", ValueFromPipeline = $False)] [string][ValidateSet("AddressBook","AuthRoot","CA","Disallowed","My","Root","TrustedPeople","TrustedPublisher")] $StoreName = "My", [Parameter( Mandatory = $False, ParameterSetName = '', HelpMessage = "Acceptable values are 'ReadOnly','ReadWrite','MaxAllowed','OpenExistingOnly','IncludeArchived'", ValueFromPipeline = $False)] [string][ValidateSet("ReadOnly","ReadWrite","MaxAllowed","OpenExistingOnly","IncludeArchived")]$OpenFlag = "ReadOnly", [Parameter( Mandatory = $False, ParameterSetName = 'Expired', HelpMessage = "Show expired certificates", ValueFromPipeline = $False)] [switch]$ListExpired, [Parameter( Mandatory = $False, ParameterSetName = 'Expiring', HelpMessage = "Enter a number to list certificates expiring in given number of days", ValueFromPipeline = $False)] [Int32]$ExpiresIn ) Begin { #Create variable that holds the OpenFlags object Write-Verbose "Setting the OpenFlag variable" $ro=[System.Security.Cryptography.X509Certificates.OpenFlags]"$OpenFlag" #Create variable that holds the Store Location object Write-Verbose "Setting the Store Location variable" $cu=[System.Security.Cryptography.X509Certificates.StoreLocation]"$StoreLocation" } Process { ForEach ($c in $computer) { Try { #Check to see if computer is remote or local Write-Verbose "Checking to see if computer is local or remote." If ($Env:Computername -ne $c) { Write-Verbose "Computer is remote, verifying network connection" If (!(Test-Connection -ComputerName $c -Count 1 -Quiet)) { Write-Verbose "$($c): Unable to locate computer" Continue } Else { If ($StoreLocation -eq "CurrentUser") { Write-Verbose "Attempting to access Remote Computer with CurrentUser store name." Write-Verbose "Unable to access remote computer's CurrentUser store. ` `nYou can only do this with the LocalMachine store name." Continue } } } Switch ($StoreLocation) { LocalMachine { #Create new object and make connection to LocalMachine certificate store on computer Write-Verbose "Attempting to make connection to certificate store" $ce=new-object System.Security.Cryptography.X509Certificates.X509Store("\\$c\$StoreName",$cu) } CurrentUser { #Create new object and make connection to CurrentUser certificate store on computer Write-Verbose "Attempting to make connection to certificate store" $ce=new-object System.Security.Cryptography.X509Certificates.X509Store("$StoreName") } } #Open the store using defined flags Write-Verbose "Opening certificate store using defined OpenFlags" $ce.Open($ro) #Determine what will be displayed based on parameter set name Write-Verbose "Determining what certificates to display" Switch ($Pscmdlet.ParameterSetName) { "PKI" { #List all certificates in the store Write-Verbose "Listing all certificates in store" $ce.certificates } "Expired" { Write-Verbose "Listing all expired certificates" $ce.Certificates | ? {$_.NotAfter -le (Get-Date)} } "Expiring" { Write-Verbose "Listing certificates that expire in $ExpiresIn days" #Create a datetime object with the expiration threshold to compare against certificate expiration timestamp $deadline = (Get-Date).AddDays($ExpiresIn) $ce.Certificates | ? {$_.NotAfter -le ($deadline)} } } } Catch { #Write error that occurred with connection Write-Host -foregroundcolor Yellow "$($c): $($error[0])" } } } }
PowerShellCorpus/GithubGist/normansolutions_8972413_raw_97727892b011f1afc65b450e0e0fe7e3cefbf50f_DisableRDPonAD.ps1
normansolutions_8972413_raw_97727892b011f1afc65b450e0e0fe7e3cefbf50f_DisableRDPonAD.ps1
Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue Get-QADUser * -OrganizationalUnit "ou=Your Sub-OU,ou=Your OU,dc=Your LDAP,dc=Your LDAP" | ?{$_.TsAllowLogon -ne $true} | Set-QADUser -TsAllowLogon $true
PowerShellCorpus/GithubGist/gravejester_f0673d05068a162de7ad_raw_c4b522d77ea063062539eadb0b4ed0aaef1d42cc_Microsoft.PowerShell_profile.ps1
gravejester_f0673d05068a162de7ad_raw_c4b522d77ea063062539eadb0b4ed0aaef1d42cc_Microsoft.PowerShell_profile.ps1
# PowerShell Profile - Øyvind Kallstad # Last updated: 27.11.2014 # Get the original prompt $originalPrompt = (Get-Item function:prompt).ScriptBlock # define our new custom prompt $customPrompt = { $currentLocaction = $executionContext.SessionState.Path.CurrentLocation.ToString() $host.UI.RawUI.WindowTitle = $currentLocaction.Replace('Microsoft.PowerShell.Core\','') Write-Host '[' -NoNewLine if (Test-Path variable:/PSDebugContext) { Write-Host 'DBG' -NoNewline -ForegroundColor 'Red' } elseif(Invoke-IsAdmin){ Write-Host "$($env:COMPUTERNAME)" -NoNewLine -ForegroundColor 'Red' } else{ Write-Host "$($env:COMPUTERNAME)" -NoNewLine -ForegroundColor 'DarkGray' } Write-Host "] $(Invoke-PathShortener $currentLocaction)$('>' * ($nestedPromptLevel + 1))" -NoNewLine return ' ' } # define a demo prompt $demoPrompt = { $host.UI.RawUI.WindowTitle = $executionContext.SessionState.Path.CurrentLocation.ToString() return '[Øyvind Kallstad] > ' } function Set-Prompt { param ([ScriptBlock] $ScriptBlock) $null = New-Item -Path function:prompt -Value $ScriptBlock -Force } function Invoke-PathShortener { <# .SYNOPSIS Path Shortener .NOTES Author: Øyvind Kallstad Date: 27.11.2014 Version: 1.0 #> [CmdletBinding()] param ( # Path to shorten. [Parameter(Position = 0)] [ValidateNotNullorEmpty()] [string] $Path, # Defines how many path levels to keep after the root before shortening. [Parameter(Position = 1)] [int] $KeepAfterRoot = 1 ) $regexString = '^(.+:{1,2}|\\{2}.+?\\.+?(?=\\))(.*)' $separator = [System.IO.Path]::DirectorySeparatorChar # first we need to clean up the path if ($path.StartsWith('Microsoft.PowerShell.Core\FileSystem')) { $path = $path.Replace('Microsoft.PowerShell.Core\FileSystem::','') } elseif ($path.StartsWith('Microsoft.PowerShell.Core')) { $path = $path.Replace('Microsoft.PowerShell.Core\','') } # use regex to separate the root from the rest of the path $matches = [regex]::Matches($path,$regexString) $pathRoot = $matches.Groups[1].Value $pathRest = ($matches.Groups[2].Value).TrimStart('\') # split on the separator character to get an array of path parts $pathParts = $pathRest.Split($separator) # put together the outpath string if ($pathParts) { if ($pathParts.Length -ge ($KeepAfterRoot + 2)) { $outPath += $pathRoot for ($i = 0; $i -lt $KeepAfterRoot; $i++) { $outPath += $separator + $pathParts[$i] } $outPath += '...' + $separator + $pathParts[-1] } else { $outPath += $pathRoot + $separator + $pathRest } } else { $outPath += $pathRoot } Write-Output $outPath } function Open-SublimeText{ # Øyvind Kallstad //2014 [CmdletBinding()] param( [Parameter(ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true)] [string[]]$Path ) BEGIN{ if(-not(Test-Path -Path $env:ProgramFiles -Filter '\Sublime Text *\sublime_text.exe')){break} $p = @() } PROCESS{ foreach ($thisPath in $Path) { $p += $thisPath } } END{ $exe = ((Get-Item "$($env:ProgramFiles)\Sublime Text *\sublime_text.exe" | Sort-Object 'LastWriteTime' -Descending | Select-Object -First 1).FullName) & $exe $p } } function Invoke-GetLocationEx { (Get-Location).ToString() } function Invoke-IsAdmin { $windowsIdentity=[System.Security.Principal.WindowsIdentity]::GetCurrent() $windowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($windowsIdentity) $adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator Write-Output ($windowsPrincipal.IsInRole($adm)) } Set-Alias -Name 'st' -Value 'Open-SublimeText' Set-Alias -Name 'pwd' -Value 'Invoke-GetLocationEx' -Option 'AllScope' -Force Set-Prompt $customPrompt Set-Location -Path 'E:\Users\ojk\Documents\Scripts' $env:Path += ';C:\Program Files (x86)\ConfigMgr 2012 Toolkit R2\ClientTools' if ($Host.Name -eq 'Windows PowerShell ISE Host') { Import-Module 'ISESteroids' Start-Sleep -Seconds 2 Start-ISERegex }
PowerShellCorpus/GithubGist/tanaka-takayoshi_8066824_raw_bf804bf48e33c2015a0702f108f584fd80e50c16_Get-SystemPowerStatus.ps1
tanaka-takayoshi_8066824_raw_bf804bf48e33c2015a0702f108f584fd80e50c16_Get-SystemPowerStatus.ps1
$signature = @" [DllImport("kernel32.dll", SetLastError = true)] public static extern Boolean GetSystemPowerStatus(out SystemPowerStatus sps); public struct SystemPowerStatus { public Byte ACLineStatus; public Byte BatteryFlag; public Byte BatteryLifePercent; public Byte Reserved1; public Int32 BatteryLifeTime; public Int32 BatteryFullLifeTime; } "@ Add-Type -MemberDefinition $signature -Name PowerStatus -Namespace PowerStatus $systemPowerStatus = New-Object PowerStatus.PowerStatus+SystemPowerStatus [void][PowerStatus.PowerStatus]::GetSystemPowerStatus([ref]$systemPowerStatus) $systemPowerStatus pause
PowerShellCorpus/GithubGist/AdamDotCom_364694_raw_d26fdfc4dc38293839bca2d52ba83cd94a27d461_install-git.ps1
AdamDotCom_364694_raw_d26fdfc4dc38293839bca2d52ba83cd94a27d461_install-git.ps1
# Installs git for Windows via PowerShell # # Sample usage: # # Install git: # PS> install-git # # Adam Kahtava - http://adam.kahtava.com/ - MIT Licensed function global:install-git { install-file http://msysgit.googlecode.com/files/Git-1.6.4-preview20090730.exe } function global:install-file([string] $urlPath) { $filename = download-file($urlPath) invoke-item $filename } function global:download-file([string] $urlPath) { $urlSplit = $urlPath.split('/') $filename = (Resolve-Path .\).ToString() + '\' + $urlSplit[$urlSplit.length - 1] $webclient = New-Object "System.Net.WebClient" $webclient.DownloadFile($urlPath, $filename) return $filename }
PowerShellCorpus/GithubGist/jstangroome_7835806_raw_7f3c5bdaeece1c8ea54173af13f256414dd3a2cb_Sort-WSDL.ps1
jstangroome_7835806_raw_7f3c5bdaeece1c8ea54173af13f256414dd3a2cb_Sort-WSDL.ps1
#requires -version 3.0 [CmdletBinding()] param ( [Parameter(Mandatory)] [string] $Path ) function Sort-NodeArray { param ( [System.Xml.XmlNode[]] $SortedNodes ) foreach ($Node in $SortedNodes) { $Node.ParentNode.AppendChild($Node.ParentNode.RemoveChild($Node)) | Out-Null } } $Path = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) $TempPath = [IO.Path]::GetTempFileName() Add-Type -AssemblyName System.Web.Services $ServiceDescription = [System.Web.Services.Description.ServiceDescription]::Read($Path) $ServiceDescription.Namespaces = $null $ServiceDescription.Write($TempPath) $Namespaces = @{ wsdl = 'http://schemas.xmlsoap.org/wsdl/' xs = 'http://www.w3.org/2001/XMLSchema' } $TypesNode = Select-Xml -Path $TempPath -XPath wsdl:definitions/wsdl:types -Namespace $Namespaces | Select-Object -ExpandProperty Node -First 1 $Schemas = @( Select-Xml -Xml $TypesNode -XPath xs:schema -Namespace $Namespaces | Select-Object -ExpandProperty Node | Sort-Object -Property { $_.GetAttribute('targetNamespace') } ) Sort-NodeArray -SortedNodes $Schemas foreach ($Schema in $Schemas) { $ImportNodes = @( Select-Xml -Xml $Schema -XPath xs:import -Namespace $Namespaces | Select-Object -ExpandProperty Node | Sort-Object -Property { $_.GetAttribute('namespace') } ) Sort-NodeArray -SortedNodes $ImportNodes $SimpleTypeNodes = @( Select-Xml -Xml $Schema -XPath xs:simpleType -Namespace $Namespaces | Select-Object -ExpandProperty Node | Sort-Object -Property { $_.GetAttribute('name') } ) Sort-NodeArray -SortedNodes $SimpleTypeNodes $ComplexTypeNodes = @( Select-Xml -Xml $Schema -XPath xs:complexType -Namespace $Namespaces | Select-Object -ExpandProperty Node | Sort-Object -Property { $_.GetAttribute('name') } ) Sort-NodeArray -SortedNodes $ComplexTypeNodes } $OutputPath = $Path $TypesNode.OwnerDocument.Save($TempPath) $ServiceDescription = [System.Web.Services.Description.ServiceDescription]::Read($TempPath) $ServiceDescription.Namespaces = $null $ServiceDescription.Namespaces.Add('tns', $ServiceDescription.TargetNamespace) $ServiceDescription.Namespaces.Add('wsdl', 'http://schemas.xmlsoap.org/wsdl/') $ServiceDescription.Namespaces.Add('soap', 'http://schemas.xmlsoap.org/wsdl/soap/') foreach ($Schema in $ServiceDescription.Types.Schemas) { $Schema.Namespaces = $null $Schema.Namespaces.Add('tns', $Schema.TargetNamespace) $Schema.Namespaces.Add('xs', 'http://www.w3.org/2001/XMLSchema') $NamespaceIndex = 1 foreach ($Include in $Schema.Includes) { $Schema.Namespaces.Add("ns$NamespaceIndex", $Include.Namespace) $NamespaceIndex++ } } $ServiceDescription.Write($OutputPath) Remove-Item -Path $TempPath
PowerShellCorpus/GithubGist/vivainio_be8e7d8a6248fdf97ef2_raw_87e3a3a85f86a0ac493cf101f6c1c4b0460792c5_gistfile1.ps1
vivainio_be8e7d8a6248fdf97ef2_raw_87e3a3a85f86a0ac493cf101f6c1c4b0460792c5_gistfile1.ps1
# edit this by: notepad $PROFILE # assumes you have Github for Windows installed (or just posh-git may be enough?) # Load posh-git example profile . 'C:\Users\villevai\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1' # Set up a simple prompt, adding the git prompt parts inside git repos function global:prompt { $realLASTEXITCODE = $LASTEXITCODE # Reset color, which can be messed up by Enable-GitColors $Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor Write-Host($pwd.ProviderPath) -nonewline -foregroundcolor DarkGray Write-VcsStatus Write-Host $global:LASTEXITCODE = $realLASTEXITCODE return "$ " } Enable-GitColors
PowerShellCorpus/GithubGist/ao-zkn_d8e1771b053f94749b5a_raw_f3ded68914520a4464e937cd49eecf262d937fe2_AddNumber-FileNameByCreationTime.ps1
ao-zkn_d8e1771b053f94749b5a_raw_f3ded68914520a4464e937cd49eecf262d937fe2_AddNumber-FileNameByCreationTime.ps1
# ------------------------------------------------------------------ # フォルダ配下のファイル名を作成日時順に連番を付ける # 関数名:AddNumber-FileNameByCreationTime # 引数  :FolderPath 対象フォルダ # :Include 対象拡張子 # :AddType 連番指定[接頭or接尾] (※接頭の場合は「Prefix」、接尾の場合は「Suffix」を指定) # :NumberFormat 0埋め桁数 (※3桁の場合「000」と桁数分0を指定) # 戻り値:なし # ------------------------------------------------------------------ function AddNumber-FileNameByCreationTime([String]$FolderPath,[String]$Include,[String]$AddType="Prefix",[String]$NumberFormat="0"){ $count = 0; Get-ChildItem $FolderPath -Recurse -Include $Include | Sort-Object {$_.CreationTime -as [DateTime]} | ForEach-Object { # 接頭に連番追加 if("Prefix" -eq $AddType){ $Name =$_.Name Rename-Item $_.FullName -newName ("{0:$NumberFormat}_$Name" -F $count++) } # 接尾に連番追加 elseif("Suffix" -eq $AddType){ $BaseName =$_.BaseName $Extension =$_.Extension Rename-Item $_.FullName -newName (("$BaseName"+ "_" + "{0:$NumberFormat}$Extension") -F $count++) } } }
PowerShellCorpus/GithubGist/bohrshaw_5e7b51e999f2d6ca8f6a_raw_24706f51ee11b670cc1e3016c4d56d537fc94c5b_ruby-builder.ps1
bohrshaw_5e7b51e999f2d6ca8f6a_raw_24706f51ee11b670cc1e3016c4d56d537fc94c5b_ruby-builder.ps1
# Build Ruby with Visual Studio on Windows # Refer win32/README.win32 mkdir mswin32 cd mswin32 ../win32/configure.bat --target=i686-mswin32 --prefix=D:/Programs/Ruby21mswin nmake nmake test nmake install
PowerShellCorpus/GithubGist/ktsugita_5559192_raw_c405f3af169c0bc2a2efdf51cec2acafb4801782_gistfile1.ps1
ktsugita_5559192_raw_c405f3af169c0bc2a2efdf51cec2acafb4801782_gistfile1.ps1
$disk = Get-WmiObject -class Win32_LogicalDisk -filter "DeviceID='C:'" Write-Host "Free space on drive C: at $($disk.freespace / $disk.size * 100) percent"
PowerShellCorpus/GithubGist/alexrydzak_6386419_raw_6c1d4884e546a747a3165439fcdb3a905a590d55_hide_metro.ps1
alexrydzak_6386419_raw_6c1d4884e546a747a3165439fcdb3a905a590d55_hide_metro.ps1
# hide_metro.ps1 # sends <Win>+D to minimize Metro on login # save as C:\Users\<Your User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\hide_metro.ps1 $shell = New-Object -ComObject "Shell.Application" $shell.minimizeall()
PowerShellCorpus/GithubGist/kyam_5575779_raw_3fd1537e119625285c58e739fce531f3a49d5c51_listed_installapps.ps1
kyam_5575779_raw_3fd1537e119625285c58e739fce531f3a49d5c51_listed_installapps.ps1
# Get All Applications with .msi $apps = Get-WmiObject -Query "SELECT * FROM win32_product" foreach ($app in $apps) { Write-Host $app.Name $app.Vendor } # Get Application with .msi selected by name $apps = Get-WmiObject -Query "SELECT * FROM win32_product WHERE name = 'Adobe AIR'" Write-Host $app.Name $app.Vendor
PowerShellCorpus/GithubGist/Retro2707_7334955_raw_397ab2a7e60f2dda9ef75c9cdff443ebe396577b_err.ps1
Retro2707_7334955_raw_397ab2a7e60f2dda9ef75c9cdff443ebe396577b_err.ps1
$error[0].Exception.GetType().Fullname #or while in a script. try { # code that causes exception } catch { $_.Exception.GetType().FullName }
PowerShellCorpus/GithubGist/belotn_5664076_raw_113df7c08d119a44b36d42ea085d61ba758f0c0c_generate_chart.ps1
belotn_5664076_raw_113df7c08d119a44b36d42ea085d61ba758f0c0c_generate_chart.ps1
$html ="<html> <head> <!--Load the AJAX API--> <script type=`"text/javascript`" src=`"https://www.google.com/jsapi`"></script> <script type=`"text/javascript`"> // Load the Visualization API and the piechart package. google.load('visualization', '1.0', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); // Callback that creates and populates a data table, // instantiates the pie chart, passes in the data and // draws it. function drawChart() { // Create the data table. var data = new google.visualization.DataTable(); data.addColumn('datetime','Date'); data.addColumn('number','CCU'); data.addRows([ " $html += @( get-childitem c:\Path\to\log -Filter Log*.txt | sort LastWriteTime |% { import-csv -Delimiter ';' $_.Name -header @("Horaire","CCU") |% { $d = [datetime]::ParseExact($_.Horaire, "MM/dd/yyyy HH:mm:ss",$null) if(-not $_.CCU ){$_.CCU=0} "[new Date($($d.Year), $($d.Month-1),$($d.Day),$($d.Hour),$($d.Minute),$($d.Second)), $($_.CCU)]" } } ) -join ",`n" $html+=" ]); // Set chart options var options = {'title':'CCU'}; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <!--Div that will hold the pie chart--> <div id=`"chart_div`"></div> </body> </html>"
PowerShellCorpus/GithubGist/gravejester_1290947b5da8dd9e733d_raw_82208a3f7bd0da310b718cf4d71182e014bb92e4_New-MsSqlConnection.ps1
gravejester_1290947b5da8dd9e733d_raw_82208a3f7bd0da310b718cf4d71182e014bb92e4_New-MsSqlConnection.ps1
function New-MsSqlConnection { <# .SYNOPSIS Create a new MSSQL database connection. .DESCRIPTION This function will create a new Microsoft SQL Server database connection and return a database connection object. .EXAMPLE New-MsSqlConnection -DatabaseServer dbServer01 -DatabaseName 'myDB' .NOTES Author: Øyvind Kallstad Date: 22.01.2015 Version: 1.0 #> [CmdletBinding()] param ( # Name of server or instance. [Parameter(Mandatory = $true, Position = 0)] [Alias('Server','ComputerName','dbServer')] [string] $DatabaseServer, # Name of database. [Parameter(Mandatory = $true, Position = 1)] [string] $DatabaseName, # Port to connect to. Default is 1433. [Parameter()] [int] $Port, # Credential, if not using trusted connection. [Parameter(Mandatory = $false)] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty ) try { # start building the connection string $connectionStringBuilder = New-Object 'System.Data.SqlClient.SqlConnectionStringBuilder' if($Port) {$DatabaseServer = "$($DatabaseServer),$($Port);"} $connectionStringBuilder.Server = $DatabaseServer $connectionStringBuilder.Database = $DatabaseName # if credential parameter is not used, trusted connection will be used if (-not($PSBoundParameters['Credential'])) { $connectionStringBuilder.Trusted_Connection = $true } # otherwise create a sqlcredential object else { $Credential.Password.MakeReadOnly() $sqlCred = New-Object 'System.Data.SqlClient.SqlCredential' -ArgumentList ($Credential.UserName,$Credential.Password) } # create database connection $dbConnection = New-Object -TypeName 'System.Data.SqlClient.SqlConnection' -ArgumentList $connectionStringBuilder.ConnectionString # if needed, add the sqlcredential object if($PSBoundParameters['Credential']) { $dbConnection.Credential = $sqlCred } # open the connection [void]$dbConnection.Open() # return the connection object Write-Output $dbConnection } catch { Write-Warning "At line:$($_.InvocationInfo.ScriptLineNumber) char:$($_.InvocationInfo.OffsetInLine) Command:$($_.InvocationInfo.InvocationName), Exception: '$($_.Exception.Message.Trim())'" } }
PowerShellCorpus/GithubGist/rgbkrk_7271813_raw_b34cc982bce34094fc5015fb49acf41597b1d106_pyrax_install.ps1
rgbkrk_7271813_raw_b34cc982bce34094fc5015fb49acf41597b1d106_pyrax_install.ps1
## ## NOTE: This script is a walkthrough and may not work if run directly. ## ## If downloaded to run, make sure to set ## ## Set-ExecutionPolicy RemoteSigned ## # Create a downloader via .NET $notwget = New-Object System.Net.WebClient # We'll download and install # - the Python 2.7 64-bit msi # - ez_setup.py # - get-pip.py # Download and install Python 2.7 $notwget.DownloadFile("http://www.python.org/ftp/python/2.7.6/python-2.7.6.amd64.msi", "$pwd\python-2.7.6.amd64.msi") # Run the installer in non-interactive installation mode & msiexec /i .\python-2.7.6.amd64.msi ALLUSERS=1 # Install the latest and greatest version of Setuptools $notwget.DownloadFile("https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py", "$pwd\ez_setup.py") # Rather than muck with PATH and PYTHONPATH, simply did these installs directly & "C:\Python27\python.exe" .\ez_setup.py # Get pip! $notwget.DownloadFile("https://raw.github.com/pypa/pip/master/contrib/get-pip.py", "$pwd\get-pip.py") & "C:\Python27\python.exe" .\get-pip.py # Because of an upstream issue in pbr, we install an old version of pbr first. & "C:\Python27\Scripts\pip.exe" install pbr==0.5.21 # Now can install pyrax & "C:\Python27\Scripts\pip.exe" install pyrax
PowerShellCorpus/GithubGist/aseabridge_2402637_raw_0ed7186782befbcce1fd67256082e0308ef581b9_delte-users.ps1
aseabridge_2402637_raw_0ed7186782befbcce1fd67256082e0308ef581b9_delte-users.ps1
#Configuration $Url = "http://yoursite.com" $Username = "admin" $ApiKey = "yourapikeyxxxxxxxxxxxxxx" $userNamesToDelete = @("adssgdsg", "peterpan", "test") #End Configuration $UserToken =[Convert]::ToBase64String([System.Text.Encoding]::Utf8.GetBytes("${ApiKey}:${Username}")) $webClient = new-object System.Net.WebClient $webClient.Headers.Add("Rest-User-Token", $UserToken) $deleteWebClient = new-object System.Net.WebClient $deleteWebClient.Headers.Add("Rest-User-Token", $UserToken) $deleteWebClient.Headers.Add("Rest-Method", "DELETE") Add-Type -AssemblyName System.Web #Start Deleting $userNamesToDelete |% { $usernameToDelete = [System.Web.HttpUtility]::UrlEncode($_).Replace("+", "%20") $user = [xml]$webClient.DownloadString("$url/api.ashx/v2/users/$usernameToDelete.xml") $user = $user.Response.User if ($user.Username -ieq $_) { $userId = $user.Id $deleteWebClient.UploadString("$url/api.ashx/v2/users/$userId.xml", "") "User Deleted" } else { "............." "User $usernameToDelete Not Found" } }
PowerShellCorpus/GithubGist/jonschoning_1149265_raw_7f5a60fc896b1b3d3a62d3b4c5a90d304a07761d_Get-SubDirSizes.ps1
jonschoning_1149265_raw_7f5a60fc896b1b3d3a62d3b4c5a90d304a07761d_Get-SubDirSizes.ps1
function Get-SubDirSizes { param([Parameter(Mandatory=$true)] [string] $path) dir $path -force | ? { $_.PSIsContainer} | % { new-object PsObject -property @{ Length = (dir $_.FullName -recurse -force | ? {! $_.PSIsContainer} | measure-object -sum Length).Sum; Name = $_.Name } } | sort Length -desc | ft Name,@{l="Size in MB"; e={[int]($_.Length/1MB)}} -autosize }
PowerShellCorpus/GithubGist/mmdemirbas_5253480_raw_a81daccee7dfbd44f7bb97f4e237e5dc83a886c7_battery.ps1
mmdemirbas_5253480_raw_a81daccee7dfbd44f7bb97f4e237e5dc83a886c7_battery.ps1
######################################################################### # # # Script to check battery state periodically and alert if it is # # going to outside of the desired range (%40-%80) by default. # # # # Usage: # # # # # To alert if x<=40 or x>=80, and check each 15 sec # # # # .\battery.ps1 40 80 15 # # # # # # Author: Muhammed Demirbas, mmdemirbas at gmail dot com # # # # Date : 2013-03-26 # # # ######################################################################### # Default values for parameters param($lowerLimit=40, $upperLimit=80, $interval=15) # Function to return first non-null value among its arguments Function IfNull($a,$b) { if($a){$a} else {$b} } while($true) { $obj = (Get-WmiObject -Class Win32_Battery -ea 0) $remainingMinutes = IfNull $obj.EstimatedRuntime "N/A" $remainingPercentage = IfNull $obj.EstimatedChargeRemaining "N/A" $statusString = switch (IfNull $obj.BatteryStatus 0) { 0 { $pluggedin=0 ; "N/A" } 1 { $pluggedin=0 ; "Discharging" } 2 { $pluggedin=1 ; "Plugged in to AC" } 3 { $pluggedin=0 ; "Fully Charged" } 4 { $pluggedin=0 ; "Low" } 5 { $pluggedin=0 ; "Critical" } 6 { $pluggedin=1 ; "Charging" } 7 { $pluggedin=1 ; "Charging and High" } 8 { $pluggedin=1 ; "Charging and Low" } 9 { $pluggedin=1 ; "Charging and Critical" } 10 { $pluggedin=0 ; "Unknown State" } 11 { $pluggedin=0 ; "Partially Charged" } } if ($remainingMinutes -ge 1000) { $remainingMinutes = "N/A" } if ( !$pluggedin -and $remainingPercentage -le $lowerLimit ) { $alert = "Connect AC!" } elseif ( $pluggedin -and $remainingPercentage -ge $upperLimit ) { $alert = "Disconnect AC!" } else { $alert = $null } $forecolor = if($alert){ [ConsoleColor]::White } else { [ConsoleColor]::Gray } $backcolor = if($alert){ [ConsoleColor]::DarkRed } else { [ConsoleColor]::DarkGreen } $log = "[$(Get-Date)] Remaining: $remainingPercentage% ~= $remainingMinutes minutes. $statusString. $alert" Write-Host -ForegroundColor $forecolor -BackgroundColor $backcolor $log if ($alert) { [System.Media.SystemSounds]::Hand.Play() # Play sound } Start-Sleep -Seconds $interval }
PowerShellCorpus/GithubGist/JayBazuzi_d5a71230d524965057be_raw_cf46945ebd0b8472b00ff1545f742ceeff18b0f3_PreBuild.ps1
JayBazuzi_d5a71230d524965057be_raw_cf46945ebd0b8472b00ff1545f742ceeff18b0f3_PreBuild.ps1
# # keep this in synch with TeamBuild.proj # $ResharperCltVersion='8.2.0.2151' # UseBasicParsing is required if IE has never been run on the machine. wget -UseBasicParsing chocolatey.org/install.ps1 | iex if (!$?) { throw "failed to install chocolatey"} cinst resharper-clt.portable -version $ResharperCltVersion if (!$?) { throw "failed to install R# CLT"}
PowerShellCorpus/GithubGist/psschroeter_53df461fe367abf714c2_raw_6b700b071c00ef994961a86cca5a63a456c19e25_xenstore_client.ps1
psschroeter_53df461fe367abf714c2_raw_6b700b071c00ef994961a86cca5a63a456c19e25_xenstore_client.ps1
param( [Parameter(Mandatory=$True,Position=0)][string]$command, [Parameter(Mandatory=$True,Position=1)][string]$value ) $sessionName = "XenStoreReader" $session = Get-WmiObject -Namespace root\wmi -Query "select * from CitrixXenStoreSession where Id='$sessionName'" if (!($session)) { $base = Get-WmiObject -Namespace root\wmi -Class CitrixXenStoreBase $base.AddSession($sessionName) $session = Get-WmiObject -Namespace root\wmi -Query "select * from CitrixXenStoreSession where Id='$sessionName'" } if ($command -eq "read") { $res = $session.GetValue($value) if ($res) { return $res.value } else { echo "Could not find value $value" exit 1 } } elseif ($command -eq "ls" -or $command -eq "dir") { $res = $session.GetChildren($value) if ($res) { return $res.children.ChildNodes -replace "$value/", "" } else { echo "Could not find dir $value" exit 1 } } else { echo "Unrecognized command $command. Only 'read' and 'dir' are currently supported" exit 1 }
PowerShellCorpus/GithubGist/rverrips_11398327_raw_4939e39ea56b03fd5bdf347be345b0f0bb6fb1f0_move-vmstorage.ps1
rverrips_11398327_raw_4939e39ea56b03fd5bdf347be345b0f0bb6fb1f0_move-vmstorage.ps1
$newpath="C:\new\place\for\Hyper-V" get-vm | % { move-vmstorage $_ -DestinationStoragepath $($newpath+"\"+$_.VMName)}
PowerShellCorpus/GithubGist/mortenya_3a2c208c92ca0e64c597_raw_3e44cc2fad3df2482c4df4da75053e20cde03c39_Get-MemberOf.ps1
mortenya_3a2c208c92ca0e64c597_raw_3e44cc2fad3df2482c4df4da75053e20cde03c39_Get-MemberOf.ps1
(Get-ADUser –Identity $user –Properties MemberOf).MemberOf -replace '^CN=([^,]+),OU=.+$','$1' > c:\user-groups.txt # The -replace will strip the CN of the group from the Distinguished Name. # This isn't error proof, but will be adequate for most use cases when dealing with Security Groups.
PowerShellCorpus/GithubGist/mikecessna_b8c1cc3c63fc9ac7a2c9_raw_2b89845c2f61bbd0890c664657ef38563c81558e_find-serviceaccounts.ps1
mikecessna_b8c1cc3c63fc9ac7a2c9_raw_2b89845c2f61bbd0890c664657ef38563c81558e_find-serviceaccounts.ps1
# Script to find servers in AD and output any services running as a 'non-normal' account. #Load the AD module if not already loaded. If (!(Get-module Activedirectory )) {Import-Module OperationsManager} $systemservicenames=@("LocalSystem", "NT AUTHORITY\LocalService", "NT AUTHORITY\Local Service", "NT AUTHORITY\NetworkService", "NT AUTHORITY\Network Service") $outputfile="C:\bin\ServiceAccounts.csv" $services=@() $servers=@() $output=@() $alive=0 $dead=0 $cred=Get-Credential #get server list from AD Write-Host "Finding Computer Objects in AD" $ADservers=Get-ADComputer -filter * -Properties OperatingSystem | ?{$_.OperatingSystem -like "*SERVER*"} $found=$ADservers.count Write-Output "Found $found Server objects in Active Directory." #test is server is alive $i=1 Foreach($ADserver in $ADservers){ Write-Progress -Activity "Checking for Live Servers" -Status "Working on [$i out of $found] $ADserver" -PercentComplete ($i++/$Found*100) if(Test-Connection -Count 1 -ComputerName $ADserver.name -ErrorAction SilentlyContinue){ #Write-Output "Got a live one:" $ADserver.name $servers+=$ADserver $alive++ } else { #Write-Output "Got a Dead One:" $ADserver.name $dead++ } } $i=1 foreach ($server in $servers) { Write-progress -Activity "Getting Services from Servers" "Working on host[$i out of $alive]: $server" -PercentComplete ($i++/$alive*100) $services=Get-WmiObject win32_service -ComputerName $server.name -Credential $cred | where {$systemservicenames -notcontains $_.startname} if($services.count -ne $null) { foreach ($service in $services) { #Write-Output "Service Account found!" $objService=New-Object system.object $objservice | Add-Member -Type NoteProperty -Name Server -Value $server $objservice | Add-Member -Type NoteProperty -Name ServiceName -Value $service.name $objservice | Add-Member -Type NoteProperty -Name StartName -Value $service.startname $output+=$objservice } } } $output | Export-Csv $outputfile -NoTypeInformation Write-Output "Servers found in AD: $found" Write-Output "Live Servers: $alive" Write-Output "Dead Servers: $dead"
PowerShellCorpus/GithubGist/vScripter_10318913_raw_97485e2eac6fd61e30a1f9d89338df216cbe46e2_Invoke-LocalAdminAudit.ps1
vScripter_10318913_raw_97485e2eac6fd61e30a1f9d89338df216cbe46e2_Invoke-LocalAdminAudit.ps1
[cmdletbinding()] param ( [parameter(mandatory = $true)] [string[]]$Servers ) $results = @() $Log = "C:\Invoke-LocalAdminAudit.ps1.log" if (Test-Path $Log) { Remove-Item $Log -Force } Write-Verbose "Gathering Local Admin Membership..." ForEach ($server in $servers) { $Report = "C:\LocalAdminReport.csv" if (Test-Path $Report) { Remove-Item -Path $Report -Force } if (Test-Connection $server -Count 2 -Quiet) { # Setup empty array and assign to a variable $admins = @() # assign ADSI local admin query to a variable $group = [ADSI]"WinNT://$server/Administrators" # Call members from the group $members = @($group.psbase.Invoke("Members")) # Cycle through each member and add the member name to a custom PSObject $members | ForEach { $obj = New-Object psobject -Property @{ Server = $Server Admin = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) }# end $obj $admins += $obj }# end foreach # Store the results in the 'results' array $results += $admins }# end if else { }# end else }# end foreach # export the results $results | Export-Csv $Report -Append -NoTypeInformation
PowerShellCorpus/GithubGist/jpoehls_2844751_raw_01159a5b7d411906fbb7a4b3ace89a13ea175838_Kill-VisualStudio.ps1
jpoehls_2844751_raw_01159a5b7d411906fbb7a4b3ace89a13ea175838_Kill-VisualStudio.ps1
function Kill-VisualStudio { <# .SYNOPSIS Kills all running 'devenv' instances. #> Get-Process devenv -ErrorAction SilentlyContinue | Stop-Process } Set-Alias killvs Kill-VisualStudio
PowerShellCorpus/GithubGist/glombard_10017705_raw_7ffe48e7beb0435a83e13d8c8dd730db4d70f171_unblock-files.ps1
glombard_10017705_raw_7ffe48e7beb0435a83e13d8c8dd730db4d70f171_unblock-files.ps1
if (!(Test-Path "$env:Temp\streams.exe")) { (new-object System.Net.WebClient).DownloadFile('http://live.sysinternals.com/streams.exe', "$env:Temp\streams.exe") } # "Unblock" the files... & "$env:Temp\streams.exe" @('-d', '*.*')
PowerShellCorpus/GithubGist/tophatsteve_2916858_raw_b5a8bb713535ddad4914b120c34e1a2766b88539_control-ie.ps1
tophatsteve_2916858_raw_b5a8bb713535ddad4914b120c34e1a2766b88539_control-ie.ps1
$ie = new-object -com "InternetExplorer.Application" $ie.visible = $true $ie.navigate("http://localhost/Default.aspx") $doc = $ie.document $link = $doc.getElementByID("link_01") $link.click()
PowerShellCorpus/GithubGist/andrewodri_46da27dab1e705f71b9c_raw_a89aff008767b8b6d53edcf7184e8789a1249d1f_elevating.ps1
andrewodri_46da27dab1e705f71b9c_raw_a89aff008767b8b6d53edcf7184e8789a1249d1f_elevating.ps1
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent(); $myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID); $adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator; Push-Location; Set-Location HKCU:\Console; if(!(Test-Path -Path ".\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe")){ Set-Item ".\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe"; } Set-Location ".\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe"; Set-ItemProperty . ColorTable00 -type DWORD -value 0x00562401; Set-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee; Set-ItemProperty . FaceName -type STRING -value "Lucida Console"; Set-ItemProperty . FontFamily -type DWORD -value 0x00000036; Set-ItemProperty . FontSize -type DWORD -value 0x000c0000; Set-ItemProperty . FontWeight -type DWORD -value 0x00000190; Set-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000; Set-ItemProperty . QuickEdit -type DWORD -value 0x00000001; Set-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078; Set-ItemProperty . WindowSize -type DWORD -value 0x00320078; Pop-Location; if($myWindowsPrincipal.IsInRole($adminRole)) { $Host.UI.RawUI.WindowTitle = "Administrator: " + $myInvocation.MyCommand.Definition; Clear-Host; }else{ $newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell"; $newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"; $newProcess.Verb = "runas"; [System.Diagnostics.Process]::Start($newProcess); Exit; } $WindowSize = $Host.UI.RawUI.WindowSize; $WindowSize.Width = 120; $WindowSize.Height = 50; $Host.UI.RawUI.WindowSize = $WindowSize;
PowerShellCorpus/GithubGist/slacker_1220314_raw_913d5de7f3a8cefb30c6afdf543df73a1c10bb56_netstat.ps1
slacker_1220314_raw_913d5de7f3a8cefb30c6afdf543df73a1c10bb56_netstat.ps1
# Based on code found at http://poshcode.org/2694 $null, $null, $null, $null, $netstat = netstat -ano $ps = Get-Process [regex]$regexTCP = '(?<Protocol>\S+)\s+(?<LAddress>\S+):(?<LPort>\S+)\s+(?<RAddress>\S+):(?<RPort>\S+)\s+(?<State>\S+)\s+(?<PID>\S+)' [regex]$regexUDP = '(?<Protocol>\S+)\s+(?<LAddress>\S+):(?<LPort>\S+)\s+(?<RAddress>\S+):(?<RPort>\S+)\s+(?<PID>\S+)' $return = @() foreach ($line in $netstat) { switch -regex ($line.Trim()) { $regexTCP { $process = New-Object psobject -property @{ Protocol = $matches.Protocol LocalAddress = $matches.LAddress LocalPort = $matches.LPort RemoteAddress = $matches.RAddress Remoteport = $matches.RPort State = $matches.State ID = [int]$matches.PID ProcessName = ( $ps | Where-Object {$_.Id -eq $matches.PID} ).ProcessName } $return = $return + $process continue } $regexUDP { $process = New-Object psobject -property @{ Protocol = $matches.Protocol LocalAddress = $matches.LAddress LocalPort = $matches.LPort RemoteAddress = $matches.RAddress Remoteport = $matches.RPort State = $matches.State ID = [int]$matches.PID ProcessName = ( $ps | Where-Object {$_.Id -eq $matches.PID} ).ProcessName } $return = $return + $process continue } } } $return
PowerShellCorpus/GithubGist/cajones_3149699_raw_5dabe97eeeffcb143654c05f65a033c8766120f6_find-hiddendrives.ps1
cajones_3149699_raw_5dabe97eeeffcb143654c05f65a033c8766120f6_find-hiddendrives.ps1
function Find-HiddenDrive($server) { $alpha = [char[]]"cdefghijklmnopqrstuvwxyz" return $alpha | ? { test-path \\$server\$_`$ } }
PowerShellCorpus/GithubGist/GuruAnt_5442585_raw_710403f1c2d0f9a4a0596053474349def59f97cc_PowerCLIScriptExample2.ps1
GuruAnt_5442585_raw_710403f1c2d0f9a4a0596053474349def59f97cc_PowerCLIScriptExample2.ps1
# Loop through each VM ForEach ($objVM in ( Get-VM | Where-Object { # Where the configured memory is greater than 2000 $_.MemoryMB -gt "2000" } )){ # Get the VM guest object Get-VMGuest -VM $objVM | Where-Object { # Where the operating system is Windows XP $_.OSFullName -like "Microsoft Windows XP Professional*" # And display the VM object name, the guest hostname, and the memory in MB } | Select-Object VMName,Hostname,MemoryMB }
PowerShellCorpus/GithubGist/AdilHindistan_8701241_raw_420e8f279baee62bb9042eb61ead0e9bb3d72fe3_Invoke-CommandAST.ps1
AdilHindistan_8701241_raw_420e8f279baee62bb9042eb61ead0e9bb3d72fe3_Invoke-CommandAST.ps1
#requires -Version 3 #Usage: #Invoke-command -computername $server -scriptblock {FunctionName -param1 -param2} # Author: Matt Graeber # @mattifestation # www.exploit-monday.com function Invoke-Command { [CmdletBinding(DefaultParameterSetName='InProcess', HelpUri='http://go.microsoft.com/fwlink/?LinkID=135225', RemotingCapability='OwnedByCommand')] param( [Parameter(ParameterSetName='FilePathRunspace', Position=0)] [Parameter(ParameterSetName='Session', Position=0)] [ValidateNotNullOrEmpty()] [System.Management.Automation.Runspaces.PSSession[]] ${Session}, [Parameter(ParameterSetName='FilePathComputerName', Position=0)] [Parameter(ParameterSetName='ComputerName', Position=0)] [Alias('Cn')] [ValidateNotNullOrEmpty()] [string[]] ${ComputerName}, [Parameter(ParameterSetName='Uri', ValueFromPipelineByPropertyName=$true)] [Parameter(ParameterSetName='FilePathUri', ValueFromPipelineByPropertyName=$true)] [Parameter(ParameterSetName='ComputerName', ValueFromPipelineByPropertyName=$true)] [Parameter(ParameterSetName='FilePathComputerName', ValueFromPipelineByPropertyName=$true)] [pscredential] [System.Management.Automation.CredentialAttribute()] ${Credential}, [Parameter(ParameterSetName='ComputerName')] [Parameter(ParameterSetName='FilePathComputerName')] [ValidateRange(1, 65535)] [int] ${Port}, [Parameter(ParameterSetName='ComputerName')] [Parameter(ParameterSetName='FilePathComputerName')] [switch] ${UseSSL}, [Parameter(ParameterSetName='FilePathComputerName', ValueFromPipelineByPropertyName=$true)] [Parameter(ParameterSetName='ComputerName', ValueFromPipelineByPropertyName=$true)] [Parameter(ParameterSetName='FilePathUri', ValueFromPipelineByPropertyName=$true)] [Parameter(ParameterSetName='Uri', ValueFromPipelineByPropertyName=$true)] [string] ${ConfigurationName}, [Parameter(ParameterSetName='ComputerName', ValueFromPipelineByPropertyName=$true)] [Parameter(ParameterSetName='FilePathComputerName', ValueFromPipelineByPropertyName=$true)] [string] ${ApplicationName}, [Parameter(ParameterSetName='FilePathComputerName')] [Parameter(ParameterSetName='Session')] [Parameter(ParameterSetName='ComputerName')] [Parameter(ParameterSetName='FilePathRunspace')] [Parameter(ParameterSetName='FilePathUri')] [Parameter(ParameterSetName='Uri')] [int] ${ThrottleLimit}, [Parameter(ParameterSetName='Uri', Position=0)] [Parameter(ParameterSetName='FilePathUri', Position=0)] [Alias('URI','CU')] [ValidateNotNullOrEmpty()] [uri[]] ${ConnectionUri}, [Parameter(ParameterSetName='FilePathComputerName')] [Parameter(ParameterSetName='Uri')] [Parameter(ParameterSetName='ComputerName')] [Parameter(ParameterSetName='FilePathRunspace')] [Parameter(ParameterSetName='FilePathUri')] [Parameter(ParameterSetName='Session')] [switch] ${AsJob}, [Parameter(ParameterSetName='Uri')] [Parameter(ParameterSetName='FilePathComputerName')] [Parameter(ParameterSetName='FilePathUri')] [Parameter(ParameterSetName='ComputerName')] [Alias('Disconnected')] [switch] ${InDisconnectedSession}, [Parameter(ParameterSetName='FilePathComputerName')] [Parameter(ParameterSetName='ComputerName')] [ValidateNotNullOrEmpty()] [string[]] ${SessionName}, [Parameter(ParameterSetName='FilePathComputerName')] [Parameter(ParameterSetName='Session')] [Parameter(ParameterSetName='FilePathRunspace')] [Parameter(ParameterSetName='ComputerName')] [Parameter(ParameterSetName='FilePathUri')] [Parameter(ParameterSetName='Uri')] [Alias('HCN')] [switch] ${HideComputerName}, [Parameter(ParameterSetName='Session')] [Parameter(ParameterSetName='FilePathRunspace')] [Parameter(ParameterSetName='FilePathComputerName')] [Parameter(ParameterSetName='ComputerName')] [Parameter(ParameterSetName='FilePathUri')] [Parameter(ParameterSetName='Uri')] [string] ${JobName}, [Parameter(ParameterSetName='Session', Mandatory=$true, Position=1)] [Parameter(ParameterSetName='Uri', Mandatory=$true, Position=1)] [Parameter(ParameterSetName='InProcess', Mandatory=$true, Position=0)] [Parameter(ParameterSetName='ComputerName', Mandatory=$true, Position=1)] [Alias('Command')] [ValidateNotNull()] [scriptblock] ${ScriptBlock}, [Parameter(ParameterSetName='InProcess')] [switch] ${NoNewScope}, [Parameter(ParameterSetName='FilePathUri', Mandatory=$true, Position=1)] [Parameter(ParameterSetName='FilePathComputerName', Mandatory=$true, Position=1)] [Parameter(ParameterSetName='FilePathRunspace', Mandatory=$true, Position=1)] [Alias('PSPath')] [ValidateNotNull()] [string] ${FilePath}, [Parameter(ParameterSetName='Uri')] [Parameter(ParameterSetName='FilePathUri')] [switch] ${AllowRedirection}, [Parameter(ParameterSetName='FilePathComputerName')] [Parameter(ParameterSetName='ComputerName')] [Parameter(ParameterSetName='Uri')] [Parameter(ParameterSetName='FilePathUri')] [System.Management.Automation.Remoting.PSSessionOption] ${SessionOption}, [Parameter(ParameterSetName='Uri')] [Parameter(ParameterSetName='ComputerName')] [Parameter(ParameterSetName='FilePathComputerName')] [Parameter(ParameterSetName='FilePathUri')] [System.Management.Automation.Runspaces.AuthenticationMechanism] ${Authentication}, [Parameter(ParameterSetName='FilePathComputerName')] [Parameter(ParameterSetName='ComputerName')] [Parameter(ParameterSetName='Uri')] [Parameter(ParameterSetName='FilePathUri')] [switch] ${EnableNetworkAccess}, [Parameter(ValueFromPipeline=$true)] [psobject] ${InputObject}, [Alias('Args')] [System.Object[]] ${ArgumentList}, [Parameter(ParameterSetName='ComputerName')] [Parameter(ParameterSetName='Uri')] [string] ${CertificateThumbprint}) begin { function Get-ScriptblockFunctions { Param ( [Parameter(Mandatory=$True)] [ValidateNotNull()] [Scriptblock] $Scriptblock ) # Return all user-defined function names contained within the supplied scriptblock $Scriptblock.Ast.FindAll({$args[0] -is [Management.Automation.Language.CommandAst]}, $True) | % { $_.CommandElements[0] } | Sort-Object Value -Unique | ForEach-Object { $_.Value } | ? { ls Function:\$_ -ErrorAction Ignore } } function Get-FunctionDefinition { Param ( [Parameter(Mandatory=$True, ValueFromPipeline=$True)] [String[]] [ValidateScript({Get-Command $_})] $FunctionName ) BEGIN { # We want to output a single string versus an array of strings $FunctionCollection = '' } PROCESS { foreach ($Function in $FunctionName) { $FunctionInfo = Get-Command $Function $FunctionCollection += "function $($FunctionInfo.Name) {`n$($FunctionInfo.Definition)`n}`n" } } END { $FunctionCollection } } try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Invoke-Command', [System.Management.Automation.CommandTypes]::Cmdlet) if($PSBoundParameters['ScriptBlock']) { $FunctionDefinitions = Get-ScriptblockFunctions $ScriptBlock | Get-FunctionDefinition $PSBoundParameters['ScriptBlock'] = [ScriptBlock]::Create($FunctionDefinitions + $ScriptBlock.ToString()) } $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Invoke-Command .ForwardHelpCategory Cmdlet #> }
PowerShellCorpus/GithubGist/mfcollins3_4448042_raw_c0b067b4cc00d3ccc5eb72ff57b393c8350aa11b_gistfile1.ps1
mfcollins3_4448042_raw_c0b067b4cc00d3ccc5eb72ff57b393c8350aa11b_gistfile1.ps1
# This function will accept component GUIDs from the pipeline # and will attempt to find and delete the component records # in the Windows Installer registry hive if they exist. # # For whatever reason, Windows Installer reverses the GUIDs # when creating the component records in the registry. This # function implements the logic for reversing the GUID values # and building the correct registry key for each component. function Remove-WindowsInstallerComponent { $flags = [System.Text.RegularExpressions.RegexOptions]::Compiled -bor [System.Text.RegularExpressions.RegexOptions]::Singleline $regex = new-object System.Text.RegularExpressions.Regex "\{?(?<a>[0-9A-F]{8})-(?<b>[0-9A-F]{4})-(?<c>[0-9A-F]{4})-(?<d>[0-9A-F]{4})-(?<e>[0-9A-F]{12})\}?",$flags foreach ($componentId in $input) { write-host "$componentId" $match = $regex.Match($componentId) if ($match.Success) { $a = $match.Groups["a"].Value.ToCharArray() $b = $match.Groups["b"].Value.ToCharArray() $c = $match.Groups["c"].Value.ToCharArray() $d = $match.Groups["d"].Value.ToCharArray() [char[]]$d1 = $d[0..1] [char[]]$d2 = $d[2..3] $e = $match.Groups["e"].Value.ToCharArray() [char[]]$e1 = $e[0..1] [char[]]$e2 = $e[2..3] [char[]]$e3 = $e[4..5] [char[]]$e4 = $e[6..7] [char[]]$e5 = $e[8..9] [char[]]$e6 = $e[10..11] [System.Array]::Reverse($a) [System.Array]::Reverse($b) [System.Array]::Reverse($c) [System.Array]::Reverse($d1) [System.Array]::Reverse($d2) [System.Array]::Reverse($e1) [System.Array]::Reverse($e2) [System.Array]::Reverse($e3) [System.Array]::Reverse($e4) [System.Array]::Reverse($e5) [System.Array]::Reverse($e6) $d = [System.String]::Format("{0}{1}", (new-object System.String @(,$d1)), (new-object System.String @(,$d2))) $e = [System.String]::Format("{0}{1}{2}{3}{4}{5}", (new-object System.String @(,$e1)), (new-object System.String @(,$e2)), (new-object System.String @(,$e3)), (new-object System.String @(,$e4)), (new-object System.String @(,$e5)), (new-object System.String @(,$e6))) $a = new-object System.String @(,$a) $b = new-object System.String @(,$b) $c = new-object System.String @(,$c) $d = new-object System.String @(,$d) $e = new-object System.String @(,$e) $key = "hklm:\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\$a$b$c$d$e" if (test-path $key) { remove-item $key -Recurse -ErrorAction Continue } } } }
PowerShellCorpus/GithubGist/pkirch_9a93bf2306e2d5419623_raw_7dcd77b3faae3b4aa1af77a47a7985a24d8df14d_GetAzureSubscription.ps1
pkirch_9a93bf2306e2d5419623_raw_7dcd77b3faae3b4aa1af77a47a7985a24d8df14d_GetAzureSubscription.ps1
Get-AzureSubscription <# Output SubscriptionId : c6244819-a8d6-4279-b492-4a47f4301c54 SubscriptionName : Azure MSDN - pkirchner Environment : AzureCloud SupportedModes : AzureServiceManagement DefaultAccount : 914193B3332ED5FFF26CECABB522B42AA08EDB0E Accounts : {914193B3332ED5FFF26CECABB522B42AA08EDB0E, 8BC857EA6D9DA18CCEFB2E3DD820A1ECD43C8060} IsDefault : True IsCurrent : True CurrentStorageAccountName : pkmsft   SubscriptionId : d1c2d82d-11f3-4454-950b-784bf663c0c6 SubscriptionName : MSFT pkirch Environment : AzureCloud SupportedModes : AzureServiceManagement DefaultAccount : A6D71DD42B1EBEFD3FF5EE501970C8C05847CCF5 Accounts : {A6D71DD42B1EBEFD3FF5EE501970C8C05847CCF5} IsDefault : False IsCurrent : False CurrentStorageAccountName : testlabclient #>
PowerShellCorpus/GithubGist/janikvonrotz_6866018_raw_9828f76124bfcee2685bed93c7f356499d9353c8_Get-ContentOfMultipleConfigurationFiles.ps1
janikvonrotz_6866018_raw_9828f76124bfcee2685bed93c7f356499d9353c8_Get-ContentOfMultipleConfigurationFiles.ps1
# Get Mail Error Report Configuration $MailConfigs = Get-ChildItem -Path $PSconfigs.Path -Filter $PSconfigs.Mail.Filter -Recurse | %{[xml]$(get-content $_.FullName)} | %{$_.Content.Mail | where{$_.Name -eq $PSconfigs.Mail.ErrorClass}} | select -first 1
PowerShellCorpus/GithubGist/bat2001_6232438_raw_ddac20a65bf965a4dda504cd6a793c91b2f7c075_gistfile1.ps1
bat2001_6232438_raw_ddac20a65bf965a4dda504cd6a793c91b2f7c075_gistfile1.ps1
[System.Reflection.Assembly]::loadwithPartialName("Microsoft.BizTalk.ExplorerOM") ## - Force 32-bit mode, BizTalk.ExplorerOM does NOT support 64-bit mode if ($env:Processor_Architecture -ne "x86") { write-warning "Running x86 PowerShell..." if ($myInvocation.Line) { &"$env:WINDIR\syswow64\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile $myInvocation.Line } else { &"$env:WINDIR\syswow64\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -file "$($myInvocation.InvocationName)" $args } exit $lastexitcode }
PowerShellCorpus/GithubGist/guitarrapc_1d903d0b7913569adbb3_raw_bbf05c35705861c4372bc27db1c66fe0262aed6c_CanNotEvaluate.ps1
guitarrapc_1d903d0b7913569adbb3_raw_bbf05c35705861c4372bc27db1c66fe0262aed6c_CanNotEvaluate.ps1
"{ {0} }" -f $hoge.hoge <# Error formatting a string: Input string was not in a correct format.. At line:1 char:5 + "{ + ~~ + CategoryInfo : InvalidOperation: ({ {0} }:String) [], RuntimeException + FullyQualifiedErrorId : FormatError #>
PowerShellCorpus/GithubGist/mikeplate_4351975_raw_e9caa0d74430f785b46af6716f59b0c6696bbafb_gistfile1.ps1
mikeplate_4351975_raw_e9caa0d74430f785b46af6716f59b0c6696bbafb_gistfile1.ps1
# List all users $filter = "(&(objectClass=user)(objectCategory=person))" $users = ([adsiSearcher]$filter).findall() $users | %{ $_.Properties['displayname'] } # Sort $users | %{ $_.Properties['displayname'] } | sort # Filter by part of name $users | %{ $_.Properties['displayname'] } | where { $_ -match "John" }
PowerShellCorpus/GithubGist/jamessantiago_52a8bf8b080461609023_raw_c71af878c886004add5b0ea1b67e9004de05fbaf_SetBackground.ps1
jamessantiago_52a8bf8b080461609023_raw_c71af878c886004add5b0ea1b67e9004de05fbaf_SetBackground.ps1
#expected to be executed from a folder with wallpapers in the format of BackGroundWIDTHxHEIGHT.jpg (e.g. Background1920x1200.jpg) $consoleDebug = $true $remoteDebug = $false $LogFile = "$($env:temp)\Wallpaper_$([int]((get-date -UFormat "%s") / 86400)).log" Function LogMessage($message) { if ($consoleDebug) { write-host $message } if ($remoteDebug) { Add-Content $LogFile -value "$($(date).ToString("ddMMMyyy HH:mm:ss.fff")):`t`t$message" -ea 0 } } #code to force wallpaper to change Add-Type @" using System; using System.Runtime.InteropServices; using Microsoft.Win32; namespace Wallpaper { public class Setter { [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni); public static void SetWallpaper(string path) { SystemParametersInfo(20, 0, path, 0x01 | 0x02); } } } "@ #set directory for manual run nonsense [system.io.directory]::SetCurrentDirectory($pwd.ProviderPath) #default resolution $width = 1600 $height = 1200 try { $monitor = Get-WmiObject win32_desktopmonitor $width = $monitor.ScreenWidth $height = $monitor.ScreenHeight } catch { #it's ok, just continue with defaults LogMessage "Failed to get native resolution: $($_.exception.message)" } #aspect needed to determine closest matches $aspect = $width/$height LogMessage "width: $width" LogMessage "height: $height" LogMessage "aspect: $aspect" LogMessage "Copying backgrounds to lockscreen" cp *.jpg $env:SystemRoot\SysNative\oobe\info\backgrounds -Force LogMessage "Backgrounds copied" #default to use if no exact or closest same aspect is matched $default = "Background1600x1200.jpg" #default for portrait backgrounds e.g. 960/1280 if ($aspect -lt 1) { $default = "Background1024x1280.jpg" } #distance for closest resolution $distance = [int]::maxvalue #iterate through all backgrounds to find exact or closest match ls *.jpg |% { #extract resolution from file name $res = $_.Name -Replace "Background", "" -replace ".jpg", "" $resolution = $res -split "x" $w = $resolution[0] $h = $resolution[1] $a = $w/$h if ($width -eq $w -and $height -eq $h) #exact match { $default = $_.Name $distance = 0 } elseif ($aspect -eq $a) { #matches aspect, find distance $d = [math]::abs($width - $w) + [math]::($height - $h) if ($d -lt $distance) #distance is closer than before { $distance = $d $default = $_.Name } } } LogMessage "Closest resolution detected is $default at distance of $distance" LogMessage "Watermarking background with computer info" try { $image = new-object System.Drawing.Bitmap $pwd\$default $g = [System.Drawing.Graphics]::FromImage($image) $g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic $g.DrawString($(hostname), $(New-Object System.Drawing.Font "verdana", 32), ` [System.Drawing.SystemBrushes]::HighlightText, $image.Width - 500, $image.Height - 160) $mac = (Get-WmiObject win32_networkadapterconfiguration -Namespace "root\CIMV2" |? {$_.IPEnabled -eq "True"}).MacAddress if ($mac.Count -gt 0) { $g.DrawString($mac[0], $(New-Object System.Drawing.Font "verdana", 32), ` [System.Drawing.SystemBrushes]::HighlightText, $image.Width - 500, $image.Height - 100) } $image.Save("$pwd\Background_Temp.jpg", ([System.Drawing.Imaging.ImageFormat]::Jpeg)) $default = "BackGround_Temp.jpg" LogMessage "Watermark applied" } Catch { LogMessage "Failed to apply watermark: $($_.message.exception)" } LogMessage "Copying to desktop background" cp $default $env:SystemRoot\SysNative\oobe\info\backgrounds -force cp $default $env:SystemRoot\Web\Wallpaper\theWallpaper.jpg -force try { $user = (get-wmiobject win32_computerscreen -ea 0).username $user = $(user -split "\\")[1] if (test-path $env:SystemDrive\Users\$user\AppData\Roaming\Microsoft\Windows\Themes) { cp $default $env:SystemDrive\Users\$user\AppData\Roaming\Microsoft\Windows\Themes\TranscodedWallpaper.jpg -force [Wallpaper.Setter]::SetWallpaper("$env:SystemRoot\Web\Wallpaper\theWallpaper.jpg") LogMessage "Set wallpaper for logged in user $user" } } catch {} LogMessage "Complete"
PowerShellCorpus/GithubGist/mefellows_9a67b17a571fcffa1bd0_raw_fd41f7383568ec492744a315fa1e502dbbe854fc_gistfile1.ps1
mefellows_9a67b17a571fcffa1bd0_raw_fd41f7383568ec492744a315fa1e502dbbe854fc_gistfile1.ps1
#$Shell.WindowTitle="WinOps Matt" set-executionpolicy unrestricted new-item alias:subl -value 'C:\Program Files\Sublime Text 3\sublime_text.exe' new-item alias:ll -value 'ls'
PowerShellCorpus/GithubGist/kouphax_1150017_raw_4a30801c74dedbd083d3e46c8b4a2adf8f427430_default.ps1
kouphax_1150017_raw_4a30801c74dedbd083d3e46c8b4a2adf8f427430_default.ps1
# ----------------------------------------------------------------------------- # H E L P E R F U N C T I O N S # ----------------------------------------------------------------------------- function Write-LineBreak(){ Write-Host "----------------------------------------------------------------------" }
PowerShellCorpus/GithubGist/catyun_6393348_raw_1bf416251759be865217155d20ad58b5543f2a45_init.ps1
catyun_6393348_raw_1bf416251759be865217155d20ad58b5543f2a45_init.ps1
$content = Get-Content -path d:\context.sh $context = @{} # Read All Context Variables from context.sh foreach ($line in $content) { if ($line[0] -ne '#') { $var = $line.split('=') if ($var[1] -ne $null) { #remove the " " of variables $var[1] = $var[1] -replace '^"|"$',"" $context.Set_Item($var[0], $var[1]) } } } #Setup the IP, gateway, netmask, dns if ($context.Get_Item("IP_PUBLIC") -ne $null) { netsh interface ip set address "°Ï°ì³s½u" static $context.Get_Item("IP_PUBLIC") $context.Get_Item("NETMASK") $context.Get_Item("GATEWAY") 1 netsh interface ip set dns "°Ï°ì³s½u" static 140.110.16.1 netsh interface ip add dns "°Ï°ì³s½u" 168.95.192.1 2 } #Setup Administrator Password if ($context.Get_Item("ROOT_PASSWD") -ne $null) { $password = $context.Get_Item('ROOT_PASSWD') net user Administrator "`"$password`"" } #New Account and Password if ($context.Get_Item("USERNAME") -ne $null) { $password = $context.Get_Item('USER_PASSWD') net user $context.Get_Item("USERNAME") "`"$password`"" /add net localgroup administrators $context.Get_Item("USERNAME") /add } #Change Computer Name if ($context.Get_Item("HOSTNAME") -ne $null) { $hostname = $context.Get_Item('HOSTNAME') (get-wmiobject -class win32_ComputerSystem).Rename("`"$hostname`"") }
PowerShellCorpus/GithubGist/guitarrapc_e17fa71083847c9ba78d_raw_7531bd7b3fb08a7a50f0c53935f492e5afe67368_PowershellConstructor.ps1
guitarrapc_e17fa71083847c9ba78d_raw_7531bd7b3fb08a7a50f0c53935f492e5afe67368_PowershellConstructor.ps1
######################## # Constructor Call check ######################## class Hoge { Hoge() { Write-Host "constuctor called" } } [Hoge]::new() <# constuctor called #> ######################## # Initialization ######################## class MyClass { [string]$name [int]$age MyClass() { $name = "" $age = 0 } } [MyClass]::new() <# name age ---- --- 0 #> ######################## # This not supported ######################## class MyClass { [string]$name; MyClass([string]$name) { $name = $name #this not yet usable } } [MyClass]::new("hoge") <# name ---- #> ######################## # Constructor can overload ######################## class MyClass { [string]$name [int]$age MyClass() { $name = "" $age = 0 } MyClass([string]$hoge, [int]$fuga) { $name = $hoge $age = $fuga } } [MyClass]::new <# OverloadDefinitions ------------------- MyClass, powershell, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null new() MyClass, powershell, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null new(string hoge, int fuga) #> [MyClass]::new("hoge", 10) <# name age ---- --- hoge 10 #>
PowerShellCorpus/GithubGist/amatashkin_6593347_raw_766219eaa7927db56cbb4ee49289f5399a6c1426_backup-computer.ps1
amatashkin_6593347_raw_766219eaa7927db56cbb4ee49289f5399a6c1426_backup-computer.ps1
#script will backup computer to backup location clear $date = get-date -UFormat %Y-%m-%d $comp = gc env:computername $share = (Get-Location).Drive.Name + ':' $folder = $share + '\WindowsImageBackup\' $log = $folder + $date + '_' + $comp + '.log' # Create backup folder try { if ( ! (Test-Path -Path $folder ) ){ New-Item -Path $folder -ItemType Directory -ErrorAction Stop } } catch [exception] { $result = "$result <br> Computer $comp FAILED to create folder <br> <br>" } # Create log file try { if ( ! (Test-Path -Path $log ) ){ New-Item -Path $log -ItemType File -ErrorAction Stop } } catch [exception] { $result = "$result <br> Computer $comp FAILED to create log file <br> <br>" } # Backup PC $start = Get-Date $process = start -Wait wbadmin.exe -ArgumentList "start backup -backuptarget:$share -include:C: -quiet" -PassThru -NoNewWindow -RedirectStandardOutput $log $code = $process.exitcode if ($code -eq 0 ){ $end = Get-Date $result = "$result backup complete on $comp, user $user <br> Started: $start <br> Ended: $end <br> <br>" $status = "good" # start net -ArgumentList "use i: /delete /Y" -NoNewWindow } else { $end = Get-Date $result= "$result Backup Failed on $comp, <br> Started: $start <br> Ended: $end <br> <br>" $status = "BAD" } $loghtmlfile = $log + '.html' $File = Get-Content $log $FileLine = @() Foreach ($Line in $File) { $MyObject = New-Object -TypeName PSObject Add-Member -InputObject $MyObject -Type NoteProperty -Name backupstatus -Value $Line $FileLine += $MyObject } $FileLine | ConvertTo-Html -Property backupstatus | Out-File $loghtmlfile $loghtml = gc $loghtmlfile $result = "$result $loghtml"
PowerShellCorpus/GithubGist/miwaniza_9041042_raw_fb97311756dccedc091f358af6ff9f19c6ffcf65_Login-VaultServer-Cmd_Ed.ps1
miwaniza_9041042_raw_fb97311756dccedc091f358af6ff9f19c6ffcf65_Login-VaultServer-Cmd_Ed.ps1
param ($help,$VServer,$VVault,$VUser,$VPass,$VOut) $WebServicesPath2014="C:\Program Files (x86)\Autodesk\Autodesk Vault 2014 SDK\bin\Autodesk.Connectivity.WebServices.dll" if ($help) { "Login Vault with read-only connection`n" "Usage:" " Login-VaultServer.ps1 -Vserver <server address> -VVault <vault name> -VUser <username> [-VPass <password>]`n" "Arguments:" " -Vserver Autodesk Vault server name. In any format: IP, DNS, IP:port, DNS:port." " -VVault Vault name." " -VUser Registered user name." " -VPass Password." "`nExample:" " powershell .\Export-FileCategories.ps1 -Vserver localhost -VVault Vault -VUser Administrator -VPass pass`n" exit } else{ if (!$VServer -or !$VVault -or !$VUser){"Invalid arguments. Use 'help' argument for more help" exit} } try { "Trying to find Vault 2014 dll" Add-Type -Path $WebServicesPath2014 #Vault 2014 } Catch { "No dlls were found. Edit script or contact author." exit } "Found - executing" try{ $cred = New-Object Autodesk.Connectivity.WebServicesTools.UserPasswordCredentials ($VServer,$VVault,$VUser,$VPass,$true) $webSvc = New-Object Autodesk.Connectivity.WebServicesTools.WebServiceManager ($cred) Write-Output $webSvc } Catch {"Login failed" exit}
PowerShellCorpus/GithubGist/alias1_6101928_raw_77a63a62f8b3c602254633c0e04e6f6aecdcaf6a_Powershell_Reverse-SecureString.ps1
alias1_6101928_raw_77a63a62f8b3c602254633c0e04e6f6aecdcaf6a_Powershell_Reverse-SecureString.ps1
# Reverse-SecureString # Version: 1.0 (20130729) # Created By: Glenn 'devalias' Grant (http://devalias.net) # License: The MIT License (MIT) - Copyright (c) 2013 Glenn 'devalias' Grant (see http://choosealicense.com/licenses/mit/ for full license text) function Reverse-SecureString([string]$secureString,[string]$key) { $objSecString=ConvertTo-SecureString -String $secureString -Key ([Byte[]]$key.Split(" ")) $secString=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($objSecString) $plaintext=[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($secString) return $plaintext } # Example SecureString decryption $password = "76492d1116743f0423413b16050a5345MgB8AFAAVwBiAGkAegBjAEcANQA5AEMAOABVAFoAUQBoADMAZAA1AEUAcgBGAHcAPQA9AHwAYgAxAGUAYwA0AGQA YwBkADUANQAwAGUAYQBmADYAMwA5AGEANwAyADAAMwBmADAANwA3AGUANgA3ADYAYgA0AGIANgA4ADYAZAA3ADkAZgBkAGYAMgAzADcAMQA2ADkAYgA3AGMA YwA0AGUAZQA1AGIANAA5ADEAZABjADQAZQA5ADgANQAxADUAYwBmADgAZQBjADMAMgBmADgANgBhADAANQBlADAANgBkAGIAZABlAGMAZAA2ADcAMwBmAGYA YwA5ADMAZQAwADYAZAA5AGMAMwAyAGUANgAyAGUAMAA3ADcAYgBkADIAYQAzAGIAOAA3ADQAMwA2ADIAMAA2AA==" $key = "114 138 230 113 215 43 58 173 155 129 196 29 105 162 10 25 187 79 18 221 142 29 155 43 28 20 19 40 103 83 110 240" $passPlaintext = Reverse-SecureString "$password" "$key" Write-Host $passPlaintext # This should output: TotallySecurePasswordLol!
PowerShellCorpus/GithubGist/jorke_6879224_raw_30567258f00887f0cf013a03059e6d5a29f06ee7_ses.ps1
jorke_6879224_raw_30567258f00887f0cf013a03059e6d5a29f06ee7_ses.ps1
Send-MailMessage -From <from> -to <to> -subject <subject> -SmtpServer email-smtp.us-east-1.amazonaws.com -Credential $(New-Object System.Management.Automation.PSCredential -argumentlist <AWS_ACCESS_KEY>, $(ConvertTo-SecureString -AsPlainText -String <AWS_SECRET_KEY> -Force) ) -UseSsl -Port 587
PowerShellCorpus/GithubGist/rogasawara_6916476_raw_a9d960e07b148321145371bf057f06a9e6304654_memo.ps1
rogasawara_6916476_raw_a9d960e07b148321145371bf057f06a9e6304654_memo.ps1
# いろいろなな処理の検証 # 開始時刻 echo "処理を開始します" Get-Date -Format "yyyy/MM/dd HH時mm分ss秒" | echo #変数準備 $out = @() $conv = @{} #カレントディレクトリ取得 $path = (Split-Path ( & { $myInvocation.ScriptName } ) -parent) # 移動 cd $path/HOGE # ファイル名取得しリスト化 $hoge = @() # 以下の拡張子を含むものは対象外 $hoge = Get-ChildItem -exclude *.exe,*.cmd,*.com,*.dat,*.bat,*.js,*.lnk,*.pif,*.vbs,*.scr -Name
PowerShellCorpus/GithubGist/jakeballard_9019696_raw_6d5dac19e0067c27ad742a4bfeefc12b952e3c0f_Get-TSMClientSchedule.ps1
jakeballard_9019696_raw_6d5dac19e0067c27ad742a4bfeefc12b952e3c0f_Get-TSMClientSchedule.ps1
function Get-TSMClientSchedule { Param( [Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true)] $ComputerName ) PROCESS { if ($ComputerName -is [Array]) { $ComputerName | ForEach-Object { Get-TSMSchedule -ComputerName $_ } } else { $LogFile = Join-Path "\\$ComputerName\" 'C$\Program Files\Tivoli\TSM\baclient\dsmsched.log' Write-Debug $LogFile if (test-path $LogFile) { $Pattern = "^(?<LastCheckin>.{19})\sServer Window Start:\s*(?<ScheduleTime>\d\d:\d\d:\d\d) on (?<ScheduleDate>\d\d/\d\d/\d\d\d\d).*" if (@(Select-String -Path $LogFile -Pattern '.{20}Server Window Start:')[-1].line -match $Pattern) { $Properties = @{ 'ComputerName' = $ComputerName 'LastCheckin' = Get-Date $Matches.LastCheckin 'Schedule' = Get-Date $( $Matches.ScheduleDate + " " + $Matches.ScheduleTime ) } Write-Output $(New-Object -TypeName PSObject -Property $Properties) } } } } #End PROCESS } #End Function #Get-TSMClientSchedule
PowerShellCorpus/GithubGist/bblade_4713294_raw_4777f8f97145bba4127065e9373cb6e415fd1038_Purge-Old-Items.ps1
bblade_4713294_raw_4777f8f97145bba4127065e9373cb6e415fd1038_Purge-Old-Items.ps1
# Set variables $HomeFolder = "C:\TEMP" $KeepDays = "-1" $Date = Get-Date $PurgeDays = $Date.AddDays($KeepDays) # Execute commands Get-ChildItem $HomeFolder -Recurse | ` Where-Object { $_.CreatedTime -lt $PurgeDays } | ` Remove-Item -Recurse
PowerShellCorpus/GithubGist/uncas_1931516_raw_c7768a0e9d3c663035915f2d5304738237e32d90_profile.ps1
uncas_1931516_raw_c7768a0e9d3c663035915f2d5304738237e32d90_profile.ps1
# My preferred prompt for Powershell. # Displays git branch (and stats) when inside a git repository. # See http://gist.github.com/180853 for gitutils.ps1. . (Resolve-Path D:/Users/ole/Documents/WindowsPowershell/gitutils.ps1) function prompt { $userLocation = $env:username + ' ' + $pwd $host.UI.RawUi.WindowTitle = $userLocation Write-Host($pwd) -nonewline -foregroundcolor Green if (isCurrentDirectoryGitRepository) { $currentBranch = gitBranchName Write-Host(' (' + $currentBranch + ')') -nonewline -foregroundcolor Yellow } Write-Host('>') -nonewline -foregroundcolor Green return " " }
PowerShellCorpus/GithubGist/kouphax_1150018_raw_c5d57926c655e4bd581efb8004a96625213a6c88_default.ps1
kouphax_1150018_raw_c5d57926c655e4bd581efb8004a96625213a6c88_default.ps1
# Set the default framework (3.5 by default) $framework = '4.0'
PowerShellCorpus/GithubGist/mpicker0_5680072_raw_88756c9d6cf306e0b0824a6cd98b917f06a3ee03_Create-WebConfigTransform.ps1
mpicker0_5680072_raw_88756c9d6cf306e0b0824a6cd98b917f06a3ee03_Create-WebConfigTransform.ps1
<# .SYNOPSIS Create a configuration transformation .DESCRIPTION This script runs an ASP.NET configuration transformation, given a source configuration and transformation file. MSBuild.exe is assumed to be in the path, and Visual Studio 2012 should be installed. Modify the path to Microsoft.Web.Publishing.Tasks.dll if a different version of Visual Studio is installed. .PARAMETER SourceFile The source file to use for transformations .PARAMETER TransformFile The transformations to apply to the source file .PARAMETER OutputFile Where to write the resulting output .EXAMPLE Create-WebConfigTransform -SourceFile C:\path\to\project\Web.config -TransformFile C:\path\to\project\Web.Debug.config -OutputFile c:\temp\transformed.xml .LINK http://msdn.microsoft.com/en-us/library/dd465326.aspx #> param( [Parameter(Mandatory=$true)] [ValidateScript({Test-Path $_})] [string]$SourceFile, [Parameter(Mandatory=$true)] [ValidateScript({Test-Path $_})] [string]$TransformFile, [Parameter(Mandatory=$true)] [string]$OutputFile ) # set up output filenames $WorkDir = Join-Path ${env:temp} "work-${PID}" $SourceWork = Join-Path $WorkDir (Split-Path $SourceFile -Leaf) $TransformWork = Join-Path $WorkDir (Split-Path $TransformFile -Leaf) $OutputWork = Join-Path $WorkDir (Split-Path $OutputFile -Leaf) # create a working directory and copy files into place New-Item -Path ${WorkDir} -Type Directory Copy-Item $SourceFile $WorkDir Copy-Item $TransformFile $WorkDir # write the project build file $BuildXml = @" <Project ToolsVersion="4.0" DefaultTargets="TransformWebConfig" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <UsingTask TaskName="TransformXml" AssemblyFile="`$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.Tasks.dll"/> <Target Name="TransformWebConfig"> <TransformXml Source="${SourceWork}" Transform="${TransformWork}" Destination="${OutputWork}" StackTrace="true" /> </Target> </Project> "@ $BuildXmlWork = Join-Path $WorkDir "build.xml" $BuildXml | Out-File $BuildXmlWork # call msbuild & MSBuild.exe $BuildXmlWork # copy the output to the desired location Copy-Item $OutputWork $OutputFile # clean up Remove-Item $WorkDir -Recurse -Force
PowerShellCorpus/GithubGist/zulucoda_81cd751f67a8cbba3605_raw_91ba95e503bd00ce01c0fce3eae22f326ffa0e52_create-web-application-in-iis.ps1
zulucoda_81cd751f67a8cbba3605_raw_91ba95e503bd00ce01c0fce3eae22f326ffa0e52_create-web-application-in-iis.ps1
<# .SYNOPSIS create-web-application - Automatic website creation. .DESCRIPTION Allows you to create a website and its ApplicationPool. .NOTES File Name : create-web-application.ps1 Author : Muzikayise Flynn Buthelezi - muzi@mfbproject.co.za Copyright : MFBproject mfbproject.co.za .EXAMPLE PS D:\>create-web-application.ps1 -SiteName TESTSITE -Port 8080 -Environment PREPROD -Runtime v4.0 -Pipeline Classic Creates a website named 'TESTSITE-PREPROD', listening on the TCP8080 port, responding to 'http://*' (default value). The associated ApplicationPool 'TESTSITE' running with the identity 'NetworkService' (default value), v4.0 .NET Framework managed runtime and 'Classic' managed pipeline mode. #> Param( [Parameter(Mandatory=$true, HelpMessage="You must provide a display name for the website.")] $SiteName = "testsite", $Port = "8080", #[ValidatePattern("([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?")] $HostName = "", [ValidateSet("PROD", "PREPROD", "INTEG", "QUAL", "DEV")] $Environment = "PROD", [ValidateSet("0", "1", "2", "3", "4")] $Identity = "2", [ValidateSet("v1.1", "v2.0", "v4.0")] [string]$Runtime = "v4.0", [ValidateSet("Classic", "Integrated")] [string]$Pipeline = "Integrated" ) switch ($Identity) { 0 {$FullIdentity = "LocalSystem"} 1 {$FullIdentity = "LocalService"} 2 {$FullIdentity = "NetworkService"} 3 {$FullIdentity = "SpecificUser"} 4 {$FullIdentity = "ApplicationPoolIdentity"} } function main(){ Write-Host "deploy web application" if (LoadIIS7Module -eq $true) { Write-Verbose "Add a New IIS 7.0 Web Site..." Add-IIS7Website $SiteName $Port $HostName $Environment $Identity $Runtime $Pipeline } else { Write-Host "IIS7 WebAdministration Snapin or Module not found." Write-Host "Please consult the Microsoft documentation for installing the IIS7 PowerShell cmdlets" } } function Check-IfWebsiteExists($SiteName, $Environment){ $SiteName += "-$Environment" if ((Test-Path -path "IIS:\Sites\$SiteName") -ne $false) { return $false } return $true } function LoadIIS7Module () { $ModuleName = "WebAdministration" $ModuleLoaded = $false $LoadAsSnapin = $false if ((Get-Module -ListAvailable | ForEach-Object {$_.Name}) -contains $ModuleName) { Import-Module $ModuleName if ((Get-Module | ForEach-Object {$_.Name}) -contains $ModuleName) { $ModuleLoaded = $true } else { $LoadAsSnapin = $true } } elseif ((Get-Module | ForEach-Object {$_.Name}) -contains $ModuleName) { $ModuleLoaded = $true } else { $LoadAsSnapin = $true } if ($LoadAsSnapin) { if ((Get-PSSnapin -Registered | ForEach-Object {$_.Name}) -contains $ModuleName) { Add-PSSnapin $ModuleName if ((Get-PSSnapin | ForEach-Object {$_.Name}) -contains $ModuleName) { $ModuleLoaded = $true } } elseif ((Get-PSSnapin | ForEach-Object {$_.Name}) -contains $ModuleName) { $ModuleLoaded = $true } else { $ModuleLoaded = $false } } return $ModuleLoaded } function Read-Choice { Param( [System.String]$Message, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.String[]]$Choices, [System.Int32]$DefaultChoice = 1, [System.String]$Title = [string]::Empty ) [System.Management.Automation.Host.ChoiceDescription[]]$Poss = $Choices | ForEach-Object { New-Object System.Management.Automation.Host.ChoiceDescription "&$($_)", "Sets $_ as an answer." } $Host.UI.PromptForChoice($Title, $Message, $Poss, $DefaultChoice) } function Select-IPAddress { [cmdletbinding()] Param( [System.String]$ComputerName = 'localhost' ) $IPs = Get-WmiObject -ComputerName $ComputerName -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled='True'" | ForEach-Object { $_.IPAddress } | Where-Object { $_ -match "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" } if($IPs -is [array]){ Write-Host "`nServer $ComputerName uses these IP addresses:" $IPs | ForEach-Object {$Id = 0} {Write-Host "${Id}: $_" -ForegroundColor Yellow; $Id++} $IPs[(Read-Choice -Message "`nChoose an IP Address" -Choices (0..($Id - 1)) -DefaultChoice 0)] } else{$IPs} } function Add-IIS7Website($SiteName, $Port, $HostName, $Environment, $Identity, $Runtime, $Pipeline) { Write-Host "`n**********************************************************" -ForegroundColor Yellow Write-Host "*`t`tAutomatic Website Creation" -ForegroundColor Yellow Write-Host "*" -ForegroundColor Yellow Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Parameters" Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Website Name (-SiteName):`t`t" -nonewline; Write-Host "$SiteName" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Website Port (-Port):`t`t`t" -nonewline; Write-Host "$Port" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Website Hostname (-Hostname):`t`t" -nonewline; Write-Host "$HostName" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Website Environment (-Environment):`t" -nonewline; Write-Host "$Environment" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " AppPool Identity (-Identity):`t`t" -nonewline; Write-Host "$FullIdentity ($Identity)" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Managed Runtime (-Runtime):`t`t" -nonewline; Write-Host "v$Runtime" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Managed Pipeline Mode (-Pipeline):`t" -nonewline; Write-Host "$Pipeline" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow Write-Host "**********************************************************" -ForegroundColor Yellow if ((Check-IfWebsiteExists $SiteName $Environment) -eq $false) { Write-Host "Website $SiteName already created!" -ForegroundColor Yellow return $false } if ($Identity -eq "3") { $AppPoolUser = Read-Host "`nPlease provide username for the ApplicationPool identity" $AppPoolPwd = Read-Host "Please provide the password for '$AppPoolUser' user" -AsSecureString } $ChosenIP = Select-IPAddress Write-Host "`nThe selected IP address is: $ChosenIP`n" -ForegroundColor DarkGreen $SiteName += "-$Environment" # Create the website directory Write-Host "Creating application directory" -ForegroundColor Yellow $WWWPath = "C:\inetpub\wwwroot" $SitePath = "$WWWPath" + "\" + "$SiteName" if (!(Test-Path $SitePath)) { New-Item -ItemType Directory -Path $SitePath } # Creates the website logfiles directory Write-Host "Creating application logfiles directory" -ForegroundColor Yellow $LogsPath = "C:\inetpub\logs\LogFiles" $SiteLogsPath = "$LogsPath" + "\" + "$SiteName" if (!(Test-Path $SiteLogsPath)) { New-Item -ItemType Directory -Path $SiteLogsPath } Import-Module "WebAdministration" -ErrorAction Stop if ($Pipeline -eq "Integrated") {$PipelineMode = "0"} else {$PipelineMode = "1"} # Creates the ApplicationPool Write-Host "Creating website application pool" -ForegroundColor Yellow New-WebAppPool –Name $SiteName -Force Set-ItemProperty ("IIS:\AppPools\" + $SiteName) -Name processModel.identityType -Value $Identity if ($Identity -eq "3") { Set-ItemProperty ("IIS:\AppPools\" + $SiteName) -Name processModel.username -Value $AppPoolUser Set-ItemProperty ("IIS:\AppPools\" + $SiteName) -Name processModel.password -Value $AppPoolPwd } Set-ItemProperty ("IIS:\AppPools\" + $SiteName) -Name managedRuntimeVersion -Value $Runtime Set-ItemProperty ("IIS:\AppPools\" + $SiteName) -Name managedPipelineMode -Value $PipelineMode # Creates the website Write-Host "Creating website" -ForegroundColor Yellow New-Website –Name $SiteName -Port $Port –HostHeader $HostName -IPAddress $ChosenIP -PhysicalPath $SitePath -ApplicationPool $SiteName -Force Set-ItemProperty ("IIS:\Sites\" + $SiteName) -Name logfile.directory -Value $SiteLogsPath Start-WebAppPool -Name $SiteName Start-WebSite $SiteName Write-Host "Website $SiteName created!" -ForegroundColor DarkGreen } main
PowerShellCorpus/GithubGist/tathamoddie_448023_raw_31fe02e3d1ec49547e7aec243746f5976ba10d26_Publish-Version.ps1
tathamoddie_448023_raw_31fe02e3d1ec49547e7aec243746f5976ba10d26_Publish-Version.ps1
#requires -Version 2 [CmdletBinding()] param ( $VersionIdentifier ) $ErrorActionPreference = "Stop" Set-PSDebug -Strict $PSScriptFilePath = (Get-Item $MyInvocation.MyCommand.Path).FullName $PSScriptRoot = Split-Path $PSScriptFilePath -Parent $StaticRoot = Split-Path $PSScriptRoot -Parent if ($VersionIdentifier -eq $null) { Write-Verbose "No version identifier was supplied as an argument to this script so it will be determined automatically via TFS." $TfsSnapin = Get-PSSnapin | Where-Object { $_.Name -eq 'Microsoft.TeamFoundation.PowerShell' } if (-not $TfsSnapin) { Add-PSSnapin Microsoft.TeamFoundation.PowerShell } $LatestChangesetId = (Get-TfsItemHistory -HistoryItem . -Recurse -StopAfter 1).ChangesetId; $VersionIdentifier = "v" + $LatestChangesetId if (-not $TfsSnapin) { Remove-PSSnapin Microsoft.TeamFoundation.PowerShell } } Write-Verbose "Using version identifier '$VersionIdentifier'." $BaseRoot = Join-Path $StaticRoot -ChildPath Base # eg /Static/Base/ $VersionedRoot = Join-Path $StaticRoot -ChildPath $VersionIdentifier # eg /Static/v1234/ if (Test-Path $VersionedRoot -PathType Container) { Remove-Item $VersionedRoot -Force -Recurse } Copy-Item $BaseRoot -Destination $VersionedRoot -Recurse Set-Content (Join-Path $StaticRoot -ChildPath ActiveVersion.config) -Value $VersionIdentifier
PowerShellCorpus/GithubGist/pkskelly_e94c9fb69511de35c6db_raw_a479b66f9eb6f62e02f6125889fa79a7feb35b05_Install-DevTools.ps1
pkskelly_e94c9fb69511de35c6db_raw_a479b66f9eb6f62e02f6125889fa79a7feb35b05_Install-DevTools.ps1
iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) ##Developer Tools #cinst sysinternals #cinst 7zip cinst diffmerge #cinst winmerge #cinst fiddler #cinst paint.net #cinst githubforwindows cinst npm cinst ilspy ## Languages #cinst python ##Editors #cinst SublimeText3 #cinst SublimeText3.PackageControl #cinst WebStorm ##SharePoint Tools and Utils #cinst SharePointManager2013 #cinst ulsviewer #cinst CAMLDesigner2013 #cinst SearchQueryTool ##Databases #cinst mongodb #cinst robomongo
PowerShellCorpus/GithubGist/dfinke_8127413_raw_e789ce79fb7bd06fc0231be99a6a8a711f5d38e9_ConvertTo-PigLatin.ps1
dfinke_8127413_raw_e789ce79fb7bd06fc0231be99a6a8a711f5d38e9_ConvertTo-PigLatin.ps1
function ConvertTo-PigLatin { param( [Parameter(ValueFromPipeline)] [string[]]$string ) Process { $r += $(foreach($s in $string) { if(Write-Output b c d f g h j k l m n p q r s t v w x y z -eq $s[0]) { "{0}{1}ay" -f ($s[1..($s.length)] -join ''), $s[0] } else { $s + "way" } }) + ' ' } End {$r.Trim()} }
PowerShellCorpus/GithubGist/gravejester_5041912_raw_48ffa67143e9dd018c82914916ac64d575f65e37_Trace-Route.ps1
gravejester_5041912_raw_48ffa67143e9dd018c82914916ac64d575f65e37_Trace-Route.ps1
function Trace-Route { <# .SYNOPSIS Trace the route between source computer and a target machine. .DESCRIPTION Trace the route between source computer and a target machine. .EXAMPLE Trace-Route Computer01 Perform trace route to Computer01 .EXAMPLE Trace-Route -Target www.microsoft.com -ResolveHostname Perform trace route to www.microsoft.com and try to resolve hostname for each hop. Note! This will slow down the function somewhat. .NOTES Author: Øyvind Kallstad Date: 28.10.2014 Version: 1.1 #> [CmdletBinding()] param( # Hostname or IP to trace to. [Parameter(Position = 0, ValueFromPipeline = $true)] [string] $Target = $env:COMPUTERNAME, # Set starting hop. [Parameter()] [int] $BeginHop = 1, # Set maximum number of hops. [Parameter()] [int] $MaxHops = 30, # Define timeout in milliseconds. [Parameter()] [int] $Timeout = 1000, # Try to resolve hostname for IP in each hop. [Parameter()] [switch] $ResolveHostname = $false ) # verify that we can reach target system try{ $ping = New-Object System.Net.NetworkInformation.Ping $pingResult = $ping.Send($Target) if(-not($pingResult.Status -eq 'Success')){ Write-Warning "Unable to resolve target system $Target" exit } } catch{ Write-Warning "Unable to resolve target system $Target" exit } # define some data to send $sendBytes = @([byte][char]'a'..[byte][char]'z') for($i = $BeginHop; $i -lt $MaxHops; $i++) { # define ping options; set start hop and fragmentation to true $pingOptions = new-object System.Net.NetworkInformation.PingOptions $i, $true # perform ping $pingReply = $ping.Send($Target, $Timeout, $sendBytes, $pingOptions) # get ip for current hop if possible if($pingReply.Address -ne $null){ $ip = $pingReply.Address } else{ $ip = '*' } # get roundtrip time $roundtripTime = $pingReply.RoundtripTime # get status $hopStatus = $pingReply.Status # resolve hostname if ($ResolveHostname) { try{ $resolvedHostname = "[$(([System.Net.Dns]::GetHostEntry($ip)).HostName)]" } catch{ $resolvedHostname = '' } } # create custom object and send to pipeline Write-Output ([PSCustomObject] [Ordered] @{ Hop = $i.ToString() IP = "$($ip) $($resolvedHostname)" Status = $hopStatus RoundtripTime = $roundtripTime }) # clean up Remove-Variable ip, roundtripTime, hopStatus, resolvedHostname -ErrorAction 'SilentlyContinue' # stop loop if current ip matches the target ip if($pingReply.Address -eq $pingResult.Address){break} } }
PowerShellCorpus/GithubGist/InPermutation_6625573_raw_ef80e2d2fe812cda0ee7310530562941b264a58c_gistfile1.ps1
InPermutation_6625573_raw_ef80e2d2fe812cda0ee7310530562941b264a58c_gistfile1.ps1
$treeish = "my_tag" # $treeish = "my_branch" # $treeish = "900fe0a22ea332fcbfdb4b0bc7136760ea30cc19" # $treeish = "900fe0a22" $exists = [bool](git rev-parse --quiet --verify $treeish) $ref = [bool](git show-ref $treeish) $sha = -not $ref # Check if it's a tag. (Careful; --list uses shell wildcard syntax) $tag = [bool](git tag --list $treeish)
PowerShellCorpus/GithubGist/sean-m_11262491_raw_be82039e1a9210d0cc2a61201b090b3e02a0d76c_EvenSpace.ps1
sean-m_11262491_raw_be82039e1a9210d0cc2a61201b090b3e02a0d76c_EvenSpace.ps1
<# Takes a string and returns a string of tab characters wide enough to make the input string take up the specified character width in $tabWidth. Useful when outputing values in a loop but haven't setup pipelining to take advantage of Format-Table. I've only tested it in PS-ISE, may not work in a terminal with different tab width. Example: $a = "Keenan" $b = "foo" $c = "bar" $a + $(EvenSpace -word $a) + $c $b + $(EvenSpace -word $b) + $c Output: Keenan bar foo bar #> function EvenSpace{ param ($word) $tabWidth = 48 $diff = $tabWidth - $word.Length $tabNum = [Math]::Floor($diff/4) / 2 ("`t" * $tabNum) }
PowerShellCorpus/GithubGist/tugberkugurlu_4223615_raw_6d41c07a6fa3bd74f796deeec8e69d33e1406e4b_EnvVar.ps1
tugberkugurlu_4223615_raw_6d41c07a6fa3bd74f796deeec8e69d33e1406e4b_EnvVar.ps1
#Set Machine level #Elevated console is required [Environment]::SetEnvironmentVariable("VarName", "Value", "Machine") #Set Current User Level [Environment]::SetEnvironmentVariable("VarName", "Value", "User") #Get All vars dir env:\ #Get specific var $env:MyVal
PowerShellCorpus/GithubGist/AaronOnTheHub_510d7408aaf163c009b3_raw_5ca8ea542dc94bbcca6f6f34c852efd6caeeb38d_Count-Down.ps1
AaronOnTheHub_510d7408aaf163c009b3_raw_5ca8ea542dc94bbcca6f6f34c852efd6caeeb38d_Count-Down.ps1
############################################################################## #.SYNOPSIS # A count down. # #.DESCRIPTION # Counts down from a number to zero, displaying the current step, with the # ability to control mucho. # #.PARAMETER startMessage # Output prior to beginning of the countdown. Defaults to empty string. # #.PARAMETER completeMessage # Output upon completion of the countdown. Defaults to empty string. # #.PARAMETER stepSleepMilliseconds # Defaults to 250. How long (in milliseconds) to wait between steps. # #.PARAMETER stepCount # The number to count down from. Defaults to 10. # #.PARAMETER endSleepMilliseconds # Defaults to 0. If given a value, the function will wait for the specified # number of milliseconds before returning flow back to the caller. # #.EXAMPLE # Count-Down -startMessage "Here we go" -completedMessage "All done" -stepSleepMilliseconds 1000 -stepCount 5 -endSleepMilliseconds 3 ############################################################################## function Count-Down { param ( [string]$startMessage = "", [string]$completeMessage = "", [int]$stepSleepMilliseconds = 250, [int]$stepCount = 10, [int]$endSleepMilliseconds = 0) if ($startMessage.Length -gt 0) { Write-Host $startMessage; }; $currentStep = $stepCount; while ($currentStep -gt 0) { Start-Sleep -Milliseconds $stepSleepMilliseconds; Write-Host "$currentStep... " -NoNewline; $currentStep--; }; if ($stepSleepMilliseconds -gt 0) { Start-Sleep -Milliseconds $endSleepMilliseconds; if ($completeMessage.Length -gt 0) { Write-Host $completeMessage -NoNewline; }; Write-Host ""; } };
PowerShellCorpus/GithubGist/paulcbetts_1944933_raw_ae9898129bc470a4d66f8a0113e892063d84f6a6_clean-merged-branches.ps1
paulcbetts_1944933_raw_ae9898129bc470a4d66f8a0113e892063d84f6a6_clean-merged-branches.ps1
$dontcare = git fetch origin --prune $branches = git branch -a --merged | ?{$_ -match "remotes\/origin"} | ?{$_ -notmatch "\/master"} | %{$_.Replace("remotes/origin/", "").Trim() } if (-not $branches) { echo "No merged branches detected" exit 0 } echo $branches $title = "Delete Merged Branches" $message = "Do you want to delete the already-merged remote branches displayed above??" $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", ` "Delete the remote branches listed." $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", ` "Leave the branches alone." $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no) $result = $host.ui.PromptForChoice($title, $message, $options, 1) if ($result -eq 1) { exit 0 } $branches | %{ git push origin ":$_" }
PowerShellCorpus/GithubGist/gravejester_3714f9ac60dcefb7721e_raw_b70db10cd961a5a2850980647b47ea75f25003ea_Test-Connection.ps1
gravejester_3714f9ac60dcefb7721e_raw_b70db10cd961a5a2850980647b47ea75f25003ea_Test-Connection.ps1
function Test-Connection { [CmdletBinding(DefaultParameterSetName='Default', HelpUri='http://go.microsoft.com/fwlink/?LinkID=135266', RemotingCapability='OwnedByCommand')] param( [Parameter(ParameterSetName='Default')] [Parameter(ParameterSetName='Source')] [switch] ${AsJob}, [System.Management.AuthenticationLevel] ${Authentication}, [Alias('Size','Bytes','BS')] [ValidateRange(0, 65500)] [int] ${BufferSize}, [Parameter(Mandatory=$true, Position=0, ValueFromPipelineByPropertyName=$true)] [Alias('CN','IPAddress','__SERVER','Server','Destination')] [ValidateNotNullOrEmpty()] [string[]] ${ComputerName}, [ValidateRange(1, 4294967295)] [int] ${Count}, [Parameter(ParameterSetName='Source')] [ValidateNotNullOrEmpty()] [pscredential] [System.Management.Automation.CredentialAttribute()] ${Credential}, [Parameter(ParameterSetName='Source', Mandatory=$true, Position=1)] [Alias('FCN','SRC')] [ValidateNotNullOrEmpty()] [string[]] ${Source}, [System.Management.ImpersonationLevel] ${Impersonation}, [Parameter(ParameterSetName='Source')] [Parameter(ParameterSetName='Default')] [ValidateRange(-2147483648, 1000)] [int] ${ThrottleLimit}, [Alias('TTL')] [ValidateRange(1, 255)] [int] ${TimeToLive}, [ValidateRange(1, 60)] [int] ${Delay}, [Parameter(ParameterSetName='Quiet')] [switch] ${Quiet}, [Parameter()] [switch] ${Resolve}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } if ($PSBoundParameters['Resolve']) { $null = $PSBoundParameters.Remove('Resolve') foreach ($item in $ComputerName) { try { $item -match [IPAddress]$item [string[]]$ComputerNameEx += ([System.Net.Dns]::GetHostEntry($item)).HostName } catch { [string[]]$ComputerNameEx += $item } } $PSBoundParameters['ComputerName'] = $ComputerNameEx } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Management\Test-Connection', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Test-Connection .ForwardHelpCategory Cmdlet #> }
PowerShellCorpus/GithubGist/slacker_1222933_raw_8d0680fb79c2ee7c8b05789da369e20b392c89f5_siastatus.ps1
slacker_1222933_raw_8d0680fb79c2ee7c8b05789da369e20b392c89f5_siastatus.ps1
$path = "c:\usr\local\monitor\log\status" if ( ! (Test-Path $path)) { Write-Error "Status file not found!" exit } # Don't care about the first four lines $null, $null, $null, $null, $siastatusfile = Get-Content $path # Matches normal lines # PORT_OpswAgent 0 INST:1 300 Armed/Normal 08/09/2011 01:52:03 $regex = "(?<name>\S+)\s+" $regex += "(?<value>\S+)\s+" $regex += "(?<type>\S+)\s+" $regex += "(?<frequency>\S+)\s+" $regex += "(Armed/Normal|Out of Bounds|Invalid Data|Uninitialized)\s+" # <status> will end up at $matches[1] $regex += "(?<lastcheckeddate>\S+)\s+" $regex += "(?<lastcheckedtime>\S+)" # Matches the following line where there is not a space between the Name and Value (Value must begin with a digit) # Memory_Database_Usage21 INST:2 300 Armed/Normal 08/09/2011 01:52:03 $regex2 = "(?<name>\D+)" $regex2 += "(?<value>\S+)\s+" $regex2 += "(?<type>\S+)\s+" $regex2 += "(?<frequency>\S+)\s+" $regex2 += "(Armed/Normal|Out of Bounds|Invalid Data|Uninitialized)\s+" # <status> will end up at $matches[1] $regex2 += "(?<lastcheckeddate>\S+)\s+" $regex2 += "(?<lastcheckedtime>\S+)" $siastatus = @() foreach ($line in $siastatusfile) { switch -regex ($line.Trim()) { $regex { $obj = New-Object psobject -Property @{ "Name" = $matches.name "Value" = $matches.value "Type" = $matches.type "Frequency" = $matches.frequency "Status" = $matches[1] "LastChecked" = $matches.lastcheckeddate + " " + $matches.lastcheckedtime } $siastatus += $obj continue } $regex2 { $obj = New-Object psobject -Property @{ "Name" = $matches.name "Value" = $matches.value "Type" = $matches.type "Frequency" = $matches.frequency "Status" = $matches[1] "LastChecked" = $matches.lastcheckeddate + " " + $matches.lastcheckedtime } $siastatus += $obj continue } # Don't bother with empty lines ""{continue} # Warn on any lines that don't match default { Write-Warning "Could not match line: $line" } } } $siastatus
PowerShellCorpus/GithubGist/JC1738_8585800_raw_fddf6fea3c86f9aac9443840af9cd84e9515d7cd_user_data.ps1
JC1738_8585800_raw_fddf6fea3c86f9aac9443840af9cd84e9515d7cd_user_data.ps1
<powershell> ##### #DON'T FORGET TO SET/CHANGE THE USERNAME/PASSWORD BELOW!!!!!!!!!! ##### $user="opscode" $password="opscode" #Disable password complexity requirements "[System Access]" | out-file c:\delete.cfg "PasswordComplexity = 0" | out-file c:\delete.cfg -append "[Version]" | out-file c:\delete.cfg -append 'signature="$CHICAGO$"' | out-file c:\delete.cfg -append secedit /configure /db C:\Windows\security\new.sdb /cfg c:\delete.cfg /areas SECURITYPOLICY # Create a user with her password, add to Admin group net user /add $user $password; net localgroup Administrators /add $user; # Get the instance ready for Chef bootstrapper, commands courtesy of Julian Dunn winrm quickconfig -q winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="300"}' winrm set winrm/config '@{MaxTimeoutms="1800000"}' winrm set winrm/config/service '@{AllowUnencrypted="true"}' winrm set winrm/config/service/auth '@{Basic="true"}' netsh advfirewall firewall set rule name="Windows Remote Management (HTTP-In)" profile=public protocol=tcp localport=5985 remoteip=localsubnet new remoteip=any </powershell>
PowerShellCorpus/GithubGist/9to5IT_9620565_raw_04b5a0e0d62290ccf025de4ab9c75597a75d6d9c_Logging_Functions.ps1
9to5IT_9620565_raw_04b5a0e0d62290ccf025de4ab9c75597a75d6d9c_Logging_Functions.ps1
Function Log-Start{ <# .SYNOPSIS Creates log file .DESCRIPTION Creates log file with path and name that is passed. Checks if log file exists, and if it does deletes it and creates a new one. Once created, writes initial logging data .PARAMETER LogPath Mandatory. Path of where log is to be created. Example: C:\Windows\Temp .PARAMETER LogName Mandatory. Name of log file to be created. Example: Test_Script.log .PARAMETER ScriptVersion Mandatory. Version of the running script which will be written in the log. Example: 1.5 .INPUTS Parameters above .OUTPUTS Log file created .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 10/05/12 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 19/05/12 Purpose/Change: Added debug mode support .EXAMPLE Log-Start -LogPath "C:\Windows\Temp" -LogName "Test_Script.log" -ScriptVersion "1.5" #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$LogName, [Parameter(Mandatory=$true)][string]$ScriptVersion) Process{ $sFullPath = $LogPath + "\" + $LogName #Check if file exists and delete if it does If((Test-Path -Path $sFullPath)){ Remove-Item -Path $sFullPath -Force } #Create file and start logging New-Item -Path $LogPath -Value $LogName -ItemType File Add-Content -Path $sFullPath -Value "***************************************************************************************************" Add-Content -Path $sFullPath -Value "Started processing at [$([DateTime]::Now)]." Add-Content -Path $sFullPath -Value "***************************************************************************************************" Add-Content -Path $sFullPath -Value "" Add-Content -Path $sFullPath -Value "Running script version [$ScriptVersion]." Add-Content -Path $sFullPath -Value "" Add-Content -Path $sFullPath -Value "***************************************************************************************************" Add-Content -Path $sFullPath -Value "" #Write to screen for debug mode Write-Debug "***************************************************************************************************" Write-Debug "Started processing at [$([DateTime]::Now)]." Write-Debug "***************************************************************************************************" Write-Debug "" Write-Debug "Running script version [$ScriptVersion]." Write-Debug "" Write-Debug "***************************************************************************************************" Write-Debug "" } } Function Log-Write{ <# .SYNOPSIS Writes to a log file .DESCRIPTION Appends a new line to the end of the specified log file .PARAMETER LogPath Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log .PARAMETER LineValue Mandatory. The string that you want to write to the log .INPUTS Parameters above .OUTPUTS None .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 10/05/12 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 19/05/12 Purpose/Change: Added debug mode support .EXAMPLE Log-Write -LogPath "C:\Windows\Temp\Test_Script.log" -LineValue "This is a new line which I am appending to the end of the log file." #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$LineValue) Process{ Add-Content -Path $LogPath -Value $LineValue #Write to screen for debug mode Write-Debug $LineValue } } Function Log-Error{ <# .SYNOPSIS Writes an error to a log file .DESCRIPTION Writes the passed error to a new line at the end of the specified log file .PARAMETER LogPath Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log .PARAMETER ErrorDesc Mandatory. The description of the error you want to pass (use $_.Exception) .PARAMETER ExitGracefully Mandatory. Boolean. If set to True, runs Log-Finish and then exits script .INPUTS Parameters above .OUTPUTS None .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 10/05/12 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 19/05/12 Purpose/Change: Added debug mode support. Added -ExitGracefully parameter functionality .EXAMPLE Log-Error -LogPath "C:\Windows\Temp\Test_Script.log" -ErrorDesc $_.Exception -ExitGracefully $True #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$ErrorDesc, [Parameter(Mandatory=$true)][boolean]$ExitGracefully) Process{ Add-Content -Path $LogPath -Value "Error: An error has occurred [$ErrorDesc]." #Write to screen for debug mode Write-Debug "Error: An error has occurred [$ErrorDesc]." #If $ExitGracefully = True then run Log-Finish and exit script If ($ExitGracefully -eq $True){ Log-Finish -LogPath $LogPath Break } } } Function Log-Finish{ <# .SYNOPSIS Write closing logging data & exit .DESCRIPTION Writes finishing logging data to specified log and then exits the calling script .PARAMETER LogPath Mandatory. Full path of the log file you want to write finishing data to. Example: C:\Windows\Temp\Test_Script.log .PARAMETER NoExit Optional. If this is set to True, then the function will not exit the calling script, so that further execution can occur .INPUTS Parameters above .OUTPUTS None .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 10/05/12 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 19/05/12 Purpose/Change: Added debug mode support Version: 1.2 Author: Luca Sturlese Creation Date: 01/08/12 Purpose/Change: Added option to not exit calling script if required (via optional parameter) .EXAMPLE Log-Finish -LogPath "C:\Windows\Temp\Test_Script.log" .EXAMPLE Log-Finish -LogPath "C:\Windows\Temp\Test_Script.log" -NoExit $True #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$false)][string]$NoExit) Process{ Add-Content -Path $LogPath -Value "" Add-Content -Path $LogPath -Value "***************************************************************************************************" Add-Content -Path $LogPath -Value "Finished processing at [$([DateTime]::Now)]." Add-Content -Path $LogPath -Value "***************************************************************************************************" #Write to screen for debug mode Write-Debug "" Write-Debug "***************************************************************************************************" Write-Debug "Finished processing at [$([DateTime]::Now)]." Write-Debug "***************************************************************************************************" #Exit calling script if NoExit has not been specified or is set to False If(!($NoExit) -or ($NoExit -eq $False)){ Exit } } } Function Log-Email{ <# .SYNOPSIS Emails log file to list of recipients .DESCRIPTION Emails the contents of the specified log file to a list of recipients .PARAMETER LogPath Mandatory. Full path of the log file you want to email. Example: C:\Windows\Temp\Test_Script.log .PARAMETER EmailFrom Mandatory. The email addresses of who you want to send the email from. Example: "admin@9to5IT.com" .PARAMETER EmailTo Mandatory. The email addresses of where to send the email to. Seperate multiple emails by ",". Example: "admin@9to5IT.com, test@test.com" .PARAMETER EmailSubject Mandatory. The subject of the email you want to send. Example: "Cool Script - [" + (Get-Date).ToShortDateString() + "]" .INPUTS Parameters above .OUTPUTS Email sent to the list of addresses specified .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 05.10.12 Purpose/Change: Initial function development .EXAMPLE Log-Email -LogPath "C:\Windows\Temp\Test_Script.log" -EmailFrom "admin@9to5IT.com" -EmailTo "admin@9to5IT.com, test@test.com" -EmailSubject "Cool Script - [" + (Get-Date).ToShortDateString() + "]" #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$EmailFrom, [Parameter(Mandatory=$true)][string]$EmailTo, [Parameter(Mandatory=$true)][string]$EmailSubject) Process{ Try{ $sBody = (Get-Content $LogPath | out-string) #Create SMTP object and send email $sSmtpServer = "smtp.yourserver" $oSmtp = new-object Net.Mail.SmtpClient($sSmtpServer) $oSmtp.Send($EmailFrom, $EmailTo, $EmailSubject, $sBody) Exit 0 } Catch{ Exit 1 } } }
PowerShellCorpus/GithubGist/victorvogelpoel_8388014_raw_38e74f8d328c59ae75134c4eea085b12a4249efa_Measure-ScriptCode.ps1
victorvogelpoel_8388014_raw_38e74f8d328c59ae75134c4eea085b12a4249efa_Measure-ScriptCode.ps1
# Measure-ScriptCode.ps1 # Return metrics about the script and module files # PowerShell 3 is required as Abstract Syntax Trees are used. # Jan 2014 # If this works, Victor Vogelpoel <victor.vogelpoel@macaw.nl> wrote this. # If it doesn't, I don't know who wrote this. # # Disclaimer # This script is provided AS IS without warranty of any kind. I disclaim all implied warranties including, without limitation, # any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or # performance of the sample scripts and documentation remains with you. In no event shall I be liable for any damages whatsoever # (including, without limitation, damages for loss of business profits, business interruption, loss of business information, # or other pecuniary loss) arising out of the use of or inability to use the script or documentation. #requires -version 3 Set-PSDebug -Strict Set-StrictMode -Version Latest function Measure-ScriptCode { [CmdletBinding()] param ( [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="One or more PS1 or PSM1 files to calculate code metrics for")] [Alias('PSPath', 'Path')] [string[]]$ScriptFile ) begin { $files = 0 $modules = 0 $manifests = 0 $lines = 0 $words = 0 $characters = 0 $codeLines = 0 $comments = 0 $functions = 0 $workflows = 0 $filters = 0 $parseErrors = 0 } process { foreach ($file in $ScriptFile) { if ($file -like "*.ps1") { $files++ } if ($file -like "*.psm1") { $modules++ } if ($file -like "*.psd1") { $manifests++ } $fileContentsArray = Get-Content -Path $file if ($fileContentsArray) { # First, measure basic metrics $measurement = $fileContentsArray | Measure-Object -Character -IgnoreWhiteSpace -Word -Line $lines += $measurement.Lines $words += $measurement.Words $characters += $measurement.Characters $tokenAst = $null $parseErrorsAst = $null # Use the PowerShell 3 file parser to create the scriptblock AST, tokens and error collections $scriptBlockAst = [System.Management.Automation.Language.Parser]::ParseFile($file, [ref]$tokenAst, [ref]$parseErrorsAst) # Get the number of comment lines and comments on the end of a code line $comments += @($tokenAst | where { $_.Kind -eq "Comment" } ).Length # Calculate the 'lines of code': any line not containing comment or commentblock and not an empty or whitespace line. # Remove comment tokens from the tokenAst, remove all double newlines and count all the newlines (minus 1) $prevTokenIsNewline = $false $codeLines += @($tokenAst | select -ExpandProperty Kind | where { $_ -ne "comment" } | where { if ($_ -ne "NewLine" -or (!$prevTokenIsNewline)) { $_ } $prevTokenIsNewline = ($_ -eq "NewLine") } | where { $_ -eq "NewLine" }).Length-1 $parseErrors += @($parseErrorsAst).Length if ($scriptBlockAst -ne $null) { # Find all functions, filters and workflows in the AST, including nested functions $functionAst = $scriptBlockAst.FindAll({ $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst]}, $true) # Count the specific implementation: 'function', 'filter' or 'workflow' $functions += @($functionAst | where { (!$_.IsFilter) -and (!$_.IsWorkflow) }).Length $filters += @($functionAst | where { $_.IsFilter }).Length $workflows += @($functionAst | where { $_.IsWorkflow }).Length } } } } end { return [PSCustomObject]@{ Files = $files Modules = $modules Manifests = $manifests CodeLines = $codeLines Comments = $comments Functions = $functions Workflows = $workflows Filters = $filters ParseErrors = $parseErrors Characters = $characters Lines = $lines Words = $words } } } Measure-ScriptCode -ScriptFile (Join-Path $PSScriptRoot "Write-HelloWorld.ps1")
PowerShellCorpus/GithubGist/rkeithhill_3e7f3bd8daf9ca45b066_raw_9afdd486ffdabc944afd25d523f1709da8d706ec_PSReadlineConfiguration.ps1
rkeithhill_3e7f3bd8daf9ca45b066_raw_9afdd486ffdabc944afd25d523f1709da8d706ec_PSReadlineConfiguration.ps1
# Install this in your $profile.CurrentUserAllHosts file # This will enable and configure PSReadline for all PowerShell console sessions. if ($host.Name -eq 'ConsoleHost') { Import-Module PSReadline Set-PSReadlineOption -MaximumHistoryCount 10000 -HistorySearchCursorMovesToEnd -HistoryNoDuplicates -HistorySaveStyle SaveAtExit Set-PSReadlineKeyHandler -Chord Ctrl+Shift+Spacebar -Function PossibleCompletions Set-PSReadlineKeyHandler -Chord UpArrow -Function HistorySearchBackward Set-PSReadlineKeyHandler -Chord DownArrow -Function HistorySearchForward Set-PSReadlineKeyHandler -Chord Ctrl+i -Function ReverseSearchHistory Set-PSReadlineKeyHandler -Chord Ctrl+Shift+i -Function ForwardSearchHistory Set-PSReadlineKeyHandler -Chord 'Ctrl+D,Ctrl+C' -Function CaptureScreen Set-PSReadlineKeyHandler -Chord "Ctrl+'","Ctrl+Shift+'" ` -BriefDescription SmartInsertQuote ` -Description "Insert paired quotes if not already on a quote" ` -ScriptBlock { param($key, $arg) $line = $null $cursor = $null [PSConsoleUtilities.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) $keyChar = $key.KeyChar if ($key.Key -eq 'Oem7') { if ($key.Modifiers -eq 'Control') { $keyChar = "`'" } elseif ($key.Modifiers -eq 'Shift','Control') { $keyChar = '"' } } if ($line[$cursor] -eq $keyChar) { # Just move the cursor [PSConsoleUtilities.PSConsoleReadLine]::SetCursorPosition($cursor + 1) } else { # Insert matching quotes, move cursor to be in between the quotes [PSConsoleUtilities.PSConsoleReadLine]::Insert("$keyChar" * 2) [PSConsoleUtilities.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) [PSConsoleUtilities.PSConsoleReadLine]::SetCursorPosition($cursor - 1) } } Set-PSReadlineKeyHandler -Key Ctrl+Shift+v ` -BriefDescription PasteAsHereString ` -LongDescription "Paste the clipboard text as a here string" ` -ScriptBlock { param($key, $arg) Add-Type -Assembly PresentationCore if ([System.Windows.Clipboard]::ContainsText()) { # Get clipboard text - remove trailing spaces, convert \r\n to \n, and remove the final \n. $text = ([System.Windows.Clipboard]::GetText() -replace "\p{Zs}*`r?`n","`n").TrimEnd() [PSConsoleUtilities.PSConsoleReadLine]::Insert("@'`n$text`n'@") } else { [PSConsoleUtilities.PSConsoleReadLine]::Ding() } } Set-PSReadlineKeyHandler -Chord Ctrl+Oem5 ` -BriefDescription SearchForwardPipeChar ` -Description "Searches forward for the next pipeline character" ` -ScriptBlock { param($key, $arg) [PSConsoleUtilities.PSConsoleReadLine]::CharacterSearch($key, '|') } Set-PSReadlineKeyHandler -Chord Ctrl+Shift+Oem5 ` -BriefDescription SearchBackwardPipeChar ` -Description "Searches backward for the next pipeline character" ` -ScriptBlock { param($key, $arg) [PSConsoleUtilities.PSConsoleReadLine]::CharacterSearchBackward($key, '|') } Set-PSReadlineKeyHandler -Key '(','{','[' ` -BriefDescription InsertPairedBraces ` -LongDescription "Insert matching braces" ` -ScriptBlock { param($key, $arg) $closeChar = switch ($key.KeyChar) { <#case#> '(' { [char]')'; break } <#case#> '{' { [char]'}'; break } <#case#> '[' { [char]']'; break } } $line = $null $cursor = $null [PSConsoleUtilities.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) if ($cursor -eq $line.Length -or $line[$cursor] -match '\)|}|\]|\s') { [PSConsoleUtilities.PSConsoleReadLine]::Insert("$($key.KeyChar)$closeChar") [PSConsoleUtilities.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) [PSConsoleUtilities.PSConsoleReadLine]::SetCursorPosition($cursor - 1) } else { [PSConsoleUtilities.PSConsoleReadLine]::Insert($key.KeyChar) } } Set-PSReadlineKeyHandler -Key ')',']','}' ` -BriefDescription SmartCloseBraces ` -LongDescription "Insert closing brace or skip" ` -ScriptBlock { param($key, $arg) $line = $null $cursor = $null [PSConsoleUtilities.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) if ($line[$cursor] -eq $key.KeyChar) { [PSConsoleUtilities.PSConsoleReadLine]::SetCursorPosition($cursor + 1) } else { [PSConsoleUtilities.PSConsoleReadLine]::Insert("$($key.KeyChar)") } } Set-PSReadlineKeyHandler -Key 'Ctrl+(' ` -BriefDescription ParenthesizeSelection ` -LongDescription "Put parenthesis around the selection or entire line and move the cursor to after the closing parenthesis" ` -ScriptBlock { param($key, $arg) $selectionStart = $null $selectionLength = $null [PSConsoleUtilities.PSConsoleReadLine]::GetSelectionState([ref]$selectionStart, [ref]$selectionLength) $line = $null $cursor = $null [PSConsoleUtilities.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) if ($selectionStart -ne -1) { $replacement = '(' + $line.SubString($selectionStart, $selectionLength) + ')' [PSConsoleUtilities.PSConsoleReadLine]::Replace($selectionStart, $selectionLength, $replacement) [PSConsoleUtilities.PSConsoleReadLine]::SetCursorPosition($selectionStart + $selectionLength + 2) } else { [PSConsoleUtilities.PSConsoleReadLine]::Replace(0, $line.Length, '(' + $line + ')') [PSConsoleUtilities.PSConsoleReadLine]::EndOfLine() } } Set-PSReadlineKeyHandler -Key "Ctrl+r" ` -BriefDescription ResolveAliases ` -LongDescription "Replace all aliases with the full command" ` -ScriptBlock { param($key, $arg) $ast = $null $tokens = $null $errors = $null $cursor = $null [PSConsoleUtilities.PSConsoleReadLine]::GetBufferState([ref]$ast, [ref]$tokens, [ref]$errors, [ref]$cursor) $startAdjustment = 0 foreach ($token in $tokens) { if ($token.TokenFlags -band [System.Management.Automation.Language.TokenFlags]::CommandName) { $alias = $ExecutionContext.InvokeCommand.GetCommand($token.Extent.Text, 'Alias') if ($alias -ne $null) { $resolvedCommand = $alias.ResolvedCommandName if ($resolvedCommand -ne $null) { $extent = $token.Extent $length = $extent.EndOffset - $extent.StartOffset [PSConsoleUtilities.PSConsoleReadLine]::Replace( $extent.StartOffset + $startAdjustment, $length, $resolvedCommand) # Our copy of the tokens won't have been updated, so we need to # adjust by the difference in length $startAdjustment += ($resolvedCommand.Length - $length) } } } } } Set-PSReadlineKeyHandler -Key Ctrl+s ` -BriefDescription SaveInHistory ` -LongDescription "Save current line in history but do not execute" ` -ScriptBlock { param($key, $arg) $line = $null $cursor = $null [PSConsoleUtilities.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor) [PSConsoleUtilities.PSConsoleReadLine]::AddToHistory($line) [PSConsoleUtilities.PSConsoleReadLine]::RevertLine() } }
PowerShellCorpus/GithubGist/pierre3_d9f567c838e5b536069f_raw_5bd79693302abd922d6ba6cc3efd81bca1ba8034_Search-Web.ps1
pierre3_d9f567c838e5b536069f_raw_5bd79693302abd922d6ba6cc3efd81bca1ba8034_Search-Web.ps1
<# .Synopsis Web検索 .DESCRIPTION Google検索を行い、検索結果リンクのタイトルとUrlを取得します .EXAMPLE $words = 'powerShell', 'script', 'example' $words | Search-Web .EXAMPLE Search-Web powerShell,script,example #> function Search-Web { [CmdletBinding()] Param( # 検索ワード [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] [PSObject[]] $SearchWords, # 取得件数 [int] $num = 10 ) Begin { $words = @() } Process { $words += $SearchWords } End { $url = "https://www.google.co.jp/search?q={0}&num={1}" -f ($words -join '+'), $num $res = Invoke-WebRequest -Uri $url $res.AllElements | ? {$_.tagName -eq "H3" } | % {[xml]$_.innerHtml } | ? { $_.DocumentElement.href -match "^\/url\?" } | % { [PSCustomObject]@{ Title = $_.DocumentElement.innerText; Url = "https://www.google.co.jp$($_.DocumentElement.href)"; } } } }
PowerShellCorpus/GithubGist/gitforhf_ab518fd9fef5b2558308_raw_e9cfb0c8037b4724232ead3875530faa0d6c06e7_gistfile1.ps1
gitforhf_ab518fd9fef5b2558308_raw_e9cfb0c8037b4724232ead3875530faa0d6c06e7_gistfile1.ps1
60 $hadoop hce \ 61 -D mapred.job.name="${job_name}" \ 62 -D mapred.map.tasks.speculative.execution=false \ 63 -D mapred.reduce.tasks.speculative.execution=false \ 64 -D mapred.reduce.memory.limit=1000 \ 65 -D mapred.job.reduce.capacity=1200 \ 66 -D mapred.job.priority=${PRIORITY} \ 67 -input "${input}" \ 68 -output "${output}" \ 69 -mapper "chmod +x ./bin/xtrans_hdfs && ./bin/xtrans_hdfs -proto=${proto} -output_file=${output_file} -division_field=${division_field} -message=${message}" \ 70 -reducer "chmod +x ./bin/xtrans_hdfs && ./bin/xtrans_hdfs -proto=${proto} -output_file=${output_file} -division_field=${division_field} -message=${message}" \ 71 -file "./proto/${proto}" \ 72 -cacheArchive ${MATERIAL_BASE}/${env_dep} \ 73 -numReduceTasks ${reduce_task}
PowerShellCorpus/GithubGist/gravejester_c713cb3cebe410463dbc_raw_6932f91b2ebe8a46eebd13c92a073af2bd7e800f_Get-Mockaroo.ps1
gravejester_c713cb3cebe410463dbc_raw_6932f91b2ebe8a46eebd13c92a073af2bd7e800f_Get-Mockaroo.ps1
# the EnumUtils code was nicked from Wayne Hartman (http://blog.waynehartman.com/articles/84.aspx) Add-Type -TypeDefinition @" using System; using System.Reflection; using System.ComponentModel; public enum MockarooType { Boolean, City, Color, [DescriptionAttribute("Company Name")]CompanyName, Country, [DescriptionAttribute("Country Code")]CountryCode, [DescriptionAttribute("Credit Card #")]CreditCardNum, [DescriptionAttribute("Credit Card Type")]CreditCardType, Currency, [DescriptionAttribute("Currency Code")]CurrencyCode, [DescriptionAttribute("Domain Name")]DomainName, [DescriptionAttribute("Email Address")]EmailAddress, [DescriptionAttribute("File Name")]FileName, [DescriptionAttribute("First Name")]FirstName, [DescriptionAttribute("First Name (Euoropean)")]FirstNameEuropean, [DescriptionAttribute("First Name (Female)")]FirstNameFemale, [DescriptionAttribute("First Name (Male)")]FirstNameMale, Frequency, [DescriptionAttribute("Full Name")]FullName, Gender, [DescriptionAttribute("Gender (abbrev)")]GenderAbbrev, GUID, [DescriptionAttribute("IP Address v4")]IPv4, [DescriptionAttribute("IP Address v6")]IPv6, [DescriptionAttribute("Job Title")]JobTitle, Language, [DescriptionAttribute("Last Name")]LastName, Latitude, Longitude, [DescriptionAttribute("MAC Address")]MACAddress, [DescriptionAttribute("MIME Type")]MIMEType, Password, Phone, [DescriptionAttribute("Postal Code")]PostalCode, Race, [DescriptionAttribute("Row Number")]RowNumber, State, [DescriptionAttribute("State (abbrev)")]StateAbbrev, [DescriptionAttribute("Street Address")]StreetAddress, [DescriptionAttribute("Street Name")]StreetName, [DescriptionAttribute("Street Number")]StreetNumber, [DescriptionAttribute("Street Suffix")]StreetSuffix, Suffix, [DescriptionAttribute("Time Zone")]TimeZone, Title, [DescriptionAttribute("Top Level Domain")]TLD, Username } public class EnumUtils { public static string stringValueOf(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[]) fi.GetCustomAttributes( typeof(DescriptionAttribute), false); if (attributes.Length > 0) { return attributes[0].Description; } else { return value.ToString(); } } public static object enumValueOf(string value, Type enumType) { string[] names = Enum.GetNames(enumType); foreach (string name in names) { if (stringValueOf((Enum)Enum.Parse(enumType, name)).Equals(value)) { return Enum.Parse(enumType, name); } } throw new ArgumentException("The string is not a description or value of the specified enum."); } } "@ function Get-Mockaroo { <# .SYNOPSIS Get mock data from www.mockaroo.com .DESCRIPTION Function to automatically get mock data from www.mockaroo.com. You need to register to get API key. Using the free key you can issue up to 1000 request per day. .EXAMPLE Get-Mockaroo -APIKey $myApiKey -Schema 'test' -Count 10 | ConvertFrom-Csv | Format-Table Get 10 rows from the saved schema called 'test', formatted as a table. .EXAMPLE Get-Mockaroo -APIKey $myApiKey -Fields @( (New-MockarooField 'Name' -Type FullName), (New-MockarooField 'City' -Type City), (New-MockarooField 'Company' -Type CompanyName), (New-MockarooFieldCustomList 'Type' -Values Retail,Online), (New-MockarooFieldNumber 'Years' -Min 1 -Max 30 -PercentBlank 10 -Decimals 0), (New-MockarooFieldMoney 'Total Sale' -Min 1000 -Max 10000) ) -Count 10 | ConvertFrom-Csv | Format-Table Create a custom query using an array of field specifications. .NOTES Author: Øyvind Kallstad Date: 21.11.2014 Version: 1.1 #> [CmdletBinding(DefaultParameterSetName = 'Schema')] param ( # Your API key [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $APIKey, # Name of saved schema [Parameter(Mandatory, ParameterSetName = 'Schema')] [ValidateNotNullOrEmpty()] [string] $Schema, # Array of fields [Parameter(Mandatory, ParameterSetName = 'Fields')] [ValidateNotNullOrEmpty()] [object[]] $Fields, # Number of rows to return (when using with a schema, 1 = all rows) [Parameter()] [ValidateNotNull()] [int] $Count = 1 ) if ($Fields) { # convert field object(s) to json $fieldsJSON = $Fields | ConvertTo-Json -Compress # if array count 1, we need to manually add [ and ] around the json string for the API call to work if ($Fields.Count -eq 1) { $fieldsJSON = $fieldsJSON.Insert(($fieldsJSON.LastIndexOfAny($fieldsJSON[-1]))+1,']').Insert(0,'[') } Write-Output (Invoke-RestMethod -Uri ([uri]"http://www.mockaroo.com/api/generate.csv?key=$($APIKey)&count=$($Count)&fields=$($fieldsJSON)")) } else { Write-Output (Invoke-RestMethod -Uri ([uri]"http://www.mockaroo.com/api/generate.csv?key=$($APIKey)&count=$($Count)&schema=$($Schema)")) } } function New-MockarooFieldNumber { [CmdletBinding()] param ( [Parameter(Position = 0, Mandatory)] [ValidateNotNullorEmpty()] [string] $Name, # The minimum value [Parameter()] [ValidateRange(1,[Int32]::MaxValue)] [int] $Min = 1, # The maximum value [Parameter()] [ValidateRange(1,[Int32]::MaxValue)] [int] $Max = 100, # The number of decimals [Parameter()] [ValidateRange(0,10)] [int] $Decimals = 2, # An integer between 0 and 100 that determines what percent of the generated values will be null [Parameter()] [ValidateRange(0,100)] [int] $PercentBlank = 0 ) Write-Output ([PSCustomObject][Ordered]@{ name = $Name type = 'Number' min = $Min max = $Max decimals = $Decimals percentBlank = $PercentBlank }) } function New-MockarooFieldMoney { [CmdletBinding()] param ( # The name of the field [Parameter(Position = 0, Mandatory)] [ValidateNotNullorEmpty()] [string] $Name, # The minimum value [Parameter()] [ValidateRange(1,[Int32]::MaxValue)] [int] $Min = 1, # The maximum value [Parameter()] [ValidateRange(1,[Int32]::MaxValue)] [int] $Max = 10, # Currency symbol [Parameter()] [ValidateSet('$','£','€','¥','random','none')] [string] $Symbol = '$', # An integer between 0 and 100 that determines what percent of the generated values will be null [Parameter()] [ValidateRange(0,100)] [int] $PercentBlank = 0 ) Write-Output ([PSCustomObject][Ordered]@{ name = $Name type = 'Money' min = $Min max = $Max symbol = $Symbol percentBlank = $PercentBlank }) } function New-MockarooFieldCustomList { [CmdletBinding()] param ( # The name of the field [Parameter(Position = 0, Mandatory)] [ValidateNotNullorEmpty()] [string] $Name, # An array of values to pick from. Each value should be a string. [Parameter()] [string[]] $Values, [Parameter()] [ValidateSet('random','sequential')] [string] $SelectionStyle = 'random' ) Write-Output ([PSCustomObject][Ordered]@{ name = $Name type = 'Custom List' values = $Values selectionStyle = $SelectionStyle }) } function New-MockarooField { [CmdletBinding()] param ( # The name of the field [Parameter(Position = 0, Mandatory)] [ValidateNotNullorEmpty()] [string] $Name, # The data type of the field [Parameter()] [MockarooType] $Type, # An integer between 0 and 100 that determines what percent of the generated values will be null [Parameter()] [ValidateRange(0,100)] [int] $PercentBlank = 0 ) Write-Output ([PSCustomObject][Ordered]@{ name = $Name type = [EnumUtils]::stringValueOf([MockarooType]::$Type) percentBlank = $PercentBlank }) }
PowerShellCorpus/GithubGist/ctrlbold_3c2eeab7a311b6971c9a_raw_9df3720c665b3700c7d46f99bab91e420a038943_Invoke-Locate.ps1
ctrlbold_3c2eeab7a311b6971c9a_raw_9df3720c665b3700c7d46f99bab91e420a038943_Invoke-Locate.ps1
<# .SYNOPSIS Fans of (Linux/UNIX) GNU findutils' locate will appreciate Invoke-Locate, which provides similar functionality. "locate" and "updatedb" aliases are automatically created. .DESCRIPTION This script was made in the spirit of GNU locate. While the name of this script is Invoke-Locate, it actually creates two persistent aliases: locate and updatedb. A fresh index is automatically created every 6 hours, updatedb can be used force a refresh. Indexes generally takes less than three minutes. Performing the actual locate takes about 300 milliseconds. Invoke-Locate supports both case-sensitive, and case-insensitive searches, and is case-insensitive by default. locate queries a user-specific SQLite database prepared by updatedb (Task Scheduler) and writes file names matching the pattern to standard output, one per line. Since the back-end is SQL, SQL "LIKE" syntax can be used for the search pattern (ie % and _). Asterisks are automatically translated to % for people who are used to searching with * wildcards. So locate SQ*ite, and locate SQ%ite will return the same results. By default, locate does not check whether files found in database still exist; locate cannot report files created after the most recent update of the relevant database. .PARAMETER filename You actually don't have to specify the filename. Just locate whatever. .PARAMETER install "Installs" script to $env:LOCALAPPDATA\locate, which allows each user to have their own secured locate database. - Sets persistent locate and updatedb user aliases. - Checks for the existence of System.Data.SQLite.dll. If it does not exist, it will be automatically downloaded to $env:LOCALAPPDATA\locate. To skip this step, download System.Data.SQLite and register it to the GAC. - Creates the database in $env:LOCALAPPDATA\locate. - Creates the initial table. - Creates a schedule task named "updatedb cron job user [username] (PowerShell Invoke-Locate)" that runs every 6 hours as an elevated SYSTEM account. This action is skipped if you don't have admin access. *Note: even though an elevated SYSTEM account is used, home directories of other users are excluded from index. - Prompts users to specify if mapped drives should be indexed. Take note that mapped drives can be huge. - Prompts user to run updatedb for the first time. .PARAMETER s Similar to findutils locate's "-i" switch for case-insensitive, this switch makes the search sensitive. By default, Windows searches are insensitive, so the default search behavior of this script is case-insensitive. .PARAMETER updatedb Forces a fresh update of the database. This generally takes less than 3 minutes. .PARAMETER includemappeddrives Internal parameter. Tells updatedb to include mapped drives. .PARAMETER locatepath Internal parameter. Specifies locate's program directory. .PARAMETER userprofile Internal parameter. This helps support mulit-user scheduled task updates. .PARAMETER homepath Internal parameter. This helps support mulit-user scheduled task updates. .NOTES Author : Chrissy LeMaire Requires: PowerShell Version 3.0 DateUpdated: 2015-Jan-24 Version: 0.5 .LINK https://gallery.technet.microsoft.com/scriptcenter/Invoke-Locate-PowerShell-0aa2673a .EXAMPLE locate powershell.exe Case-insensitive search which return the path to any file or directory named powershell.exe .EXAMPLE updatedb Forces a database refresh. This generally takes just a few minutes. .EXAMPLE locate power*.exe Case-insensitive search which return the path to any file or directory that starts with power and ends with .exe .EXAMPLE locate -s System.Data.SQLite Case-sensitive search which return the path to any file or directory named System.Data.SQLite. .EXAMPLE locate powers_ell.exe Similar to SQL's "LIKE" syntax, underscores are used to specify "any single character." #> #Requires -Version 3.0 [CmdletBinding(DefaultParameterSetName="Default")] Param( [parameter(Position=0)] [string]$filename, [switch]$install, [switch]$updatedb, [string]$locatepath, [string]$userprofile, [string]$homepath, [switch]$s, [switch]$includemappedrives ) BEGIN { Function Install-Locate { <# .SYNOPSIS Installs Invoke-Locate.ps1 to the current user's $env:localappdata. #> param( [Parameter(Mandatory = $false)] [bool]$noprompt, [string]$locatepath ) if ($locatepath.length -eq 0) { $locatepath = "$env:LOCALAPPDATA\locate" } # Create locate's program directory within user $env:localappdata. if (!(Test-path $locatepath)) { $null = New-Item $locatepath -Type Directory } # Copy the files to the new directory $script = "$locatepath\Invoke-Locate.ps1" Get-Content $PSCommandPath | Set-Content $script # Set persistent aliases by writing to $profile Write-Host "Setting persistent locate and updatedb aliases" -ForegroundColor Green $locatealias = "New-Alias -name locate -value $script -scope Global -force" $exists = Get-Alias locate -ErrorAction SilentlyContinue if ($exists -eq $null) { if (!(Test-Path $profile)) { $profiledir = Split-Path $profile If (!(Test-Path $profiledir)) { $null = New-Item $profiledir -Type Directory } } Add-Content $profile $locatealias } else { Write-Warning "Alias locate exists. Skipping." } # Prompt user to see if they want to index mapped drives $message = "This script can index mapped drives, too." $question = "Would you like to index your mapped drives?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No')) $decision = $Host.UI.PromptForChoice($message, $question, $choices, 1) if ($decision -eq 1) { Write-Host "Mapped drives will not be indexed." $includemappedrives = $false } else { Write-Host "Mapped drives will be indexed." $includemappedrives = $true } # Aliases don't allow params, so a new file must be created in localappdata to support using the alias updatedb $updatefilename = "$locatepath\Update-LocateDB.ps1" if ($homepath.length -eq 0) { $homepath = "$env:HOMEDRIVE$env:HOMEPATH" } if ($userprofile.length -eq 0) { $userprofile = $env:USERPROFILE } if (!$includemappedrives) { $maparg = '-includemappedrives:$false' } else { $maparg = '-includemappedrives:$true' } Set-Content $updatefilename "Invoke-Expression '$script -updatedb -locatepath $locatepath -homepath $homepath -userprofile $userprofile $maparg'" Add-Content $updatefilename '$computername = "$($env:COMPUTERNAME)`$".ToUpper()' Add-Content $updatefilename '$username = "$env:USERNAME".ToUpper()' Add-Content $updatefilename 'if ($computername -eq $username) { return $true }' # Add persistent updatedb alias $updatealias = "New-Alias -name updatedb -value $updatefilename -scope Global -force" $exists = Get-Alias updatedb -ErrorAction SilentlyContinue if ($exists -eq $null) { Add-Content $profile $updatealias } else { Write-Warning "Alias updatedb exists. Skipping." } # Reload $profile. Now locate and udpatedb alises will work. Invoke-Expression $profile -ErrorAction SilentlyContinue # Download the DLL if System.Data.SQLite cannot be found. Copy to $env:localappdata. $sqlite = "System.Data.SQLite" $globalsqlite = [Reflection.Assembly]::LoadWithPartialName($sqlite) if ($globalsqlite -eq $null -and !(Test-Path("$locatepath\$sqlite.dll")) ) { # Check architecture if (!(Test-Path "locatepath\$sqlite.dll")) { Write-Host "Downloading $sqlite.dll" -ForegroundColor Green if ($env:Processor_Architecture -eq "x86") { $url = "http://bit.ly/x86sqlitedll" } else { $url = "http://bit.ly/x64sqlitedll" } Invoke-WebRequest $url -OutFile "$locatepath\$sqlite.dll" } } if ($globalsqlite -eq $null) {[void][Reflection.Assembly]::LoadFile("$locatepath\$sqlite.dll")} # Setup connstring $database = "$locatepath\locate.sqlite" $connString = "Data Source=$database" #Create the database if it doesn't exist. if (!(Test-Path $database)) { Write-Host "Creating database" -ForegroundColor Green # Create database [void][System.Data.SQLite.SQLiteConnection]::CreateFile($database); $connection = New-Object System.Data.SQLite.SQLiteConnection($connString) $connection.Open() Write-Host "Creating table" -ForegroundColor Green # Create table, check if primary key is automatically unique $table = "CREATE TABLE [Files] ([Name] nvarchar(450) PRIMARY KEY)" $command = $connection.CreateCommand() $command.CommandText = $table $null = $command.ExecuteNonQuery() $command.Dispose() $connection.Close() $connection.Dispose() } else { Write-Warning "database exists. Skipping." } # Create scheduled task if user is on Windows 8+ or Windows 2012+. This scheduled task will run updatedb every 6 hours, # as an elevated SYSTEM account. By default, the script wil not index any home directories, other than the user who installed it. Write-Host "Setting up Scheduled Task to run every 6 hours" -ForegroundColor Green if ([Environment]::OSVersion.Version -ge (new-object 'Version' 6,2)) { $null = New-LocateScheduledTask -locatepath $locatepath } else { $null = New-LocateScheduledTaskWin7 -locatepath $locatepath } if ($noprompt -ne $true) { Write-Warning "The database must be populated before it will return any results." $message = $null $question = "Would you like to run updatedb to populate the database now?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No')) $decision = $Host.UI.PromptForChoice($message, $question, $choices, 0) if ($decision -eq 1) { Write-Host "updatedb skipped. locate will return no results, or will be out of date." -ForegroundColor Red -BackgroundColor Black } else { Update-LocateDB -locatepath $locatepath -homepath $homepath, -userprofile $userprofile -includemappedrives $includemappedrives } } else { Update-LocateDB -locatepath $locatepath -homepath $homepath -userprofile $userprofile -includemappedrives $includemappedrives } # Finish up Write-Host "Installation to $locatepath complete." -ForegroundColor Green } Function New-LocateScheduledTask { <# .SYNOPSIS Creates a new scheduled task in Windows 8+ and Windows 2012+. This scheduled task is run as an elevated SYSTEM account, but will only search the home directory of the user that installed locate. Supports multiple users. Administrator access required because it uses a system account. #> param( [Parameter(Mandatory = $false)] [string]$locatepath ) If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Write-Warning "This script does not support creating Scheduled Tasks for non-admin users. You will have to set one up yourself. Please see http://bit.ly/1zHldCU for more information." return } # Get locate program directory if ($locatepath -eq $null) { $locatepath = "$env:LOCALAPPDATA\locate" } # Name the task, and check to see if it exists, if so, skip. $taskname = "updatedb cron job user $($env:USERNAME) (PowerShell Invoke-Locate)" $checktask = Get-ScheduledTask $taskname -TaskPath \ -ErrorAction SilentlyContinue if ($checktask -ne $null) { Write-Warning "$taskname exists. Skipping." return } else { # Script to execute $updatefilename = "$locatepath\Update-LocateDB.ps1" # Repeat timespan. $repeat = (New-TimeSpan -Hours 6) # Run indefinitely $duration = ([timeSpan]::maxvalue) # Terminate task if it runs for longer than an hour $maxduration = (New-TimeSpan -Hours 1) # Set the action to have powershell.exe call a script. $action = New-ScheduledTaskAction -Argument "$updatefilename" -WorkingDirectory $locatepath -Execute "powershell.exe" # Set script to run every 6 hours, indefintely. $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval $repeat -RepetitionDuration $duration # Set some options. $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -DontStopOnIdleEnd -ExecutionTimeLimit $maxduration # Register the task, run as SYTEM (NT AUTHORITY\SYSTEM). This is a super user that will be able to access what it needs. $null = Register-ScheduledTask -Settings $settings -TaskName $taskname -Action $action -Trigger $trigger -RunLevel Highest -User "NT AUTHORITY\SYSTEM" } } Function New-LocateScheduledTaskWin7 { <# .SYNOPSIS Creates a new scheduled task in Windows 7 and below. This scheduled task is run as an elevated SYSTEM account, but will only search the home directory of the user that installed locate. Supports multiple users. Administrator access required because it uses a system account. #> param( [Parameter(Mandatory = $false)] [string]$locatepath ) # Check if admin. If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Write-Warning "This script does not support creating Scheduled Tasks for non-admin users. You will have to set one up yourself. Please see http://bit.ly/1zHldCU for more information." return } # Get locate program directory if ($locatepath -eq $null) { $locatepath = "$env:LOCALAPPDATA\locate" } # Name the task, and check to see if it exists, if so, skip. $taskname = "updatedb cron job user $($env:USERNAME) (PowerShell Invoke-Locate)" # Script to execute $updatefilename = "$locatepath\Update-LocateDB.ps1" $taskscheduler = New-Object -ComObject Schedule.Service $taskscheduler.Connect() # Place Task in root $rootfolder = $taskscheduler.GetFolder("\") $definition = $taskscheduler.NewTask(0) # Get base info $registrationInformation = $definition.RegistrationInfo # Run as built in $principal = $definition.Principal $principal.LogonType = 5 $principal.UserID = "NT AUTHORITY\SYSTEM" $principal.RunLevel = 1 # Set options $settings = $definition.Settings $settings.StartWhenAvailable = $true $settings.RunOnlyIfNetworkAvailable = $false $settings.ExecutionTimeLimit = "PT1H" $settings.RunOnlyIfIdle = $false $settings.AllowDemandStart = $true $settings.AllowHardTerminate = $true $settings.DisallowStartIfOnBatteries = $false $settings.Priority = 7 $settings.StopIfGoingOnBatteries = $false $settings.idlesettings.StopOnIdleEnd = $false # Set script to run every 6 hours, indefintely. $triggers = $definition.Triggers $trigger = $triggers.Create(2) $trigger.Repetition.Interval = "P0DT6H0M0S" $trigger.Repetition.StopAtDurationEnd = $false $trigger.StartBoundary = (Get-Date "00:00:00" -Format s) # Set the action to have powershell.exe call a script. $action = $definition.Actions.Create(0) $action.Path = "powershell.exe" $action.Arguments = $updatefilename $action.WorkingDirectory = $locatepath # 6 = update or delete, 0 is no password needed $rootfolder.RegisterTaskDefinition($taskname, $definition, 6, "NT AUTHORITY\SYSTEM",$null,0) } Function Update-LocateDB { <# .SYNOPSIS Migrates logins from source to destination SQL Servers. Database & Server securables & permissions are preserved. .EXAMPLE Copy-SQLLogins -Source $sourceserver -Destination $destserver -Force $true Copies logins from source server to destination server. .OUTPUTS A CSV log and visual output of added or skipped logins. #> param( [string]$locatepath, [string]$homepath, [string]$userprofile, [bool]$includemappedrives ) Write-Host "Updating locate database. This should only take a few minutes." -ForegroundColor Green # Set varables and load up assembly if ($locatepath.length -eq 0) {$locatepath = "$env:LOCALAPPDATA\locate" } if ($homepath.length -eq 0) { $homepath = "$env:HOMEDRIVE$env:HOMEPATH" } if ($userprofile.length -eq 0) { $userprofile = $env:USERPROFILE } if ([Reflection.Assembly]::LoadWithPartialName("System.Data.SQLite") -eq $null) { [void][Reflection.Assembly]::LoadFile("$locatepath\System.Data.SQLite.dll") } $elapsed = [System.Diagnostics.Stopwatch]::StartNew() $database = "$locatepath\locate.sqlite" $connString = "Data Source=$database" $connection = New-Object System.Data.SQLite.SQLiteConnection($connString) $connection.Open() $command = $connection.CreateCommand() # SQLite doesn't support truncate, let's just drop the table and add it back. $command.CommandText = "DROP TABLE [Files]" [void]$command.ExecuteNonQuery() $command.CommandText = "CREATE TABLE [Files] ([Name] nvarchar(450) PRIMARY KEY)" [void]$command.ExecuteNonQuery() Write-Host "Updating database" -ForegroundColor Green # Use a single transaction to speed up insert. $transaction = $connection.BeginTransaction() # Get local drives. Like GNU locate, this includes your local DVD-CDROM, etc drives. $disks = Get-WmiObject Win32_Volume -Filter "Label!='System Reserved'" foreach ($disk in $disks.name) { Get-Filenames -path $disk -locatepath $locatepath } # Since C:\Users is ignored by default in the above routine, $homepath and $userprofile must be explicitly indexed. Get-Filenames -path $homepath -locatepath $locatepath if ($homepath -ne $userprofile) { Get-Filenames -path $userprofile -locatepath $locatepath } # When locate was installed, the user was prompted to answer whether they wanted to index their mapped drives. If ($includemappedrives -eq $true) { $disks = Get-WmiObject Win32_MappedLogicalDisk foreach ($disk in $disks.name) { Get-Filenames -path $disk -locatepath $locatepath } } # Commit the transaction $transaction.Commit() # Count the number of files indexed and report $totaltime = [math]::Round($elapsed.Elapsed.TotalMinutes,2) $totaltime = (($elapsed.Elapsed.ToString()).Split("."))[0] $command.CommandText = "SELECT COUNT(*) FROM [Files]" $rowcount = $command.ExecuteScalar() Write-Host "$rowcount files on $($disks.count) drives have been indexed in $totaltime." -ForegroundColor Green $command.Dispose() $connection.Close() $connection.Dispose() } Function Get-Filenames { <# .SYNOPSIS This function is called recursively to get filenames and insert them into the database. Skips $env:APPDATA), $env:LOCALAPPDATA, $env:TMP, $env:TEMP. The system drive's Users directory is also excluded, but then the locate user's homepath and userprofile are explicitly included. #> param( [string]$path, [string]$locatepath, [string]$homepath, [string]$userprofile ) # Set variables and load SQLite assembly if ($locatepath -eq $null) { $locatepath = "$env:LOCALAPPDATA\locate" } if ([Reflection.Assembly]::LoadWithPartialName("System.Data.SQLite") -eq $null) { [void][Reflection.Assembly]::LoadFile("$locatepath\System.Data.SQLite.dll") } # IO.Directory throws a lot of access denied exceptions, ignore them. Set-Variable -ErrorAction SilentlyContinue -Name files Set-Variable -ErrorAction SilentlyContinue -Name folders # Get the directories, and make a list of the files within them try { $files = [IO.Directory]::GetFiles($path) [System.IO.DirectoryInfo]$directoryInfo = New-Object IO.DirectoryInfo($path) $folders = $directoryInfo.GetDirectories() | Where-Object {$_.Name -ne "`$Recycle.Bin" -and $folder -ne "System Volume Information" } } catch { $folders = @()} # For each file, clean up the SQL syntax and insert into database. foreach($filename in $files) { $filename = $filename.replace('\\','\') $filename = $filename.replace("'","''") $command.CommandText = "insert into files values ('$filename')" [void]$command.ExecuteNonQuery() } # Some things just don't need to be indexed (though you're free to remove any if you'd like. $exclude = @($env:APPDATA) $exclude += $env:LOCALAPPDATA $exclude += $env:TMP $exclude += $env:TEMP # Lil bit of lightweight security $exclude += "$env:systemdrive\Users" $include = @($homepath) $include += $userprofile # Process folders and subfolders foreach($folder in $folders) { if ($exclude -notcontains "$path$folder") { Get-Filenames -path "$path\$folder" -locatepath $locatepath Write-Verbose "Indexing $path\$folder" } } # Remove the erroraction variable Remove-Variable -ErrorAction SilentlyContinue -Name files Remove-Variable -ErrorAction SilentlyContinue -Name folders } Function Search-Filenames { <# .SYNOPSIS Performs a LIKE query on the SQLite database. .OUTPUT System.Data.Datatable #> param( [string]$filename, [string]$locatepath, [bool]$s ) # Get variables, load assembly if ($locatepath -eq $null) { $locatepath = "$env:LOCALAPPDATA\locate" } if ([Reflection.Assembly]::LoadWithPartialName("System.Data.SQLite") -eq $null) { [void][Reflection.Assembly]::LoadFile("$locatepath\System.Data.SQLite.dll") } # Setup connect $database = "$locatepath\locate.sqlite" $connString = "Data Source=$database" try { $connection = New-Object System.Data.SQLite.SQLiteConnection($connString) } catch { throw "Can't load System.Data.SQLite.SQLite. Architecture mismatch or access denied. Quitting." } $connection.Open() $command = $connection.CreateCommand() # Allow users to use * as wildcards. $filename = $filename.Replace("`*","`%") if ($s -eq $false) { $sql = "PRAGMA case_sensitive_like = 0;select name from files where name like '%$filename%'" } else { $sql = "PRAGMA case_sensitive_like = 1;select name from files where name like '%$filename%'" } Write-Verbose "SQL string executed: $sql" $command.CommandText = $sql # Create datatable and fill it with results $datatable = New-Object System.Data.DataTable $datatable.load($command.ExecuteReader()) $command.Dispose() $connection.Close() $connection.Dispose() # return the datatable (which just includes one column, 'name' return $datatable } } PROCESS { # Set locate's program directory if ($locatepath.length -eq 0) { $locatepath = "$env:LOCALAPPDATA\locate" } if ($install -eq $true){ Install-Locate -noprompt $false -locatepath $locatepath; return } # Check to see if the SQLite database exists, if it doesn's, prompt the user to install locate and populate the database. $locatedb = "$locatepath\locate.sqlite" if (!(Test-Path $locatedb)) { Write-Warning "locate database not found" $question = "Would you like to run the installer and populate the database now?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No')) $decision = $Host.UI.PromptForChoice($message, $question, $choices, 0) if ($decision -eq 1) { Write-Host "Install skipped and no database to query. Quitting." -ForegroundColor Red -BackgroundColor Black break } else { Install-Locate -noprompt $true -locatepath $locatepath } } # If updatedb is called if ($updatedb -eq $true) { Update-LocateDB -locatepath $locatepath -homepath $homepath, -userprofile $userprofile -includemappedrives $includemappedrives; return } # If no arguments are passed, error out. if ($filename.length -eq 0) { throw "You need to pass an argument." } # Perform a search, and specify the case sensitivty. Output match strings. $dt = (Search-Filenames $filename -locatepath $locatepath -s $s) $dt.name } END { # Clean up connections, if needed if ($command.connection -ne $null) { $command.Dispose() } if ($connection.state -ne $null) { $connection.Close(); $connection.Dispose() } }
PowerShellCorpus/GithubGist/sandrinodimattia_4215259_raw_b6fb9802b02341e109bcc6dfb548b17011fe2350_gistfile1.ps1
sandrinodimattia_4215259_raw_b6fb9802b02341e109bcc6dfb548b17011fe2350_gistfile1.ps1
# Remove RDP endpoints from VMs in cloud service Get-AzureVM -ServiceName myservice | Remove-AzureEndpoint -Name RemoteDesktop | Update-AzureVM # Add RDP endpoints to all VMs in cloud service Get-AzureVM -ServiceName myservice | Add-AzureEndpoint -Name RemoteDesktop -LocalPort 3389 -Protocol tcp | Update-AzureVM
PowerShellCorpus/GithubGist/amatashkin_6605833_raw_1f7065eeb89ea24c561de51f03a2856140b6d515_backup-gists.ps1
amatashkin_6605833_raw_1f7065eeb89ea24c561de51f03a2856140b6d515_backup-gists.ps1
$githubname = '' $githubname = Read-Host "Enter GitHub account name" if ($githubname) { $dirname = "gists_" + $githubname $dirname = Read-Host "Enter local directory name ($dirname)" if ( !($dirname)) {$dirname = "gists_" + $githubname } if ( !(Test-Path -path $dirname)){ New-Item -Path $dirname -ItemType Directory Set-Location $dirname $gistjson = ConvertFrom-Json (Invoke-WebRequest https://api.github.com/users/$githubname/gists).content $gisturls = $gistjson.git_pull_url foreach ($url in $gisturls) {git clone $url} Set-Location .. } else {Write-Output "Directory $dirname already exists. Exit."} } else { Write-Output "Github account name cannot be empty. Exit."}
PowerShellCorpus/GithubGist/ao-zkn_0356a22e5d9a8b2cbb0b_raw_d3e56bef0db451682b090f88e24619b01fdee0fe_Get-URLEncode.ps1
ao-zkn_0356a22e5d9a8b2cbb0b_raw_d3e56bef0db451682b090f88e24619b01fdee0fe_Get-URLEncode.ps1
# ------------------------------------------------------------------ # 指定した文字コードより、文字列をURLエンコードする # 関数名:Get-URLEncode # 引数 :VALUE URLエンコードする文字列 # :ENCODING 文字コード # 戻り値:URLエンコードした文字列 # ------------------------------------------------------------------ function Get-URLEncode([String]$VALUE, [String]$ENCODING){ [void][System.Reflection.Assembly]::LoadWithPartialName("System.Web") $enc= [System.Text.Encoding]::GetEncoding($ENCODING) return [System.Web.HttpUtility]::UrlEncode($VALUE,$enc) }
PowerShellCorpus/GithubGist/SLaks_9752028_raw_da99bcf89c76bd8b2d162f711e158a43de2ade94_Reference-DLLs.ps1
SLaks_9752028_raw_da99bcf89c76bd8b2d162f711e158a43de2ade94_Reference-DLLs.ps1
$names = "Microsoft.VisualStudio.VisualBasic.LanguageService", "Microsoft.VisualBasic.Editor", "Microsoft.VisualBasic.LanguageService", "Microsoft.VisualStudio.CSharp.Services.Language", "Microsoft.VisualStudio.CSharp.Services.Language.Interop" $regex = "(" + (($names | ForEach-Object {[System.Text.RegularExpressions.Regex]::Escape($_)}) -join '|') + ")" $sourceFolder = "...\Ref12\References\v10.0\" $env:path += ";${env:ProgramFiles(x86)}\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools" foreach($sourceName in $names) { $sourceDLL = Join-Path $sourceFolder -ChildPath "$sourceName.dll" $destName = "Reference.$sourceName" $destDLL = Join-Path $sourceFolder -ChildPath "$destName.dll" $workDir = [System.IO.Path]::GetTempFileName(); #$workDir = "$sourceFolder\$destName"; Remove-Item $workDir New-Item -ItemType directory -Path $workDir cd $workDir ildasm $sourceDLL /Out:"$destName.il" (Get-Content "$destName.il") ` -replace "\[$regex\]", '[Reference.$1]' ` -join "`n" ` -replace "(?m)^(\.(?:assembly|module) (?:extern )?)$regex(\.dll)?(`n)(?:(\{`n) .publickeytoken = \([0-9A-F ]+\)\s+//.+`n)?", '$1Reference.$2$3$4$5' ` -replace "(?m)^ .publickey = \(([0-9A-F ]+ [ )] // .+\r?\n)+", '' ` | Set-Content "$destName.il" Remove-Item $destDLL ilasm /DLL "$destName.il" /output=$destDLL > $null Remove-Item $workDir -Recurse break }
PowerShellCorpus/GithubGist/pjfontillas_2798f4b076ce583ecf31_raw_eeb8f9ece682743b230bfd5bd78e707a03100e4d_Microsoft.PowerShell_profile.ps1
pjfontillas_2798f4b076ce583ecf31_raw_eeb8f9ece682743b230bfd5bd78e707a03100e4d_Microsoft.PowerShell_profile.ps1
# run this to allow scripting # Set-ExecutionPolicy Unrestricted -Scope CurrentUser # $PROFILE support # Notepad is always available, but text editor can be overridden Function Edit-Profile { Param ( [Parameter()] [string]$editor ) if (!$editor){ #echo "Using Notepad to edit $PROFILE" Notepad $PROFILE } else { #echo "Using $editor to edit $PROFILE" # e.g. "Edit-Profile -use subl" iex "$editor $PROFILE" } } Function Reload-Profile { iex ". $PROFILE" } Set-Alias ep Edit-Profile Function eps { iex "Edit-Profile -editor subl" } # support for easy exit of Powershell Window Function quit { iex "exit" } Set-Alias q quit Set-Alias e quit # create files like Unix Function touch { New-Item -ItemType File $args } # sublime editor Set-Alias subl "C:\Program Files\Sublime Text 2\sublime_text.exe" # npm http-server support Function dev-http-server { iex "http-server -c-1 -p 80" } # open command, similar to OSX Set-Alias open "explorer" Function Open-Powershell { iex "Invoke-Item C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe" } Set-Alias pws Open-Powershell Set-Alias terminal Open-Powershell
PowerShellCorpus/GithubGist/Kruzen_8720595_raw_c1773499fbd85a5bc31d47606927f9f801b5ffd7_Notify-VdiDisconnectedSessions.ps1
Kruzen_8720595_raw_c1773499fbd85a5bc31d47606927f9f801b5ffd7_Notify-VdiDisconnectedSessions.ps1
Import-Module RemoteDesktop Get-RDUserSession | Where-Object SessionState -eq STATE_DISCONNECTED $ADServer = "" $from = "" $subject = "Improper Logoff From: $($user.CollectionName)" $body = "Hello $($user.UserName), `n`nPlease log back on to your VDI $($user.CollectionName) Session and select `"Log Off`" from the start menu to discontinue these notifications. Sessions should always be terminated from the start menu and not from the X at the top of the screen. `n`n Thanks,`n`n IT" $mailserver = "" if (Get-RDUserSession | Where-Object SessionState -eq STATE_DISCONNECTED){ $notify_list = Get-RDUserSession | Where-Object SessionState -eq STATE_DISCONNECTED foreach($user in $notify_list){ $usermail = invoke-command -cn $ADServer -ScriptBlock {param($user);Import-Module ActiveDirectory;(Get-ADUser -identity $user.UserName -properties mail).mail} -ArgumentList $user Write-Host "Sending Mail to" $usermail Send-MailMessage ` -to $usermail ` -from $from ` -subject $subject ` -body $body ` -SmtpServer $mailserver } Write-Host Done! }
PowerShellCorpus/GithubGist/ReubenBond_1387620_raw_cba96c3277343062ba2b53766f94d9b799c0ad1f_Disable-AutomaticallyDetectSettings.ps1
ReubenBond_1387620_raw_cba96c3277343062ba2b53766f94d9b799c0ad1f_Disable-AutomaticallyDetectSettings.ps1
# Disable 'Automatically detect proxy settings' in Internet Explorer. function Disable-AutomaticallyDetectProxySettings { # Read connection settings from Internet Explorer. $regKeyPath = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections\" $conSet = $(Get-ItemProperty $regKeyPath).DefaultConnectionSettings # Index into DefaultConnectionSettings where the relevant flag resides. $flagIndex = 8 # Bit inside the relevant flag which indicates whether or not to enable automatically detect proxy settings. $autoProxyFlag = 8 if ($($conSet[$flagIndex] -band $autoProxyFlag) -eq $autoProxyFlag) { # 'Automatically detect proxy settings' was enabled, adding one disables it. Write-Host "Disabling 'Automatically detect proxy settings'." $mask = -bnot $autoProxyFlag $conSet[$flagIndex] = $conSet[$flagIndex] -band $mask $conSet[4]++ Set-ItemProperty -Path $regKeyPath -Name DefaultConnectionSettings -Value $conSet } $conSet = $(Get-ItemProperty $regKeyPath).DefaultConnectionSettings if ($($conSet[$flagIndex] -band $autoProxyFlag) -ne $autoProxyFlag) { Write-Host "'Automatically detect proxy settings' is disabled." } }
PowerShellCorpus/GithubGist/MikeAStevenson_646a079f09c641679c5b_raw_382dd997af2781f4d17b732921ab694cb42c1f62_Enable-RDP.ps1
MikeAStevenson_646a079f09c641679c5b_raw_382dd997af2781f4d17b732921ab694cb42c1f62_Enable-RDP.ps1
# # Author: M. Stevenson # Desc : Enable RDP on a remote computer, given the hostname or IP # Date : 2014-11-04 - M. Stevenson - Initial Version # Function Enable-RDP { [CmdletBinding()] param( [parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="Enter the name/IP of the computer to enable RDP on")] [string]$computer ) PROCESS { if (!(Test-Connection -ComputerName $computer -Count 1 -ea 0)) { Write-Host "$computer : OFFLINE" Continue } try { $rdp = gwmi -Class Win32_TerminalServiceSetting ` -Namespace root\CIMV2\TerminalServices ` -ComputerName $computer ` -Authentication 6 ` -ErrorAction Stop } catch { Write-Host "$computer : WMIQueryFailed" Continue } if ($rdp.AllowTSConnections -eq 1) { Write-Host "$computer : RDP Already enabled" continue } else { try { $result = $rdp.SetAllowTSConnections(1,1) if ($result.ReturnValue -eq 0) { Write-Host "$computer : Enabled RDP Successfully" } else { Write-Host "$computer : Failed to enable RDP" } } catch { Write-Host "$computer : Failed to enable RDP" } } } end {} }
PowerShellCorpus/GithubGist/stefanstranger_b4c75d440469f1dc25c7_raw_1fdcda0625e9ac8e70416cb4bceefb533f7fd983_InstallISEWinMergeModule.ps1
stefanstranger_b4c75d440469f1dc25c7_raw_1fdcda0625e9ac8e70416cb4bceefb533f7fd983_InstallISEWinMergeModule.ps1
$webclient = New-Object System.Net.WebClient $url = "https://github.com/stefanstranger/ISEWinMerge/archive/master.zip" Write-Host "Downloading latest version of ISEWinMerge from $url" -ForegroundColor Cyan $file = "$($env:TEMP)\ISEWinMerge.zip" if (Test-path "$targetondisk\ISEWinMerge"){remove-item $targetondisk"\ISEWinMerge" -Recurse -force} if (Test-Path "$targetondisk\ISEWinMerge-Master"){remove-item $targetondisk"\ISEWinMerge-Master" -Recurse -force} $webclient.DownloadFile($url,$file) Write-Host "File saved to $file" -ForegroundColor Green $targetondisk = "$($env:USERPROFILE)\Documents\WindowsPowerShell\Modules" New-Item -ItemType Directory -Force -Path $targetondisk | out-null $shell_app=new-object -com shell.application $zip_file = $shell_app.namespace($file) Write-Host "Uncompressing the Zip file to $($targetondisk)" -ForegroundColor Cyan $destination = $shell_app.namespace($targetondisk) $destination.Copyhere($zip_file.items(), 0x10) Write-Host "Renaming folder" -ForegroundColor Cyan Rename-Item -Path ($targetondisk+"\ISEWinMerge-master") -NewName "ISEWinMerge" -Force Write-Host "Module has been installed" -ForegroundColor Green Import-Module -Name ISEWinMerge Get-Command -Module ISEWinMerge
PowerShellCorpus/GithubGist/AdamNaj_5e0e040d91b04359df1d_raw_4dee4e1e0f976cf5510e9c6f9647dcd3410e5302_change_image_field.ps1
AdamNaj_5e0e040d91b04359df1d_raw_4dee4e1e0f976cf5510e9c6f9647dcd3410e5302_change_image_field.ps1
#item I want to set the field on $item = get-item "master:/content/home" #image I want to use $image = new-object -TypeName "Sitecore.Data.Items.MediaItem" -ArgumentList (get-item "master:/media library/Showcase/cognifide_logo") #field I want to set on $item $imageField = [Sitecore.Data.Fields.ImageField]$item.Fields["image"]; $item.Editing.BeginEdit(); $imageField.MediaID = $image.ID; $imageField.Src = [Sitecore.Resources.Media.MediaManager]::GetMediaUrl($image) $imageField.MediaPath = $image.MediaPath; $item.Editing.EndEdit();
PowerShellCorpus/GithubGist/jstangroome_485519_raw_b362f62b5c2b866767ab5cb306ff878e043c9d65_Export-TfsCollectionReports.ps1
jstangroome_485519_raw_b362f62b5c2b866767ab5cb306ff878e043c9d65_Export-TfsCollectionReports.ps1
#requires -version 2.0 [CmdletBinding()] param ( [parameter(Mandatory=$true)] [ValidatePattern('^https?://')] [string] $TeamProjectCollectionUri, [parameter(Mandatory=$true)] [string] $Destination ) function Ensure-Path ($Path) { if (-not ($Path | Test-Path -PathType Container)) { New-Item -Path $Path -ItemType Container | Out-Null } } function Export-CatalogItem ( $Item, $Destination, $ProjectReportFolder ) { $ItemPath = $Destination | Join-Path -ChildPath $Item.Path.Substring($ProjectReportFolder.Length) switch ($Item.Type) { Folder { Ensure-Path $ItemPath } Report { Write-Host "Exporting report: $($Item.Path)" $RdlPath = $ItemPath + '.rdl' $Def = $RSProxy.GetReportDefinition($Item.Path) Set-Content -Path $RdlPath -Value $Def -Encoding Byte $Rdl = Get-Item -Path $RdlPath if ($Item.CreationDateSpecified) { $Rdl.CreationTime = $Item.CreationDate } if ($Item.ModifiedDateSpecified) { $Rdl.LastWriteTime = $Item.ModifiedDate } } default { Write-Warning "Catalog item type '$_' not supported: $($Item.Path)" } } } function Export-TeamProjectReports ( $ProjectReportFolder, $Destination ) { Write-Host "Processing reports in $ProjectReportFolder" $RSProxy.ListChildren($ProjectReportFolder, $true) | ForEach-Object { Export-CatalogItem $_ $Destination $ProjectReportFolder } } $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest 'Microsoft.TeamFoundation', 'Microsoft.TeamFoundation.Client', 'Microsoft.TeamFoundation.Common' | ForEach-Object { $AsmName = "$_, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" [Reflection.Assembly]::Load($AsmName) | Out-Null } Ensure-Path $Destination $ResourceTypes = [Microsoft.TeamFoundation.Framework.Common.CatalogResourceTypes] [Guid[]]$ReportingFolderFilter = @($ResourceTypes::ReportingFolder) [Guid[]]$TeamProjectFilter = @($ResourceTypes::TeamProject) Write-Host "Connecting to Team Project Collection: $TeamProjectCollectionUri" $CollectionFactoryType = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory] $Collection = $CollectionFactoryType::GetTeamProjectCollection($TeamProjectCollectionUri) $ServerLocations = $Collection.ConfigurationServer.GetService([Microsoft.TeamFoundation.Framework.Client.ILocationService]) $ReportsServiceDef = $ServerLocations.FindServiceDefinitions([Microsoft.TeamFoundation.ServiceInterfaces]::ReportWebServiceUrl) | Select-Object -First 1 $ReportsUrl = $ServerLocations.LocationForCurrentConnection($ReportsServiceDef) $RSAsmxUrl = $ReportsUrl + '/ReportService2005.asmx' Write-Host "Connecting to Reporting Services: $RSAsmxUrl" $RSProxy = New-WebServiceProxy -Uri $RSAsmxUrl -UseDefaultCredential $RSProxy.Url = $RSAsmxUrl $Node = $Collection.CatalogNode.QueryChildren($ReportingFolderFilter, $false, 'None') | Select-Object -First 1 $CollectionReportFolder = $Node.Resource.Properties['ItemPath'] Write-Host "Querying Team Projects" $Collection.CatalogNode.QueryChildren($TeamProjectFilter, $false, 'None') | ForEach-Object { $Node = $_.QueryChildren($ReportingFolderFilter, $false, 'None') | Select-Object -First 1 if ($Node) { $ReportSubfolder = $Node.Resource.Properties['ItemPath'] $ProjectDestination = $Destination | Join-Path -ChildPath $ReportSubfolder Ensure-Path $ProjectDestination $ProjectReportFolder = '{0}/{1}' -f $CollectionReportFolder, $ReportSubfolder Export-TeamProjectReports $ProjectReportFolder $ProjectDestination } } Write-Host "Export complete."
PowerShellCorpus/GithubGist/thecodejunkie_1384038_raw_216e03b0219dd0b68c8e8043787c6b56a764a1e9_Continuous-CoffeeScript.ps1
thecodejunkie_1384038_raw_216e03b0219dd0b68c8e8043787c6b56a764a1e9_Continuous-CoffeeScript.ps1
# watch a file changes in the current directory, # compile when a .coffee file is changed or renamed # Wrapped Graeme's version up into a function so it can be installed with install-module # Also changed so it invoked coffee.exe directly, you need Coffee for Windows in your PATH for it to work # https://github.com/alisey/CoffeeScript-Compiler-for-Windows function watch { $watcher = New-Object System.IO.FileSystemWatcher $watcher.Path = get-location $watcher.IncludeSubdirectories = $true $watcher.EnableRaisingEvents = $false $watcher.NotifyFilter = [System.IO.NotifyFilters]::LastWrite -bor [System.IO.NotifyFilters]::FileName while($TRUE){ $result = $watcher.WaitForChanged([System.IO.WatcherChangeTypes]::Changed -bor [System.IO.WatcherChangeTypes]::Renamed -bOr [System.IO.WatcherChangeTypes]::Created, 1000); if($result.TimedOut){ continue; } write-host "Modified" $result.Name $file = Get-Item $result.Name if($file.Extension -eq ".coffee"){ write-host "Compiling" $result.Name coffee.exe -c $file.FullName } } }
PowerShellCorpus/GithubGist/scotro_64be96a44170ab693a8b_raw_ee155d6f7d48a4d4e9a4ee7f4fb5069b13c0e0bd_win-grep.ps1
scotro_64be96a44170ab693a8b_raw_ee155d6f7d48a4d4e9a4ee7f4fb5069b13c0e0bd_win-grep.ps1
Get-ChildItem C:\ -include *.txt -rec -ErrorAction SilentlyContinue | Select-String -pattern "^(?:[0-9A-Z]{5}-){4}[0-9A-Z]{5}$" -ErrorAction SilentlyContinue
PowerShellCorpus/GithubGist/pkirch_4648d7899619e7c8ec7f_raw_14aff94802945bafecfd339df21ad7a7ab7af06b_Get-RelatedCommand.ps1
pkirch_4648d7899619e7c8ec7f_raw_14aff94802945bafecfd339df21ad7a7ab7af06b_Get-RelatedCommand.ps1
# Sample by Peter Kirchner (peter.kirchner@microsoft.com) PS C:\Users\pkirch> Get-Command -Module Azure -Noun AzureService <# Output CommandType Name ModuleName ----------- ---- ---------- Cmdlet Get-AzureService Azure Cmdlet New-AzureService Azure Cmdlet Remove-AzureService Azure Cmdlet Set-AzureService Azure Cmdlet Start-AzureService Azure Cmdlet Stop-AzureService Azure #> PS C:\Users\pkirch> Get-Command -Module Azure -Noun AzureVM <# Output CommandType Name ModuleName ----------- ---- ---------- Cmdlet Export-AzureVM Azure Cmdlet Get-AzureVM Azure Cmdlet Import-AzureVM Azure Cmdlet New-AzureVM Azure Cmdlet Remove-AzureVM Azure Cmdlet Restart-AzureVM Azure Cmdlet Start-AzureVM Azure Cmdlet Stop-AzureVM Azure Cmdlet Update-AzureVM Azure #>
PowerShellCorpus/GithubGist/janegilring_5595200_raw_f9a24077368e7e27fa75cf79c67f947131aecbe7_2013SGEvent3AdvancedSample.ps1
janegilring_5595200_raw_f9a24077368e7e27fa75cf79c67f947131aecbe7_2013SGEvent3AdvancedSample.ps1
function Ping-SYHost ([string] $hostName) { <#     .SYNOPSIS         Tests server availability by using PING command.               .DESCRIPTION         This script will ping a host and return TRUE/FALSE.  Use this function to determine if the host is reachable.                     .EXAMPLE         Ping-SYHost -hostName "CHAGRES01" #>     [bool] $result = 0     $oPing = New-Object System.Net.NetworkInformation.Ping           try {         $PingStatus = $oPing.Send("$hostName")         if ($PingStatus.Status -eq "Success"){             $result = 1         }         else {             $result = 0         }     }     catch {         $result = 0           }     $result }     function Get-SYEvent3{ <#     .SYNOPSIS         Displays information about local storage.       .DESCRIPTION         Queries the Win32_LogicalDisk class to display general information about local storage.                 .EXAMPLE         Get-SYEvent3 CHAGRES01         Display local storage information for computer CHAGRES01               .EXAMPLE         Get-Content C:\PoSh\2013Scripting\Events\3\Event3.txt|% {Get-SYEvent3 -HostList $_ -TargetPath "C:\PoSh\2013Scripting\Events\3"}         Display local storage information for computers listed in the "Event3.txt" file #>     param(         [Parameter(ValueFromPipeline = $true,                    ValueFromPipelineByPropertyName = $true)] [array] $HostList = "$env:COMPUTERNAME",         [string] $TargetPath = "$env:HOMEDRIVE$env:HOMEPATH"     )       $sHTML = ""    $sHead = @" <head><title>Drive Free Space Report</title> <style type="text/css"> BODY{font-family:Verdana; background-color:#white;} TABLE{table-layout:auto;border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse; background-color:#FFFFFF} TH{font-family:Verdana,Sans-Serif; color:#000000; font-size:1em; font-weight:bold; border-width: 1px; padding: 2px; border-style: solid; border-color: black; background-color:#CCCCCC} TD{font-family:Verdana,Sans-Serif; font-size:0.7em; border-width: 1px; padding: 2px; border-style: solid; border-color: black; background-color:#FFFFFF} </style></head> <body> "@           foreach ($HostName in $HostList) {         if ($HostList.Count -gt 1){             $sHostName = $HostName         } else {             $sHostName = $HostList         }           if (Ping-SYHost $HostName) {             $Drives = Get-WmiObject -computername "$HostName" Win32_LogicalDisk -filter "DriveType=3" | foreach {                 add-member -in $_ -membertype NoteProperty -Name SizeGB -Value $([math]::round(($_.Size/1GB),2))                 add-member -in $_ -membertype NoteProperty -Name FreeMB -Value $([math]::round(($_.FreeSpace/1MB),2)) -passThru}               $sHTMLBody = "<H2>Local Fixed Disk Report for $sHostName</H2>"             $sHTML = $Drives|SELECT @{Name="Drive";Expression={$_.DeviceID}}, @{Name="DriveSize(GB)";Expression={$_.SizeGB}}, @{Name="FreeSpace(MB)";Expression={$_.FreeMB}}|ConvertTo-Html -Fragment             $sHTMLFooter = "<hr>This report was generated on $(Get-Date -f 'MM/dd/yyyy HH:mm:ss')"         } else {             WRITE "Computer $sHostName did not respond to a PING command in a timely manner, check to make suere it is online."         }                   $regex = [regex] '<td>'         if ($regex.IsMatch($sHTML)){             if(!(Test-Path "$TargetPath")){                 New-Item -ItemType directory -Path "$TargetPath"             }               $sBody = "$sHead $sHTMLBody $sHTML $sHTMLFooter </body>"             $sBody|Out-File -FilePath $TargetPath\$sHostName.htm             WRITE "$TargetPath\$sHostName.htm"         }         start "file:///$TargetPath\$sHostName.htm"     } }
PowerShellCorpus/GithubGist/hotpicklesoup_a084d3da7475b8584728_raw_5d7c65cf5460bc2e8c3e9693b3a9e866a0c30ced_UpdateFirewallConfig.ps1
hotpicklesoup_a084d3da7475b8584728_raw_5d7c65cf5460bc2e8c3e9693b3a9e866a0c30ced_UpdateFirewallConfig.ps1
function UpdateFirewallConfig { Param ( $SRC_config, $DST_config ) # Compare the sections to see if the are new, existing, or extraneous. $diff_sections = Compare-Object $dst_config.firewallconfiguration.layer3sections.section $src_config.firewallconfiguration.layer3sections.section -Property name -IncludeEqual # Compare the sections to see if the are new, existing, or extraneous. $diff_rules = Compare-Object $DST_config.firewallConfiguration.layer3Sections.section.rule $SRC_config.firewallConfiguration.layer3Sections.section.rule -Property name -IncludeEqual # Loop through each Layer 3 section in the source firewall configuration Foreach ($section in $SRC_config.firewallConfiguration.layer3Sections.section) { # Replace the source ObjectIds with destination ObjectsIds using the objects we just pushed to the destination Foreach ($source in $section.rule.sources.source) { # Match against the Security Groups and IPSets we just pushed to the destination and update Objectids. Switch ($source.type) { SecurityGroup { $source.value = [string]($new_securitygroups | Where {$_.name -eq $source.name}).objectid } IPSet { $source.value = [string]($new_ipsets | Where {$_.name -eq $source.name}).objectid } } } # Loop through all the destinations for all the rules in the section Foreach ($source in $section.rule.destinations.destination) { # Match against the Security Groups and IPSets we just pushed to the destination and update the ObjectIds Switch ($source.type) { SecurityGroup { $source.value = [string]($new_securitygroups | Where {$_.name -eq $source.name}).objectid } IPSet { $source.value = [string]($new_ipsets | Where {$_.name -eq $source.name}).objectid } } } # Loop through all the services for all the rules in the sections Foreach ($source in $section.rule.services.service) { # Match against the Services and Service Groups we just pushed to the destination and update the ObjectIds. Switch ($source.type) { ApplicationGroup { $source.value = [string]($new_servicegroups | Where {$_.name -eq $source.name}).objectid } Application { $source.value = [string]($new_services | Where {$_.name -eq $source.name}).objectid } } } # Switch based on results of the compare-object Switch (($diff_sections | ? {$_.name -like $section.name}).sideindicator) { # If the section is existing in destination already then update the ObjectsIds of the rules and section and it will be updated when the new config is pushed "==" { # Update the id of each rule in the section with the Id from the destination Foreach ($rule in $section.rule) { if (-not ($DST_config.firewallConfiguration.layer3Sections.section.rule | Where {$_.name -eq $rule.name})){ $rule.RemoveAttribute("id") } else { $rule.id = [string]($DST_config.firewallConfiguration.layer3Sections.section.rule | Where {$_.name -eq $rule.name}).id } } # Update the id of the section with the Id from the destination $section.id = ($DST_config.firewallConfiguration.layer3Sections.section | Where {$_.name -eq $section.name}).id Add-content $log -value "$(get-date -format u) Section $([string]$section.name) will be Updated on Destination" } # If the section exists in source but not destination then remove all section and rule Ids and it will be created when the new config is pushed "=>" { # Loop through all rules in the section and remove the Id attribute Foreach ($rule in $section.rule) { $rule.RemoveAttribute("id") } # Remove the Id attribute from the section $section.RemoveAttribute("id") Add-content $log -value "$(get-date -format u) Section $([string]$section.name) will be Created on Destination" } # If the section exists on destination but not source then it will be removed when the new config is pushed "<=" { Add-content $log -value "$(get-date -format u) Section $([string]$section.name) will be Deleted on Destination" } } } Foreach ($rule in $SRC_config.firewallConfiguration.layer3Sections.section.rule) { Switch (($diff_rules | ? {$_.name -like $rule.name}).sideindicator) { # If the rule is existing in destination already then it will be updated when the new config is pushed "==" { Add-content $log -value "$(get-date -format u) Rule $([string]$rule.name) will be Updated on Destination" } # If the section exists in source but not destination then it will be created when the new config is pushed "=>" { Add-content $log -value "$(get-date -format u) Rule $([string]$rule.name) will be Created on Destination" } # If the rule exists on destination but not source then it will be removed when the new config is pushed "<=" { Add-content $log -value "$(get-date -format u) Rule $([string]$rule.name) will be Deleted on Destination" } } } # Loop through each Layer 2 section in the source firewall configuration Foreach ($section in $SRC_config.firewallConfiguration.layer2Sections.section) { # Update the id of each rule in the section with the Id from the destination Foreach ($rule in $section.rule) { $rule.id = [string]($DST_config.firewallConfiguration.layer2Sections.section.rule | Where {$_.name -eq $rule.name}).id } # Update the id of the section with the Id from the destination $section.id = ($DST_config.firewallConfiguration.layer2Sections.section | Where {$_.name -eq $section.name}).id } # ETag is the generation number of the section, it needs to be in the header for firewall updates. [string]$ETag = $DST_fw_config.firewallConfiguration.generationNumber $fw_headers = @{"Authorization" = "Basic YWRtaW46NFRBWnNLQllDWkVv";"Content-Type" = "application/xml";"If-Match" = "$ETag"} Try { $response = Invoke-WebRequest -Uri $DST_fw_config_uri_PUT -Headers $fw_headers -TimeoutSec 120 -Method PUT -Body $src_config.outerxml Add-content $log -value "$(get-date -format u) $($response.StatusCode) $($response.statusdescription) Updating Destination Firewall Configuration with PUT on $DST_fw_config_uri_PUT" } Catch { $Error[0].exception "PUT $DST_fw_config_uri_PUT" Add-content $log -value "$(get-date -format u) ERROR:$error[0].exception Deleting $([string]$member.name) with Updating Destination Firewall Configuration with PUT on $DST_fw_config_uri_PUT" } }
PowerShellCorpus/GithubGist/davideicardi_22b13fc76b180c9a7399_raw_01564ab42d311e7fe6b5fc86016eaca5494a67f3_script.ps1
davideicardi_22b13fc76b180c9a7399_raw_01564ab42d311e7fe6b5fc86016eaca5494a67f3_script.ps1
Function Install-PoshSsh { # https://github.com/darkoperator/Posh-SSH # http://www.powershellmagazine.com/2014/07/03/posh-ssh-open-source-ssh-powershell-module/ if(-not(Get-Module -name posh-ssh)) { $webclient = New-Object System.Net.WebClient $url = "https://github.com/darkoperator/Posh-SSH/archive/master.zip" Write-Host "Downloading latest version of Posh-SSH from $url" -ForegroundColor Cyan $file = "$($env:TEMP)\Posh-SSH.zip" $webclient.DownloadFile($url,$file) Write-Host "File saved to $file" -ForegroundColor Green $targetondisk = "$($env:USERPROFILE)\Documents\WindowsPowerShell\Modules" New-Item -ItemType Directory -Force -Path $targetondisk | out-null $shell_app=new-object -com shell.application $zip_file = $shell_app.namespace($file) Write-Host "Uncompressing the Zip file to $($targetondisk)" -ForegroundColor Cyan $destination = $shell_app.namespace($targetondisk) $destination.Copyhere($zip_file.items(), 0x10) Write-Host "Renaming folder" -ForegroundColor Cyan Rename-Item -Path ($targetondisk+"\Posh-SSH-master") -NewName "Posh-SSH" -Force Write-Host "Module has been installed" -ForegroundColor Green Import-Module -Name posh-ssh #Get-Command -Module Posh-SSH } } Function Create-Vm { Param( [Parameter(Mandatory = $true)] [String] $user, [Parameter(Mandatory = $true)] [String] $password, [Parameter(Mandatory = $true)] [String] $serviceName, [Parameter(Mandatory = $true)] [String] $machineName, [Parameter(Mandatory = $true)] [String] $location ) <# $user = "webplu" $password = "Passw0rd!" $serviceName = "test-vm" $machineName = "test-vm-1" $location = "West Europe" #> $service = Get-AzureService -ServiceName $serviceName if (!$service) { Write-Host "Creating service " $serviceName $service = New-AzureService -ServiceName $serviceName -Location $location } Write-Host "Creating VM " $machineName #and image retrieved from Get-AzureVMImage | Select ImageName $imageName = "b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04_1-LTS-amd64-server-20140927-en-us-30GB" $vmc = New-AzureVMConfig -Name $machineName -InstanceSize "Small" -Image $imageName -AvailabilitySetName $serviceName $null = $vmc | Add-AzureProvisioningConfig -Linux -LinuxUser $user -Password $password $null = $vmc | New-AzureVM -ServiceName $serviceName -WaitForBoot $vm = Get-AzureVM -Name $machineName -ServiceName $serviceName <# open some ports $mainRabbitPort = 5672 $mgmtPort = 15672 $null = Add-AzureEndpoint -VM $vm -LocalPort $mainRabbitPort -PublicPort $mainRabbitPort -Name "RabbitMQ-Main" -Protocol tcp -LBSetName "RabbitMQ-LB-MAIN" -ProbePort $mainRabbitPort -ProbeProtocol tcp -ProbeIntervalInSeconds 15 $null = Add-AzureEndpoint -VM $vm -LocalPort $mgmtPort -PublicPort $mgmtPort -Name "RabbitMQ-MGMT" -Protocol tcp -LBSetName "RabbitMQ-LB-MGMT" -ProbePort $mgmtPort -ProbeProtocol tcp -ProbeIntervalInSeconds 15 $null = $vm | Update-AzureVM #> Write-Host $machineName " created!" } Function Invoke-VirtualMachineSSH { Param( [Parameter(Mandatory = $true)] [String] $user, [Parameter(Mandatory = $true)] [String] $password, [Parameter(Mandatory = $true)] [String] $serviceName, [Parameter(Mandatory = $true)] [String] $machineName, [Parameter(Mandatory = $true)] [String[]] $commands ) <# $user = "webplu" $password = "Passw0rd!" $serviceName = "test-rabbitmq" $machineName = "test-rabbitmq-2" $commands = @("pwd") #> $vm = Get-AzureVM -Name $machineName -ServiceName $serviceName $endpoint = Get-AzureEndpoint -Name "ssh" -VM $vm $sshHost = $serviceName + ".cloudapp.net" # remove ssh trusted hosts Get-SSHTrustedHost | Remove-SSHTrustedHost $secpasswd = ConvertTo-SecureString $password -AsPlainText -Force $sshCredentials = New-Object System.Management.Automation.PSCredential ($user, $secpasswd) $sshSession = New-SSHSession -ComputerName $sshHost -Port $endpoint.Port -Credential $sshCredentials -AcceptKey $TRUE foreach ($command in $commands) { $status = Invoke-SSHCommand -SSHSession $sshSession -Command $command if ($status.ExitStatus -ne 0) { break } else { Write-Host $status.Output } } $null = Remove-SSHSession -SSHSession $sshSession if ($status.ExitStatus -ne 0) { throw $status.Output } }
PowerShellCorpus/GithubGist/srkirkland_3694398_raw_19ed21ddcc03b1cbe4719a133f7b259dce540acb_deploy.ps1
srkirkland_3694398_raw_19ed21ddcc03b1cbe4719a133f7b259dce540acb_deploy.ps1
#Modified and simplified version of https://www.windowsazure.com/en-us/develop/net/common-tasks/continuous-delivery/ $subscription = "[Your Subscription Name]" $service = "[Your Azure Service Name]" $slot = "staging" #staging or production $package = "[ProjectName]\bin\[BuildConfigName]\app.publish\[ProjectName].cspkg" $configuration = "[ProjectName]\bin\[BuildConfigName]\app.publish\ServiceConfiguration.Cloud.cscfg" $timeStampFormat = "g" $deploymentLabel = "ContinuousDeploy to $service v%build.number%" Write-Output "Running Azure Imports" Import-Module "C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure\*.psd1" Import-AzurePublishSettingsFile "C:\TeamCity\[PSFileName].publishsettings" Set-AzureSubscription -CurrentStorageAccount $service -SubscriptionName $subscription function Publish(){ $deployment = Get-AzureDeployment -ServiceName $service -Slot $slot -ErrorVariable a -ErrorAction silentlycontinue if ($a[0] -ne $null) { Write-Output "$(Get-Date -f $timeStampFormat) - No deployment is detected. Creating a new deployment. " } if ($deployment.Name -ne $null) { #Update deployment inplace (usually faster, cheaper, won't destroy VIP) Write-Output "$(Get-Date -f $timeStampFormat) - Deployment exists in $servicename. Upgrading deployment." UpgradeDeployment } else { CreateNewDeployment } } function CreateNewDeployment() { write-progress -id 3 -activity "Creating New Deployment" -Status "In progress" Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: In progress" $opstat = New-AzureDeployment -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service $completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot $completeDeploymentID = $completeDeployment.deploymentid write-progress -id 3 -activity "Creating New Deployment" -completed -Status "Complete" Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: Complete, Deployment ID: $completeDeploymentID" } function UpgradeDeployment() { write-progress -id 3 -activity "Upgrading Deployment" -Status "In progress" Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: In progress" # perform Update-Deployment $setdeployment = Set-AzureDeployment -Upgrade -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service -Force $completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot $completeDeploymentID = $completeDeployment.deploymentid write-progress -id 3 -activity "Upgrading Deployment" -completed -Status "Complete" Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: Complete, Deployment ID: $completeDeploymentID" } Write-Output "Create Azure Deployment" Publish
PowerShellCorpus/GithubGist/ziembor_5267404_raw_4a1e493e31395a5e8c922dc0596d1710d834e5dd_get-ADUsersWithManagerGroupMemberShipsFlatFiles.ps1
ziembor_5267404_raw_4a1e493e31395a5e8c922dc0596d1710d834e5dd_get-ADUsersWithManagerGroupMemberShipsFlatFiles.ps1
$users = get-ADUser -Filter * -Properties manager | where {$_.manager -ne $null} foreach ($user in $users) { $userSAM = $user.SamAccountName $manager = get-ADUser $user.Manager $managerSAM = $manager.SamAccountName $managerName = $manager.Name $plik = "info_+_$($managerSAM)_+_$($userSAM).txt" write-host "plik: $plik managerSAM: $managerSAM userSAM $userSAM" write-output "Manager: $managerName" | out-file -Force $plik $user | select Surname,GivenName,Name,SamAccountName,UserPrincipalName,Enabled | out-file -Append $plik Get-ADPrincipalGroupMembership $user.DistinguishedName | select Name,SamAccountName | out-file -Append $plik }
PowerShellCorpus/GithubGist/jrotello_3858994_raw_d8209427f8f0de01fde2e52f75e5ab07e2dae4d0_volunteer.ps1
jrotello_3858994_raw_d8209427f8f0de01fde2e52f75e5ab07e2dae4d0_volunteer.ps1
function Get-Volunteers { [CmdletBinding()] param( [int]$count = 1, [array]$values = @(), [string]$file = "" ) if ($file -ne "") { Get-Content $file | % { $values += $_ } } Write-Verbose "Volunteer Pool" Write-Verbose "=========================" $values | Write-Verbose $values | Get-Random -Count $count }
PowerShellCorpus/GithubGist/mefellows_80b05f8af9fd9f526ec5_raw_6852550c5c760522bc32ecf15d5716c28b8317db_vagrant-bootstrapper.ps1
mefellows_80b05f8af9fd9f526ec5_raw_6852550c5c760522bc32ecf15d5716c28b8317db_vagrant-bootstrapper.ps1
Write-Host -ForegroundColor green "Bootstrapping machine" Write-Host "Setting up package management and installing required packages for Dev." # # Install Choco (if not already installed) + required packages # if ( (Get-Command "choco" -errorAction SilentlyContinue) ) { Write-Host "Chocolatey already installed. Skipping." } else { Write-Host "Installing Chocolatey" $wc=new-object net.webclient; $wp=[system.net.WebProxy]::GetDefaultProxy(); $wp.UseDefaultCredentials=$true; $wc.Proxy=$wp; iex ($wc.DownloadString('https://chocolatey.org/install.ps1')) $env:Path = $env:Path + ";C:\ProgramData\chocolatey\bin" [Environment]::SetEnvironmentVariable( "Path", $env:Path, [System.EnvironmentVariableTarget]::Machine ) } Write-Host "Installing required packages." $packages = @( "git.commandline" "git" "cyg-get" ) $packages.ForEach({ cinst $_ }) Write-Host "Packages installed" Write-Host "Configuring Cygwin for use with SSH" # Setup SSH / Rsync for use with Vagrant $OLD_USER_PATH=[Environment]::GetEnvironmentVariable("PATH", [System.EnvironmentVariableTarget]::User) $OLD_MACHINE_PATH=[Environment]::GetEnvironmentVariable("PATH", [System.EnvironmentVariableTarget]::Machine) cyg-get rsync cyg-get openssh $CYG_PATH = "c:\tools\cygwin\;c:\tools\cygwin\bin" [Environment]::SetEnvironmentVariable("PATH", "${OLD_USER_PATH};${CYG_PATH}", "User") [Environment]::SetEnvironmentVariable("PATH", "${OLD_MACHINE_PATH};${CYG_PATH}", "Machine") # TODO: Add to Git Bash Path /c/tools/cygwin/bootstrapping Write-Host "Cygwin configuration complete." Write-Host "Installing Vagrant and friends... This will take a little bit of time" cinst vagrant virtualbox virtualbox.extensionpack Write-Host "Vagrant and friends installed, Installing required Vagrant plugins..." vagrant plugin install vagrant-proxyconf vagrant-hostsupdater Write-Host "Vagrant plugins complete. Pulling down 'talent-search-web' box and importing into Vagrant..." vagrant box add BOX_NAME PATH_TO_BOX Write-Host "Vagrant box downloaded." Write-Host -ForegroundColor green "OK. If there were no exceptions above then you could probably run a 'vagrant up' now!"