full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/chilversc_839599_raw_c7a4d67fbdec728530694f247d273554fe62c4f8_Microsoft.PowerShell_profile.ps1
chilversc_839599_raw_c7a4d67fbdec728530694f247d273554fe62c4f8_Microsoft.PowerShell_profile.ps1
function Get-HomeLocation { # Using 'Run as administrator' does not set $Home, so try other variables as well if ($variable:Home) { $variable:Home } elseif ($env:Home) { $env:Home } elseif ($env:UserProfile) { $env:UserProfile } else { $null } } function Get-HomeRelativeLocation { $h = Get-HomeLocation if ($h) { $pwd = [string] (Get-Location) if ($pwd.StartsWith($h)) { '~' + $pwd.Substring($h.Length) } else { $pwd } } else { [string] (Get-Location) } } function Write-LabeledPrompt ($Label) { if ($nestedpromptlevel -ge 1) { '>>> ' } else { $pwd = Get-HomeRelativeLocation if (Test-Administrator) { Write-Host -NoNewline -ForegroundColor Red "[Admin] " } if (Test-Path variable:/PSDebugContext) { Write-Host -NoNewline -ForegroundColor DarkGreen '[DBG]:' } Write-Host -NoNewline -ForegroundColor DarkGreen "$Label " Write-Host -ForegroundColor DarkYellow ('[' + $pwd + ']') '> ' } } function prompt { Write-LabeledPrompt 'PS' } function Test-Administrator { $user = [Security.Principal.WindowsIdentity]::GetCurrent() (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) } function touch { param([string] $filename) New-Item -type file $filename } # If the file system has not had its home set (eg using run as administrator) try to set # it using one of the other environmental variables so that commands like 'cd ~' work if (-not (Get-PSProvider 'FileSystem').Home) { $h = Get-HomeLocation if ($h) { (Get-PSProvider 'FileSystem').Home = $h } }
PowerShellCorpus/GithubGist/Steh_6051934_raw_b05c503c6e384a4f89f7f27a43138ef16a4a68dd_Get-MailboxDelegatedPermissions.ps1
Steh_6051934_raw_b05c503c6e384a4f89f7f27a43138ef16a4a68dd_Get-MailboxDelegatedPermissions.ps1
<# .SYNOPSIS Shows all Permissions on a user mailbox .DESCRIPTION shows the GrantSendOnBehalfTo field an users in MailboxPermission .EXAMPLE Get-MailboxDelegatedPermissions stehsa .PARAMETER -mailbox .NOTES Author: Steh Sa Date: July 22, 2013 #> function Get-MailboxDelegatedPermissions( [Parameter(Mandatory=$true,position=0,ValueFromPipeline=$false)] $mailbox ) { process { Write-Verbose $mailbox $i = Get-Mailbox $mailbox Write-Verbose "Mailbox: $i" Write-Host "" Write-Host "GrantSendOnBehalfTo:" Write-Host "--------------------" $i | Select-Object -ExpandProperty GrantSendOnBehalfTo Write-Host "" Write-Host "MailboxPermission:" Write-Host "------------------" $i | Get-MailboxPermission | Where-Object {($_.IsInherited -eq $False) -and ($_.User -notlike "NT AUTHORITY\SELF")} | Fl User,AccessRights } end{ Remove-Variable i } }
PowerShellCorpus/GithubGist/jhorsman_7658365_raw_ce38f8bcfac7da78424e04d1e85017d087fe6b19_Tridion-Install-CoreService-Module.ps1
jhorsman_7658365_raw_ce38f8bcfac7da78424e04d1e85017d087fe6b19_Tridion-Install-CoreService-Module.ps1
$powershellModulePath = $env:UserProfile + "\Documents\WindowsPowerShell\Modules\Tridion-CoreService" #todo test if path is in $env:PSModulePath http://msdn.microsoft.com/en-us/library/dd878350%28v=vs.85%29.aspx $powershellClientPath = $powershellModulePath + "\Clients" Write-Debug ("PowerShell module path: {0}" -f $powershellModulePath) if(!(Test-Path $powershellModulePath)) { $newModuleFolder = New-Item -path $powershellModulePath -type directory Write-Debug ("Created new module directory {0}" -f $newModuleFolder.FullName) } if(!(Test-Path $powershellClientPath)) { $newClientFolder = New-Item -path $powershellClientPath -type directory Write-Debug ("Created new client directory {0}" -f $newClientFolder.FullName) } if(Get-Module Tridion-CoreService) { Write-Debug "Module Tridion-CoreService already exists" Remove-Module Tridion-CoreService Write-Debug "Removed module Tridion-CoreService" } Copy-Item *.psm1 $powershellModulePath Copy-Item *.psd1 $powershellModulePath # @todo prevent copy errors # how to we figure out if this is writable? # can we unload the DLLs so that we can deploy them? Copy-Item "Clients\*.dll" $powershellClientPath #disable this line and copy manually if DLLs are already exist and in use Write-Debug ("Copied module files from {0} to {1}" -f ((Get-Item ".\").FullName), ((Get-Item $powershellModulePath).FullName)) Import-Module Tridion-CoreService Write-Host ("Installed Tridion-CoreService module in {0}" -f (Get-Item $powershellModulePath).FullName)
PowerShellCorpus/GithubGist/jeffpatton1971_9769168_raw_6bbe78ecd3f80687886ae5b1ebca78cf3553a12e_Copy-OuDelegation.ps1
jeffpatton1971_9769168_raw_6bbe78ecd3f80687886ae5b1ebca78cf3553a12e_Copy-OuDelegation.ps1
<# .SYNOPSIS Template script .DESCRIPTION This script sets up the basic framework that I use for all my scripts. .PARAMETER .EXAMPLE .NOTES ScriptName : Copy-Delegations.ps1 Created By : jspatton Date Coded : 03/25/2014 12:45:57 ScriptName is used to register events for this script ErrorCodes 100 = Success 101 = Error 102 = Warning 104 = Information .LINK https://code.google.com/p/mod-posh/wiki/Production/Copy-Delegations.ps1 #> [CmdletBinding()] Param ( [string]$SourceDN, [string]$DestDN, [pscredential]$Credential ) Begin { [string]$ScriptName = $MyInvocation.MyCommand.ToString() [string]$ScriptPath = $MyInvocation.MyCommand.Path [string]$Username = $env:USERDOMAIN + "\" + $env:USERNAME New-EventLog -Source $ScriptName -LogName 'Windows Powershell' -ErrorAction SilentlyContinue [string]$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString() Write-EventLog -LogName 'Windows Powershell' -Source $ScriptName -EventID "104" -EntryType "Information" -Message $Message # Dotsource in the functions you need. [int]$ADS_OPTION_SECURITY_MASK = 3 [string]$ADS_SECURITY_INFO_DACL = '&H4' } Process { [System.DirectoryServices.DirectoryEntry]$SourceDirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry($SourceDN, $Credential.UserName, $Credential.GetNetworkCredential().Password) [System.Security.AccessControl.DirectoryObjectSecurity]$SourceSecurityDescriptor = $SourceDirectoryEntry.ObjectSecurity [System.DirectoryServices.DirectoryEntry]$DestDirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry($DestDN, $Credential.UserName, $Credential.GetNetworkCredential().Password) [string]$SourceSDDL = $SourceSecurityDescriptor.Sddl $DestDirectoryEntry.ObjectSecurity.SetSecurityDescriptorSddlForm($SourceSDDL) $DestDirectoryEntry.CommitChanges() } End { [string]$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString() Write-EventLog -LogName 'Windows Powershell' -Source $ScriptName -EventID "104" -EntryType "Information" -Message $Message }
PowerShellCorpus/GithubGist/konstantindenerz_9757047_raw_7bf579c081b7f85f500eaa14f1b146dba3693c09_training.functions.output.ps1
konstantindenerz_9757047_raw_7bf579c081b7f85f500eaa14f1b146dba3693c09_training.functions.output.ps1
clear function RetrieveData($output, $param1, $param2){ #TODO: Retrieve data $output.data = 42 $output.temp = $param1 + $param2 } function ProcessData($output, $param1){ #TODO: process data $output.data++ $output.temp += $param1 } # Should be used to share state $context = @{} RetrieveData $context 'foo' 'bar' ProcessData $context 'bubu' Write-Host $context.data # 43 Write-Host $context.temp # foobarbubu
PowerShellCorpus/GithubGist/rheid_32a8c47eace524649385_raw_45655055d862a787a258b639b23b448349a986ca_ctforceupdate.ps1
rheid_32a8c47eace524649385_raw_45655055d862a787a258b639b23b448349a986ca_ctforceupdate.ps1
Param( [string] $siteUrl, [string] $group ) if(!($siteUrl)) { Write-Host "Error: Site parameter missing." -ForegroundColor Red Write-Host "Usage: Update-ContentTypeHub $siteUrl $group" return } if(!($group)) { Write-Host "Error: Group parameter missing." -ForegroundColor Red Write-Host "Usage: Update-ContentTypeHub $siteUrl $group" return } #Update Content Type hub subscribers for all web apps #Set the execution policy Set-ExecutionPolicy Unrestricted #Add the required SP snapins Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null function Publish-ContentTypeHub { param ( [parameter(mandatory=$true)][string]$CTHUrl, [parameter(mandatory=$true)][string]$Group ) $site = Get-SPSite $CTHUrl if(!($site -eq $null)) { $contentTypePublisher = New-Object Microsoft.SharePoint.Taxonomy.ContentTypeSync.ContentTypePublisher ($site) $site.RootWeb.ContentTypes | ? {$_.Group -match $Group} | % { $contentTypePublisher.Publish($_) write-host "Content type" $_.Name "has been republished" -foregroundcolor Green } } } #Updates the Content Type subscribers for each web application function Update-ContentHub([string]$url) { #Get the Timer job info $job = Get-SPTimerJob -WebApplication $url | ?{ $_.Name -like "MetadataSubscriberTimerJob"} #check that the job is not null if ($job -ne $null) { #run the timer job $job | Start-SPTimerJob #run the admin action Start-SPAdminJob -ErrorAction SilentlyContinue } } #force publish of the content types Publish-ContentTypeHub $siteUrl $group write-host write-host "Waiting for 10 seconds for job to finish..." Start-Sleep -s 10 write-host #get the web applications and update the content type hub subscribers for each web application Get-SPWebApplication | ForEach-Object { Write-Host "Updating Metadata for site:" $_.Url; Update-ContentHub -url $_.Url }
PowerShellCorpus/GithubGist/wiliammbr_06d26fc12c823b47c330_raw_dcfa1f795ac3f1f89b7477e97fb21794b79326f1_ChangePageLayout.ps1
wiliammbr_06d26fc12c823b47c330_raw_dcfa1f795ac3f1f89b7477e97fb21794b79326f1_ChangePageLayout.ps1
# Url da Web em que sua página se encontra $web = Get-SPWeb("http://awesomesharepointsite/web") # Url da página que você deseja alterar o Page Layout $file = $web.GetFile("http://awesomesharepointsite/web/pages/pagename.aspx") # Check-out na página $file.CheckOut("Online", $null) # Atualização do Page Layout passando a URL relativa do page layout desejado plus o título deste page layout $file.Properties["PublishingPageLayout"] = "/_catalogs/masterpage/page_layout_file.aspx, page_layout_title" # Update + CheckIn $file.Update() $file.CheckIn("Changing PageLayout", [Microsoft.SharePoint.SPCheckinType]::MajorCheckIn) $web.Dispose()
PowerShellCorpus/GithubGist/YoungjaeKim_e5d76f476a19224daf0a_raw_aeed412da544e30ecbc8434aff4be9de05d0ea2b_installnet35.ps1
YoungjaeKim_e5d76f476a19224daf0a_raw_aeed412da544e30ecbc8434aff4be9de05d0ea2b_installnet35.ps1
# original: http://anuchandy.blogspot.kr/2014/06/automating-net-35-installation-on-azure.html # Method that returns path to the directory holding 'installnet35.ps1' script. function Get-ScriptDirectory { $Invocation = (Get-Variable MyInvocation -Scope 1).Value Split-Path $Invocation.MyCommand.Path } # Gets path to the local resource we reserved for manipulating the zip file. [void]([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.WindowsAzure.ServiceRuntime")) $localStoreRoot = ([Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::GetLocalResource("net35resource")).RootPath.TrimEnd('\\') # .NET 3.5 source (in blob storage) # Note that you can also include the .NET 3.5 source zip file in the package $net35Source = "http://<your_blob_storage_address>.blob.core.windows.net/windows-source-for-webrole/net35.zip" # Destination path for the zip file $net35ZipDestination = Join-Path $localStoreRoot "net35.zip" # Use WebClient to download the the zip file $webClient = New-Object System.Net.WebClient $webClient.DownloadFile($net35Source, $net35ZipDestination) # Destination path to hold the extracted files $net35ExtractDestination = Join-Path $localStoreRoot "net35" $pathExists = Test-Path $net35ExtractDestination if (!$pathExists) { new-item $net35ExtractDestination -itemtype directory } # Build command to unzip $zipTool = (Join-Path (Get-ScriptDirectory) "\7za.exe") $unzipCommandArgs = "x " + $net35ZipDestination + " -o$net35ExtractDestination -y" # Unzip the file Start-Process $zipTool $unzipCommandArgs -NoNewWindow -Wait $net35ExtractDestination = Join-Path $net35ExtractDestination "net35" # Install .NET 3.5 using -Source option Install-WindowsFeature NET-Framework-Core –Source $net35ExtractDestination
PowerShellCorpus/GithubGist/AndrewBarfield_2552163_raw_4bc16fec9f8d1096b482af18387f67bafc03e44e_gistfile1.ps1
AndrewBarfield_2552163_raw_4bc16fec9f8d1096b482af18387f67bafc03e44e_gistfile1.ps1
cls $N = 5; # -------------------------------------------------------------------------------- # # FUNCTION NAME: GenerateSet # # DESCRIPTION: Generates a set of N random integers between -9 and 9 # # -------------------------------------------------------------------------------- function GenerateSet { Write-Host –NoNewLine "S = {" for($i=0; $i -le $N; $i++) { $rnd = Get-Random -minimum -9 -maximum 9 if($i -lt $N) { Write-Host –NoNewLine $rnd", " } else { Write-Host –NoNewLine $rnd } } Write-Host "}" } GenerateSet
PowerShellCorpus/GithubGist/jeppevammenkristensen_3c038b5bd9c10babac57_raw_e08097218a2498ea5a7a3a574be165df5fcff972_SetupSite.ps1
jeppevammenkristensen_3c038b5bd9c10babac57_raw_e08097218a2498ea5a7a3a574be165df5fcff972_SetupSite.ps1
Import-Module webadministration $managedRuntime = "v4.0" $Name = "Madplan" # This is of cause a dependency on Powershell version 3.0 $webPath = join-path $PSScriptRoot $Name Write-Host $webPath pushd iis:\apppools if (!(Test-Path $Name)) { Write-Host "Requesting your password" $credential = Get-Credential Write-Warning "Adding app pool with your credentials $Name" $apppool = New-item $Name $apppool | Set-ItemProperty -Name "managedRuntimeVersion" -Value $managedRuntime $apppool.processModel.identityType = 3 $apppool.processModel.username = $credential.GetNetworkCredential().UserName $apppool.processModel.password = $credential.GetNetworkCredential().Password #$apppool.processModel.setProfileEnvironment = $true $apppool | Set-Item } popd pushd iis:\sites if (Test-Path $name){ return } if ($credential -eq $null){ $credential = Get-Credential } $iisApp = new-item $name -bindings @{protocol="http";bindingInformation=":80:" + "$Name.localtest.me"} -physicalPath $webPath $iisApp | Set-ItemProperty -Name "applicationPool" -Value $Name $iisApp | Set-ItemProperty -Name username -value $credential.GetNetworkCredential().UserName $iisApp | Set-ItemProperty -Name password -value $credential.GetNetworkCredential().Password popd
PowerShellCorpus/GithubGist/jeffpatton1971_8188439_raw_abb41a44771904e62fbb5126579cdfb446c75262_Setup-PullServer.ps1
jeffpatton1971_8188439_raw_abb41a44771904e62fbb5126579cdfb446c75262_Setup-PullServer.ps1
$SourcePath = "$($pshome)\modules\psdesiredstateconfiguration\pullserver" $DestinationPath = "C:\inetpub\wwwroot\PSDSCPullServer" $AppPool = "DSCAppPool" New-Item C:\inetpub\wwwroot\PSDSCPullServer\bin -ItemType directory -Force Copy-Item "$($SourcePath)\psdscpullserver.*" $DestinationPath Copy-Item "$($SourcePath)\Global.asax" $DestinationPath Copy-Item "$($SourcePath)\Microsoft.Powershell.DesiredStateConfiguration.Service.dll" "$($DestinationPath)\bin" Rename-Item "$($DestinationPath)\psdscpullserver.config" "$($DestinationPath)\web.config" Copy-Item "$($SourcePath)\Devices.mdb" "$($env:programfiles)\WindowsPowerShell\DscService" New-WebAppPool -Name $AppPool New-Website -Name "DSC-Service" -Port 8080 -PhysicalPath $DestinationPath -ApplicationPool $AppPool $appcmd = "$env:windir\system32\inetsrv\appcmd.exe" & $appCmd unlock config -section:access & $appCmd unlock config -section:anonymousAuthentication & $appCmd unlock config -section:basicAuthentication & $appCmd unlock config -section:windowsAuthentication
PowerShellCorpus/GithubGist/mcollier_5309605_raw_96f69f957cff4a45cd0ca7fc25ab9a905e2f2b0b_BuildAndDeploy.ps1
mcollier_5309605_raw_96f69f957cff4a45cd0ca7fc25ab9a905e2f2b0b_BuildAndDeploy.ps1
$Error.Clear() $BuildConfiguration = 'Debug' Write-Host "*** Starting to build the project ***" C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe c:\Projects\MyApp\MyApp.ccproj ` /p:Configuration=$BuildConfiguration ` /t:CorePublish if ($LASTEXITCODE -ne 0) { throw "Build Failed" } Write-Host "*** Finished building the project ***" $thumbprint = '[YOUR_MANAGEMENT_CERTIFICATE_THUMBPRINT]' $sub = '[YOUR_WINDOWS_AZURE_SUBSCRIPTION_ID]' $subscriptionName = '[FRIENDLY_NAME_FOR_YOUR_SUBSCRIPTION]' $buildPath = 'c:\Projects\MyApp\bin\' + $BuildConfiguration + '\app.publish\' $packagename = 'MyApp.cspkg' $serviceconfig = 'ServiceConfiguration.Cloud.cscfg' $servicename = '[YOUR_CLOUD_SERVICE_NAME]' $storageaccount = '[YOUR_STORAGE_ACCOUNT_NAME]' $storagekey = '[YOUR_STORAGE_ACCOUNT_KEY]' $slot = 'Staging' $region = 'East US' Write-Host "*** Starting Windows Azure deployment process ***" . "C:\Projects\MyApp\scripts\AzurePublish.ps1" -serviceName $servicename -storageAccountName $storageaccount -storageAccountKey $storagekey -cloudConfigLocation $buildPath$serviceconfig ` -packageLocation $buildPath$packagename -selectedSubscription $subscriptionName -thumbprint $thumbprint -subscriptionId $sub -slot $slot -location $region
PowerShellCorpus/GithubGist/mintsoft_5917067_raw_d094b25982ab308cefb4459c43e53fedb99670e7_ExportSQLTasks.ps1
mintsoft_5917067_raw_d094b25982ab308cefb4459c43e53fedb99670e7_ExportSQLTasks.ps1
import-module SSIS $ssis_package = "D:\MyFile.dtsx"; $package = Get-ISPackage -path $ssis_package; $package.Executables | Where-Object { $_.InnerObject -like 'Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask.ExecuteSQLTask' } | %{ $fn = $_.Name+".sql"; $_.InnerObject.SqlStatementSource > $fn }
PowerShellCorpus/GithubGist/josheinstein_3859588_raw_f0ce1c346393ab45894ed1c8816605af4505b8cd_New-PSObject.ps1
josheinstein_3859588_raw_f0ce1c346393ab45894ed1c8816605af4505b8cd_New-PSObject.ps1
# PowerShell 3 adds the new [PSCustomObject] pseudo type attribute which # lets you declare an object literal using a syntax very similar to that # of an ordinary Hashtable. (There's also a new [Ordered] attribute that # creates a hash table with the order of keys preserved.) # # But it only lets you declare an object literal with NoteProperties. # What I would really love to have seen is the syntax look for script # blocks and create ScriptProperties out of them if there is no param # block or ScriptMethods out of them if there is a param block. # # In the example below, I show how this can be done with the following # syntax: New-PSObject ([Ordered]@{ ... }) # # But it would have been nice if [PSCustomObject]@{ ... } worked this way. function New-PSObject($Dictionary) { $Obj = New-Object PSObject foreach ($K in $Dictionary.Keys) { $V = $Dictionary[$K] if ($V -is [ScriptBlock]) { if ($V.Ast.ParamBlock) { $Obj | Add-Member ScriptMethod $K $V } else { $Obj | Add-Member ScriptProperty $K $V } } else { $Obj | Add-Member NoteProperty $K $V } } Return $Obj } New-PSObject ([Ordered]@{ X = 1 Y = 2 Z = { $This.X + $This.Y } DoSomething = { param() "Did something!" } }) | GM
PowerShellCorpus/GithubGist/pavelbinar_7343002_raw_b452cdde7618e2bd9323233f754a3a6cb34777a7_gistfile1.ps1
pavelbinar_7343002_raw_b452cdde7618e2bd9323233f754a3a6cb34777a7_gistfile1.ps1
# Source: http://stackoverflow.com/questions/16151018/npm-throws-error-without-sudo # This looks like a permissions issue in your home directory. To reclaim ownership of the .npm directory execute sudo chown -R `whoami` ~/.npm # Also you will need the write permission in node_modules directory: sudo chown -R `whoami` /usr/local/lib/node_modules
PowerShellCorpus/GithubGist/rytmis_4178996_raw_80858abd7e88e2f74c8c365fbb0f8e4685b4e84e_add-reply-address.ps1
rytmis_4178996_raw_80858abd7e88e2f74c8c365fbb0f8e4685b4e84e_add-reply-address.ps1
$addresses = $principal.Addresses $addresses.Add((New-MsolServicePrincipalAddresses -Address http://localhost:81)) $addresses.Add((New-MsolServicePrincipalAddresses -Address http://my-deployment-endpoint.cloudapp.net)) Set-MsolServicePrincipal -AppPrincipalId 3dc125e6-d518-40d2-9392-87a03dac8f68 -Addresses $addresses
PowerShellCorpus/GithubGist/benbrandt22_3606e55fe947a9227bd4_raw_a4a7994fc1a8189dc5ef7f5f083c35826995d5ca_Objectify.ps1
benbrandt22_3606e55fe947a9227bd4_raw_a4a7994fc1a8189dc5ef7f5f083c35826995d5ca_Objectify.ps1
# Objectify.ps1 # Ben Brandt - July 18, 2014 # Turns a tab-delimited table from the clipboard text, and converts it to a List of objects in C# code. # Useful for taking data copied from SQL Management Studio (with Headers) and converting it to in-memory objects for use as test data. function Get-ClipboardText() { Add-Type -AssemblyName System.Windows.Forms $tb = New-Object System.Windows.Forms.TextBox $tb.Multiline = $true $tb.Paste() return $tb.Text } filter isNumeric() { $out = 0 $isNum = [System.Int32]::TryParse($_, [ref]$out) return $isNum } Clear-Host $cbText = Get-ClipboardText $lines = $cbText.Split("`r`n") | where { ![string]::IsNullOrEmpty($_) } Write-Host 'ClipBoard Text:' Write-Host '--------------------------------------------------' Write-Host $cbText Write-Host '' Write-Host '--------------------------------------------------' $firstLine = $lines[0]; $columns = $firstLine.Split("`t") Write-Host "Detected Column Headers ($($columns.Count)):" $columns | Foreach { Write-Host " [$_]" } Write-Host '--------------------------------------------------' Write-Host 'C# Object Code:' Write-Host '' Write-Host "var objects = new List<dynamic> {" $lines | select -skip 1 | Foreach { $thisLine = $_ $thisLineValues = $thisLine.Split("`t") $keyValuePairs = @(); for ($i=0; $i -lt $columns.Count; $i++){ $valueOutput = $thisLineValues[$i] If($valueOutput | isNumeric) { $valueOutput = $valueOutput } Else { #escape double quotes $valueOutput = $valueOutput -replace """", "\""" #surround with double quotes $valueOutput = """$valueOutput""" } $kvp = [string]::Format("{0} = {1}", $columns[$i], $valueOutput ) $keyValuePairs += $kvp } $outputLine = " new { " $outputLine += $keyValuePairs -join ", " $outputLine += " }," Write-Host $outputLine } Write-Host "};"
PowerShellCorpus/GithubGist/jrotello_3fa07e0b522b411f85ef_raw_7863e6ebd50d330e42fcb054449d2bdce3179bf8_gistfile1.ps1
jrotello_3fa07e0b522b411f85ef_raw_7863e6ebd50d330e42fcb054449d2bdce3179bf8_gistfile1.ps1
function Remove-FiddlerCertificates { $fiddlerCert = "CN=DO_NOT_TRUST_FiddlerRoot" ls Cert:\CurrentUser\My | ? { # All certificates issued by the fiddler root certificate. $PSItem.Issuer.StartsWith($fiddlerCert) -and # But not the fiddler root certificate itself. -not $PSItem.Subject.StartsWith($fiddlerCert) } | Remove-Item }
PowerShellCorpus/GithubGist/dpanda_5830306_raw_08778c40e8e5ceedd80a8ffbba4f544c1c4d749c_gistfile1.ps1
dpanda_5830306_raw_08778c40e8e5ceedd80a8ffbba4f544c1c4d749c_gistfile1.ps1
#!/bin/bash cd img images=(`ls *.png *.jpg *.jpeg *.gif 2> /dev/null`) # get all images cd ../sass scss=(`ls *.scss */*.scss`) # get all compass files usedImg=() unusedImg=() for i in "${images[@]}"; do # for each image... : used="not-used" for f in "${scss[@]}" ; do # for each compass file... : rule=`cat $f | grep $i` # find out if images is used in any rule if [ "$rule" ] ; then # if so, add it to the "used images" array usedImg=("${usedImg[@]}" "$f \t\t\t\t$i\n") used="" break fi done if [ $used ] ; then # not found in any file: add it to the "unused images" array unusedImg=("${unusedImg[@]}" "$i") fi done # print used and unused images echo "Used images:" echo -e "${usedImg[@]}" echo echo "Unused images, moving them to _unused:" echo "${unusedImg[@]}" # move all unused images to another directory cd ../img mkdir _unused 2> /dev/null for i in "${unusedImg[@]}"; do : mv $i ./_unused done
PowerShellCorpus/GithubGist/jole78_5102112_raw_0d2a3175dbd66d9a3167df4f52ef7228686a4fe7_New-WDPublishSettings.ps1
jole78_5102112_raw_0d2a3175dbd66d9a3167df4f52ef7228686a4fe7_New-WDPublishSettings.ps1
Add-PSSnapin WDeploySnapin3.0 New-WDPublishSettings ` -ComputerName "virjole-wfe1" ` -EncryptPassword:$true ` -FileName "C:\temp\virjole-wfe1.publishsettings" ` -UserId "hyper-v\wd_remote" ` -Password "pass@word1" ` -AgentType:WMSvc ` -AllowUntrusted:$true
PowerShellCorpus/GithubGist/phantomtypist_9a2c3ac50d55c726f7b0_raw_f322bf364a481fddabadb1b3a3e1172471f18bf2_Boxstarter-01-Update-Windows.ps1
phantomtypist_9a2c3ac50d55c726f7b0_raw_f322bf364a481fddabadb1b3a3e1172471f18bf2_Boxstarter-01-Update-Windows.ps1
# http://boxstarter.org/package/url? # Boxstarter options $Boxstarter.RebootOk=$true # Allow reboots? $Boxstarter.NoPassword=$false # Is this a machine with no login password? $Boxstarter.AutoLogin=$true # Save my password securely and auto-login after a reboot ##################### # BEGIN CONFIGURATION ##################### #region Initial Windows Config Install-WindowsUpdate -AcceptEula Update-ExecutionPolicy Unrestricted Enable-RemoteDesktop Enable-MicrosoftUpdate Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -EnableShowFileExtensions Disable-InternetExplorerESC #endregion # Let's get the latest version of powershell, .net frameworks, etc. cinst binroot cinst PowerShell cinst ChocolateyGUI cinst DotNet3.5 cinst DotNet4.0 cinst DotNet4.5 cinst DotNet4.5.1 cinst mono
PowerShellCorpus/GithubGist/belotn_7198387_raw_982cace4cb21e1be1c49aacbeca2bafe4fb38a1e_RemoteInstall.ps1
belotn_7198387_raw_982cace4cb21e1be1c49aacbeca2bafe4fb38a1e_RemoteInstall.ps1
######################################################### # FileName RemoteInstall.ps1 # # Version 0.3 # # Author Nicolas # ######################################################### # ChangeLog # # # # Version 0.3 # # Author Nicolas # # Content Utilisation d'un fichier XML # pour stocker les actions # # # # Version 0.2 # # Author Nicolas # # Content Ajout d'un système de multi # # installation de composant "Actions List" # # # # Version 0.1 # # Author Nicolas # # Content Initial Realase # ######################################################### # TODO # # WSUS Forced Install # ######################################################### #Chargement des Actions depuis le fichier action_list.xml ([xml]( gc .\action_list.xml)).actions.action |% { new-variable -Name $_.name -value $_ } #Déploiement #Ajout des composant Citrix si non chargé If ((Get-PSSnapin -Name "Citrix*" -ErrorAction SilentlyContinue | Measure-Object).count -eq 0) {Add-PSSnapin -Name "Citrix*"} Write-host Installation import-csv .\Folders.txt -delim ';' |% { #Récupération de la liste des serveurs qui vont redemarrer dans 1h $servers = get-xaserver -FolderPath $_.Folder |Select ServerNAme,@{N="Last reboot";E={(get-date).AddSeconds( - (gwmi -ComputerName $_.ServerNAme Win32_PerfFormattedData_PerfOS_System).systemuptime) }} |? { $_.'Last Reboot'.dayOfweek -eq [DateTime]::Now.AddDays(-7).DayOfWeek } $action = $_.action if( $servers -and (Get-Variable |? { $_.NAme -eq $action })){#L'action existe ? $myAction = get-variable $action -valueonly $servers |% { Write-host $_.ServerName #copie des fichiers nécessaire if( -not (test-path \\$($_.serverName)\c$\tmp )){ new-item \\$($_.serverName)\c$\tmp -type directory} if( $myAction.file ){ cpi $myAction.file \\$($_.serverName)\c$\tmp } #lancement de l'installation $process = [WMICLASS]"\\$($_.ServerName)\ROOT\CIMV2:win32_process" $result = $process.Create($myAction.script) } #temporisation Start-Sleep -second 120 Write-host suppression $servers |% { Write-host $_.ServerName if( $myAction.clean ){ #Attente de la fin d'installation while( -not( Select-String \\$($_.ServerNAme)\c$\tmp\$($myAction.clean[0]) -pattern ($myAction.clean[1]) -quiet )){ Start-Sleep -second 120 } #Suppression des fichiers copiés if( (get-variable $action -valueonly).file ){ remove-item \\$($_.ServerNAme)\c$\tmp\$( Split-PAth -Leaf $myAction.file ) } } } } }
PowerShellCorpus/GithubGist/quakersquares_5548299_raw_419c3e9a5c078b82d0fecd2bfda64d2f8c91eba3_ReplStatus.ps1
quakersquares_5548299_raw_419c3e9a5c078b82d0fecd2bfda64d2f8c91eba3_ReplStatus.ps1
# ============================================================================================== # NAME: Check-Replication # # AUTHOR: Maish Saidel-Keesing # DATE : 27/04/2010 # # COMMENT: Will check the replication status and if there are failures will send an email to the # Assigned Addresses. # ** Requires Repadmin from the Windows resource Kit accessible in the default path ** # ============================================================================================== $from = "Replication Status<[email protected]>" $to = "Alex<[email protected]>" #Collect the replication info #Check the Replication with Repadmin $workfile = C:\Windows\System32\repadmin.exe /showrepl * /csv $results = ConvertFrom-Csv -InputObject $workfile #Here you set the tolerance level for the report $results = $results | select "Source DC", "Naming Context", "Destination DC" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status" | ConvertTo-Html Send-MailMessage -From $from -To $to -Subject "Daily Forest Replication Status" -SmtpServer "12.53.115.28" -BodyAsHtml ($results | Out-String)
PowerShellCorpus/GithubGist/Steh_8728329_raw_af9b5e3528591c13d89bbc573cfa24d32da7f323_MessageTrackingOU.ps1
Steh_8728329_raw_af9b5e3528591c13d89bbc573cfa24d32da7f323_MessageTrackingOU.ps1
$mbx = Get-Mailbox -OrganizationalUnit <OU> $srv = Get-TransportServer stehsa-* | Sort-Object Name ForEach($i in $mbx) { $i.PrimarySmtpAddress ForEach($x in $srv) { $x.Name Get-MessageTrackingLog -Server $x.DistinguishedName -Recipients $i.PrimarySmtpAddress | Select-Object Sender >> C:\Export\mail.txt } } Remove-Variable mbx, srv
PowerShellCorpus/GithubGist/stevengorrell_9974119_raw_f47e5cd17c9eb211b4a0db7b2f6e7c791d6bcdd3_Bootstrap-EC2-Windows-CloudInit.ps1
stevengorrell_9974119_raw_f47e5cd17c9eb211b4a0db7b2f6e7c791d6bcdd3_Bootstrap-EC2-Windows-CloudInit.ps1
#ps1 # Windows AMIs don't have WinRM enabled by default -- this script will enable WinRM # AND install 7-zip, curl and .NET 4 if its missing. # Then use the EC2 tools to create a new AMI from the result, and you have a system # that will execute user-data as a PowerShell script after the instance fires up! # This has been tested on Windows 2008 SP2 64bits AMIs provided by Amazon # # Inject this as user-data of a Windows 2008 AMI, like this (edit the adminPassword to your needs): # # <powershell> # Set-ExecutionPolicy Unrestricted # icm $executioncontext.InvokeCommand.NewScriptBlock((New-Object Net.WebClient).DownloadString('https://gist.github.com/masterzen/6714787/raw')) -ArgumentList "adminPassword" # </powershell> # param( [Parameter(Mandatory=$true)] [string] $AdminPassword ) Start-Transcript -Path 'c:\bootstrap-transcript.txt' -Force Set-StrictMode -Version Latest Set-ExecutionPolicy Unrestricted $log = 'c:\Bootstrap.txt' while (($AdminPassword -eq $null) -or ($AdminPassword -eq '')) { $AdminPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host "Enter a non-null / non-empty Administrator password" -AsSecureString))) } $systemPath = [Environment]::GetFolderPath([Environment+SpecialFolder]::System) $sysNative = [IO.Path]::Combine($env:windir, "sysnative") #http://blogs.msdn.com/b/david.wang/archive/2006/03/26/howto-detect-process-bitness.aspx $Is32Bit = (($Env:PROCESSOR_ARCHITECTURE -eq 'x86') -and ($Env:PROCESSOR_ARCHITEW6432 -eq $null)) Add-Content $log -value "Is 32-bit [$Is32Bit]" #http://msdn.microsoft.com/en-us/library/ms724358.aspx $coreEditions = @(0x0c,0x27,0x0e,0x29,0x2a,0x0d,0x28,0x1d) $IsCore = $coreEditions -contains (Get-WmiObject -Query "Select OperatingSystemSKU from Win32_OperatingSystem" | Select -ExpandProperty OperatingSystemSKU) Add-Content $log -value "Is Core [$IsCore]" # move to home, PS is incredibly complex :) cd $Env:USERPROFILE Set-Location -Path $Env:USERPROFILE [Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath #change admin password net user Administrator $AdminPassword Add-Content $log -value "Changed Administrator password" $client = new-object System.Net.WebClient #.net 4 if ((Test-Path "${Env:windir}\Microsoft.NET\Framework\v4.0.30319") -eq $false) { $netUrl = if ($IsCore) {'http://download.microsoft.com/download/3/6/1/361DAE4E-E5B9-4824-B47F-6421A6C59227/dotNetFx40_Full_x86_x64_SC.exe' } ` else { 'http://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe' } $client.DownloadFile( $netUrl, 'dotNetFx40_Full.exe') Start-Process -FilePath 'C:\Users\Administrator\dotNetFx40_Full.exe' -ArgumentList '/norestart /q /ChainingPackage ADMINDEPLOYMENT' -Wait -NoNewWindow del dotNetFx40_Full.exe Add-Content $log -value "Found that .NET4 was not installed and downloaded / installed" } #configure powershell to use .net 4 $config = @' <?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- http://msdn.microsoft.com/en-us/library/w4atty68.aspx --> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" /> <supportedRuntime version="v2.0.50727" /> </startup> </configuration> '@ if (Test-Path "${Env:windir}\SysWOW64\WindowsPowerShell\v1.0\powershell.exe") { $config | Set-Content "${Env:windir}\SysWOW64\WindowsPowerShell\v1.0\powershell.exe.config" Add-Content $log -value "Configured 32-bit Powershell on x64 OS to use .NET 4" } if (Test-Path "${Env:windir}\system32\WindowsPowerShell\v1.0\powershell.exe") { $config | Set-Content "${Env:windir}\system32\WindowsPowerShell\v1.0\powershell.exe.config" Add-Content $log -value "Configured host OS specific Powershell at ${Env:windir}\system32\ to use .NET 4" } #check winrm id, if it's not valid and LocalAccountTokenFilterPolicy isn't established, do it $id = &winrm id if (($id -eq $null) -and (Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -ErrorAction SilentlyContinue) -eq $null) { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -value 1 -propertyType dword Add-Content $log -value "Added LocalAccountTokenFilterPolicy since winrm id could not be executed" } #enable powershell servermanager cmdlets (only for 2008 r2 + above) if ($IsCore) { DISM /Online /Enable-Feature /FeatureName:MicrosoftWindowsPowerShell /FeatureName:ServerManager-PSH-Cmdlets /FeatureName:BestPractices-PSH-Cmdlets Add-Content $log -value "Enabled ServerManager and BestPractices Cmdlets" #enable .NET flavors - on server core only -- errors on regular 2008 DISM /Online /Enable-Feature /FeatureName:NetFx2-ServerCore /FeatureName:NetFx2-ServerCore-WOW64 /FeatureName:NetFx3-ServerCore /FeatureName:NetFx3-ServerCore-WOW64 Add-Content $log -value "Enabled .NET frameworks 2 and 3 for x86 and x64" } #7zip $7zUri = if ($Is32Bit) { 'http://sourceforge.net/projects/sevenzip/files/7-Zip/9.22/7z922.msi/download' } ` else { 'http://sourceforge.net/projects/sevenzip/files/7-Zip/9.22/7z922-x64.msi/download' } $client.DownloadFile( $7zUri, '7z922.msi') Start-Process -FilePath "msiexec.exe" -ArgumentList '/i 7z922.msi /norestart /q INSTALLDIR="c:\program files\7-zip"' -Wait SetX Path "${Env:Path};C:\Program Files\7-zip" /m $Env:Path += ';C:\Program Files\7-Zip' del 7z922.msi Add-Content $log -value "Installed 7-zip from $7zUri and updated path" #vc 2010 redstributable $vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/5/B/C/5BC5DBB3-652D-4DCE-B14A-475AB85EEF6E/vcredist_x86.exe'} ` else { 'http://download.microsoft.com/download/3/2/2/3224B87F-CFA0-4E70-BDA3-3DE650EFEBA5/vcredist_x64.exe' } $client.DownloadFile( $vcredist, 'vcredist.exe') Start-Process -FilePath 'C:\Users\Administrator\vcredist.exe' -ArgumentList '/norestart /q' -Wait del vcredist.exe Add-Content $log -value "Installed VC++ 2010 Redistributable from $vcredist and updated path" #vc 2008 redstributable $vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/d/d/9/dd9a82d0-52ef-40db-8dab-95376989c03/vcredist_x86.exe'} ` else { 'http://download.microsoft.com/download/d/2/4/d242c3fb-da5a-4542-ad66-f9661d0a8d19/vcredist_x64.exe' } $client.DownloadFile( $vcredist, 'vcredist.exe') Start-Process -FilePath 'C:\Users\Administrator\vcredist.exe' -ArgumentList '/norestart /q' -Wait del vcredist.exe Add-Content $log -value "Installed VC++ 2008 Redistributable from $vcredist and updated path" #curl $curlUri = if ($Is32Bit) { 'http://www.paehl.com/open_source/?download=curl_724_0_ssl.zip' } ` else { 'http://curl.haxx.se/download/curl-7.23.1-win64-ssl-sspi.zip' } $client.DownloadFile( $curlUri, 'curl.zip') &7z e curl.zip `-o`"c:\program files\curl`" if ($Is32Bit) { $client.DownloadFile( 'http://www.paehl.com/open_source/?download=libssl.zip', 'libssl.zip') &7z e libssl.zip `-o`"c:\program files\curl`" del libssl.zip } SetX Path "${Env:Path};C:\Program Files\Curl" /m $Env:Path += ';C:\Program Files\Curl' del curl.zip Add-Content $log -value "Installed Curl from $curlUri and updated path" #vim curl -# -G -k -L ftp://ftp.vim.org/pub/vim/pc/vim73_46rt.zip -o vim73_46rt.zip 2>&1 > "$log" curl -# -G -k -L ftp://ftp.vim.org/pub/vim/pc/vim73_46w32.zip -o vim73_46w32.zip 2>&1 > "$log" Get-ChildItem -Filter vim73*.zip | % { &7z x `"$($_.FullName)`"; del $_.FullName; } SetX Path "${Env:Path};C:\Program Files\Vim" /m $Env:Path += ';C:\Program Files\Vim' Move-Item .\vim\vim73 -Destination "${Env:ProgramFiles}\Vim" Add-Content $log -value "Installed Vim text editor and updated path" #chocolatey - standard one line installer doesn't work on Core b/c Shell.Application can't unzip if (-not $IsCore) { Invoke-Expression ((new-object net.webclient).DownloadString('http://bit.ly/psChocInstall')) } else { #[Environment]::SetEnvironmentVariable('ChocolateyInstall', 'c:\nuget', [System.EnvironmentVariableTarget]::User) #if (![System.IO.Directory]::Exists('c:\nuget')) {[System.IO.Directory]::CreateDirectory('c:\nuget')} $tempDir = Join-Path $env:TEMP "chocInstall" if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)} $file = Join-Path $tempDir "chocolatey.zip" $client.DownloadFile("http://chocolatey.org/api/v1/package/chocolatey", $file) &7z x $file `-o`"$tempDir`" Add-Content $log -value 'Extracted Chocolatey' $chocInstallPS1 = Join-Path (Join-Path $tempDir 'tools') 'chocolateyInstall.ps1' & $chocInstallPS1 Add-Content $log -value 'Installed Chocolatey / Verifying Paths' } Add-Content $log -value "Installed Chocolatey" # install puppet #https://downloads.puppetlabs.com/windows/puppet-3.2.4.msi curl -# -G -k -L https://downloads.puppetlabs.com/windows/puppet-3.2.4.msi -o puppet-3.2.4.msi 2>&1 > "$log" Start-Process -FilePath "msiexec.exe" -ArgumentList '/qn /passive /i puppet-3.2.4.msi /norestart' -Wait SetX Path "${Env:Path};C:\Program Files\Puppet Labs\Puppet\bin" /m &sc.exe config puppet start= demand Add-Content $log -value "Installed Puppet" #&winrm quickconfig `-q #&winrm set winrm/config/client/auth '@{Basic="true"}' #&winrm set winrm/config/service/auth '@{Basic="true"}' #&winrm set winrm/config/service '@{AllowUnencrypted="true"}' #Add-Content $log -value "Ran quickconfig for winrm" &netsh firewall set portopening tcp 445 smb enable Add-Content $log -value "Ran firewall config to allow incoming smb/tcp" #run SMRemoting script to enable event log management, etc - available only on R2 $remotingScript = [IO.Path]::Combine($systemPath, 'Configure-SMRemoting.ps1') if (-not (Test-Path $remotingScript)) { $remotingScript = [IO.Path]::Combine($sysNative, 'Configure-SMRemoting.ps1') } Add-Content $log -value "Found Remoting Script: [$(Test-Path $remotingScript)] at $remotingScript" if (Test-Path $remotingScript) { . $remotingScript -force -enable Add-Content $log -value 'Ran Configure-SMRemoting.ps1' } #wait a bit, it's windows after all Start-Sleep -m 10000 #Write-Host "Press any key to reboot and finish image configuration" #[void]$host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') Restart-Computer
PowerShellCorpus/GithubGist/janikvonrotz_7823559_raw_90e9932228c405da72ad06792fddf7e0210d77d2_Check-PSCompatibility.ps1
janikvonrotz_7823559_raw_90e9932228c405da72ad06792fddf7e0210d77d2_Check-PSCompatibility.ps1
# Check for executeable if ((Get-Command "cmdkey.exe") -and (Get-Command "mstsc.exe")) { } # Execute with Powershell version 2 instead of version 3 and higher if($Host.Version.Major -gt 2){ powershell -Version 2 $MyInvocation.MyCommand.Definition exit } # only powershell 2 and higher if($Host.Version.Major -lt 2){ throw "Only compatible with Powershell version 2 and higher" }else{ }
PowerShellCorpus/GithubGist/sunnyc7_cc62b79263d261d898e6_raw_81151e84015846f95186c6c4ebf59c9c91874707_Set-ReverseString.ps1
sunnyc7_cc62b79263d261d898e6_raw_81151e84015846f95186c6c4ebf59c9c91874707_Set-ReverseString.ps1
# Golang inspired. # https://www.youtube.com/watch?v=XCsL89YtqCs Function Set-ReverseString { param ( [string]$s) process { $b = [char[]] ($s) for ($i =0; $i -lt $(($s.Length)/2) ;$i++){ $j =$b.Length - $i -1 $b[$i],$b[$j] = $b[$j],$b[$i] } [string]::join("",$b) } } Trace-Command -PSHost ParameterBinderBase -Expression { Set-ReverseString -s "Funnys" }
PowerShellCorpus/GithubGist/scichelli_4151973_raw_4b7dba5d636e5db0b5c649f21d617f2ccc52d5fa_sleep.ps1
scichelli_4151973_raw_4b7dba5d636e5db0b5c649f21d617f2ccc52d5fa_sleep.ps1
$WarningDuration = 5 $MessagePlural = "" if ($WarningDuration -gt 1) { $MessagePlural = "s" } [System.Media.SystemSounds]::Asterisk.play() [void] [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [windows.forms.messagebox]::show(("Save your work. Sleep in {0} minute{1}." -f $WarningDuration, $MessagePlural)) Start-Sleep -Second ($WarningDuration * 60) [System.Media.SystemSounds]::Beep.play() Start-Sleep -Second 2 [System.Windows.Forms.Application]::SetSuspendState("Suspend", $false, $true)
PowerShellCorpus/GithubGist/mikeplate_69a270411f23a4f49298_raw_3b6225eb530b597463120780a52107756d357de2_list_net_versions.ps1
mikeplate_69a270411f23a4f49298_raw_3b6225eb530b597463120780a52107756d357de2_list_net_versions.ps1
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | Get-ItemProperty -name Version -EA 0 | Where { $_.PSChildName -match '^(?!S)\p{L}'} | Select PSChildName, Version
PowerShellCorpus/GithubGist/mortenya_fe07bb219925e114fcf3_raw_b1d451c5eefe8d633aaec02fef6cd993f4052a34_Generate-RandomPassword.ps1
mortenya_fe07bb219925e114fcf3_raw_b1d451c5eefe8d633aaec02fef6cd993f4052a34_Generate-RandomPassword.ps1
$Computers = Get-ADComputer -Filter * | Where distinguishedName -NotLike "*DC*" $user = Get-WmiObject Win32_UserAccount -Filter "LocalAccount=true" | where { $_.Name -eq 'Administrator' } $Count = 1 $CharSet1 = [Char[]]"abcdefghijklmnopqrstuvwxyz1234567890" ForEach ($c in $Computers) { Write-Progress -Id 1 -Activity "Changing Server Passwords" -Status "Current Progress: $Count of $($Servers.Count): $($Server.Name)" -PercentComplete (($Count / $c.Count) * 100) $Ping = Test-Connection $c.Name -Count 2 -Quiet If ($Ping) { $Password = (($CharSet1 | Get-Random -Count 5) -join "") + " " + ` (($CharSet1 | Get-Random -Count 5) -join "") + " " + ` (($CharSet1 | Get-Random -Count 5) -join "") Try { $User = [ADSI]"WinNT://$($Server.Name)/$($user),user" $User.SetPassword($Password) $User.SetInfo() Start-Sleep -Milliseconds 500 } Catch { Write-Warning "Unable to change password for "$($c.Name)" because "$($Error[0])"" } } Else { Write-Warning "Unable to ping $($Server.Name)" } $count++ }
PowerShellCorpus/GithubGist/HowardvanRooijen_4313af807f8405b1b01b_raw_dd736e09269c762361f69676039e5308fbcc6edd_NotifyNewRelic.ps1
HowardvanRooijen_4313af807f8405b1b01b_raw_dd736e09269c762361f69676039e5308fbcc6edd_NotifyNewRelic.ps1
try { $body = ""; if ([String]::IsNullOrEmpty($apiKey)){ throw "API Key is required" } else { $headers += @{"x-api-key"=($apiKey)}; } if ([String]::IsNullOrEmpty($appName)){ throw "App Name is required" } else { $body += "deployment[app_name]=$appName"; } if (![String]::IsNullOrEmpty($changeLog)){ $body += "&deployment[changelog]=$changeLog"; } if (![String]::IsNullOrEmpty($description)){ $body += "&deployment[description]=$description"; } if (![String]::IsNullOrEmpty($environment)){ $body += "&deployment[environment]=$environment"; } if (![String]::IsNullOrEmpty($revision)){ $body += "&deployment[revision]=$revision"; } if (![String]::IsNullOrEmpty($user)){ $body += "&deployment[user]=$user"; } $result = Invoke-RestMethod -Uri $url -Headers $headers -Body $body Write-Host $result } catch { Write-Error $_ [System.Environment]::Exit(1) }
PowerShellCorpus/GithubGist/kmpm_2996955_raw_2e6d7cb3c7b3e9dcb94be3a372ac82292e175483_GitHub.PowerShell_profile.ps1
kmpm_2996955_raw_2e6d7cb3c7b3e9dcb94be3a372ac82292e175483_GitHub.PowerShell_profile.ps1
# <My Documents>\WindowsPowershell\GitHub.PowerShell_profile.ps1 # If Posh-Git environment is defined, load it. if (test-path env:posh_git) { . $env:posh_git } # If module is installed in a default location ($env:PSModulePath), # use this instead (see about_Modules for more information): # Import-Module posh-git # Set up a simple prompt, adding the git prompt parts inside git repos function prompt { $realLASTEXITCODE = $LASTEXITCODE # Reset color, which can be messed up by Enable-GitColors $Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor Write-Host($pwd) -nonewline Write-VcsStatus $global:LASTEXITCODE = $realLASTEXITCODE return "`n> " } Enable-GitColors Pop-Location Start-SshAgent -Quiet
PowerShellCorpus/GithubGist/GuruAnt_7215567_raw_bcd1def81db9ba941d53104b9fdc9f3117e6b8e2_RenameVMTemplates.ps1
GuruAnt_7215567_raw_bcd1def81db9ba941d53104b9fdc9f3117e6b8e2_RenameVMTemplates.ps1
# Get all templates $objTemplates = Get-Template # Loop through the templates ForEach ($objTemplate in $objTemplates){ # Set the $StrInterimTemplateName variable to the template name, replacing the string "Tmpl" with an empty string $StrInterimTemplateName = ($objTemplate.Name -replace("Tmpl","")) # As the string we've just removed might be anywhere in the name, we need to replace double spaces with single $StrInterimTemplateName = ($StrInterimTemplateName -replace(" "," ")) # And also remove trailing spaces from the start, or the end of the string $StrInterimTemplateName = $StrInterimTemplateName.Trim() # Display on screen what we're doing (as the "Set-Template" with -WhatIf isn't very clear Write-Host Changing `[($objTemplate.Name)`] to `[ Tmpl $StrInterimTemplateName `] # Change the Template Name to the $StrInterimTemplateName variable preceeded by "Tmpl", uncomment the #-WhatIf if testing Set-Template -Template $objTemplate -Name "Tmpl $StrInterimTemplateName" #-WhatIf }
PowerShellCorpus/GithubGist/zakird_a8582ced2f50cfe1c702_raw_ca3cc10d035df0ca788615876da709cf20541726_get-root-cas.ps1
zakird_a8582ced2f50cfe1c702_raw_ca3cc10d035df0ca788615876da709cf20541726_get-root-cas.ps1
$type = [System.Security.Cryptography.X509Certificates.X509ContentType]::Cert get-childitem -path cert:\LocalMachine\AuthRoot | ForEach-Object { $hash = $_.GetCertHashString() [System.IO.File]::WriteAllBytes("$hash.der", $_.export($type) ) }
PowerShellCorpus/GithubGist/dotps1_9215724_raw_a63e0b7650a820b12beef703dbf703211954e765_Get-UnEncryptedWorkstationsFromCMDB.ps1
dotps1_9215724_raw_a63e0b7650a820b12beef703dbf703211954e765_Get-UnEncryptedWorkstationsFromCMDB.ps1
<# .SYNOPSIS Queries ConfigMgr Database for BitLockerProtectionStatus Boolean Value. .DESCRIPTION Queries ConfigMgr Database for any workstation that has completed a Hardware Inventory Scan, looks for the BitLockerProtectionStatus Value, 1 is fully encrypted and Protection is on, 0 for anything else. Also uses the inventoried file: 'Orginal System Loader' which is used by TrueCrypt to indicate full disk encryption. .EXAMPLE Get-UnEncryptedWorkstationsFromCMDB .EXAMPLE Get-UnEncryptedWorkstationsFromCMDB -SqlServer localhost -Database ConfigMgr -IntergratedSecurity .NOTES The BDE Status of a workstation is not inventoried with ConfigMgr by default, it needs to be enabled in the client settings.. The file 'Orginal System Loader' is not inventoried with ConfigMgr by default, it needs to be configured in the client settings. The file location is %ProgramData%\TrueCrypt\Original System Loader. .LINK http://dotps1.github.io Twitter: @dotps1 #> function Get-UnEncryptedWorkstationsFromCMDB { [CmdletBinding()] [OutputType([Array])] param ( # SqlServer, Type String, The SQL Server containing the ConfigMgr database. [Parameter(Mandatory = $true, Position = 0)] [ValidateScript({ if (-not(Test-Connection -ComputerName $_ -Quiet -Count 2)) { throw "Failed to connect to $_. Please ensure the system is available." } else { $true } })] [String] $SqlServer = $env:COMPUTERNAME, # ConnectionPort, Type Int, Port to connect to SQL server with, defualt value is 1433. [parameter(Position = 1)] [ValidateRange(1,50009)] [Alias("Port")] [Int] $ConnectionPort = 1433, # Database, Type String, The name of the ConfigMgr database. [Parameter(Mandatory = $true, Position = 2)] [String] $Database, # IntergratedSecurity, Type Switch, Use the currently logged on users credentials. [Switch] $IntergratedSecurity ) $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $sqlConnection.ConnectionString="Server=$SqlServer,$ConnectionPort;Database=$Database;Integrated Security=" if ($IntergratedSecurity) { $sqlConnection.ConnectionString += "true;" } else { $sqlCredentials = Get-Credential $sqlConnection.ConnectionString += "false;User ID=$($sqlCredentials.Username);Password=$($sqlCredentials.GetNetworkCredential().Password);" } try { $sqlConnection.Open() } catch { throw $Error[0].Exception.Message } $sqlCMD = New-Object System.Data.SqlClient.SqlCommand $sqlCMD.CommandText = "with ct_CollectedFiles (FileName,ClientID) as (select dbo.CollectedFiles.FileName, dbo.CollectedFiles.ClientID from dbo.CollectedFiles), ct_Everything (ComputerName,DriveLetter,BitLockerStatus) as (select dbo.Computer_System_DATA.Name00 as ComputerName, left(dbo.Operating_System_DATA.SystemDirectory00, 2) as DriveLetter, case dbo.ENCRYPTABLE_VOLUME_DATA.ProtectionStatus00 when '1' then 'Enabled' when '0' then case ct_CollectedFiles.FileName when 'Original System Loader' then 'Enabled' else 'Disabled or Suspended' end end as BitLockerStatus from dbo.Operating_System_DATA join dbo.ENCRYPTABLE_VOLUME_DATA on dbo.Operating_System_DATA.MachineID = dbo.ENCRYPTABLE_VOLUME_DATA.MachineID join dbo.Computer_System_DATA on dbo.Operating_System_DATA.MachineID = dbo.Computer_System_DATA.MachineID left join ct_CollectedFiles on dbo.Operating_System_DATA.MachineID = ct_CollectedFiles.ClientID where dbo.ENCRYPTABLE_VOLUME_DATA.DriveLetter00 = left(dbo.Operating_System_DATA.SystemDirectory00, 2) and dbo.Operating_System_Data.ProductType00 <> '3' and dbo.Computer_System_DATA.Manufacturer00 not like '%VMware, Inc.%' and dbo.Computer_System_DATA.Manufacturer00 not like '%Xen%') select * from ct_Everything where BitLockerStatus = 'Disabled or Suspended' order by 'ComputerName' asc" $sqlCMD.Connection = $sqlConnection $results = $sqlCMD.ExecuteReader() If ($results.HasRows) { While ($results.Read()) { $workstations += @($results["ComputerName"]) } return $workstations } $results.Close() $sqlConnection.Close() }
PowerShellCorpus/GithubGist/geoffreysmith_912395_raw_d1d625417da9f11736c2c4b211a721e405b7be9a_MvcScaffolding.Controller.ps1
geoffreysmith_912395_raw_d1d625417da9f11736c2c4b211a721e405b7be9a_MvcScaffolding.Controller.ps1
[T4Scaffolding.ControllerScaffolder("Controller with read/write action and views, using EF data access code", Description = "Adds an ASP.NET MVC controller with views and data access code", SupportsModelType = $true, SupportsDataContextType = $true, SupportsViewScaffolder = $true)][CmdletBinding()] param( [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)][string]$ControllerName, [string]$ModelType, [string]$Project, [string]$CodeLanguage, [string]$DbContextType, [string]$Area, [string]$ViewScaffolder = "View", [alias("MasterPage")][string]$Layout, [alias("ContentPlaceholderIDs")][string[]]$SectionNames, [alias("PrimaryContentPlaceholderID")][string]$PrimarySectionName, [switch]$ReferenceScriptLibraries = $false, [switch]$Repository = $false, [switch]$NoChildItems = $false, [string[]]$TemplateFolders, [switch]$Force = $false ) if (!((Get-ProjectAspNetMvcVersion -Project $Project) -ge 3)) { Write-Error ("Project '$((Get-Project $Project).Name)' is not an ASP.NET MVC 3 project.") return } # Ensure you've referenced System.Data.Entity (Get-Project $Project).Object.References.Add("System.Data.Entity") | Out-Null # If you haven't specified a model type, we'll guess from the controller name if (!$ModelType) { if ($ControllerName.EndsWith("Controller", [StringComparison]::OrdinalIgnoreCase)) { # If you've given "PeopleController" as the full controller name, we're looking for a model called People or Person $ModelType = [System.Text.RegularExpressions.Regex]::Replace($ControllerName, "Controller$", "", [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) $foundModelType = Get-ProjectType $ModelType -Project $Project -BlockUi -ErrorAction SilentlyContinue if (!$foundModelType) { $ModelType = [string](Get-SingularizedWord $ModelType) $foundModelType = Get-ProjectType $ModelType -Project $Project -BlockUi -ErrorAction SilentlyContinue } } else { # If you've given "people" as the controller name, we're looking for a model called People or Person, and the controller will be PeopleController $ModelType = $ControllerName $foundModelType = Get-ProjectType $ModelType -Project $Project -BlockUi -ErrorAction SilentlyContinue if (!$foundModelType) { $ModelType = [string](Get-SingularizedWord $ModelType) $foundModelType = Get-ProjectType $ModelType -Project $Project -BlockUi -ErrorAction SilentlyContinue } if ($foundModelType) { $ControllerName = [string]($foundModelType.Name) + "Controller" } } if (!$foundModelType) { throw "Cannot find a model type corresponding to a controller called '$ControllerName'. Try supplying a -ModelType parameter value." } } else { # If you have specified a model type $foundModelType = Get-ProjectType $ModelType -Project $Project -BlockUi if (!$foundModelType) { return } if (!$ControllerName.EndsWith("Controller", [StringComparison]::OrdinalIgnoreCase)) { $ControllerName = $ControllerName + "Controller" } } Write-Host "Scaffolding $ControllerName..." #if(!$DbContextType) { $DbContextType = [System.Text.RegularExpressions.Regex]::Replace((Get-Project $Project).Name, "[^a-zA-Z0-9]", "") + "Context" } #if (!$NoChildItems) { # if ($Repository) { # Scaffold Repository -ModelType $foundModelType.FullName -DbContextType $DbContextType -Area $Area -Project $Project -CodeLanguage $CodeLanguage -Force:$Force -BlockUi # } else { #$dbContextScaffolderResult = Scaffold DbContext -ModelType $foundModelType.FullName -DbContextType $DbContextType -Area $Area -Project $Project -CodeLanguage $CodeLanguage -BlockUi #$foundDbContextType = $dbContextScaffolderResult.DbContextType #} #} $primaryKey = Get-PrimaryKey $foundModelType.FullName -Project $Project -ErrorIfNotFound if (!$primaryKey) { return } $outputPath = Join-Path Controllers $ControllerName # We don't create areas here, so just ensure that if you specify one, it already exists if ($Area) { $areaPath = Join-Path Areas $Area if (-not (Get-ProjectItem $areaPath -Project $Project)) { Write-Error "Cannot find area '$Area'. Make sure it exists already." return } $outputPath = Join-Path $areaPath $outputPath } # Prepare all the parameter values to pass to the template, then invoke the template with those values $repositoryName = $foundModelType.Name + "Repository" $defaultNamespace = (Get-Project $Project).Properties.Item("DefaultNamespace").Value $modelTypeNamespace = [T4Scaffolding.Namespaces]::GetNamespace($foundModelType.FullName) $controllerNamespace = [T4Scaffolding.Namespaces]::Normalize($defaultNamespace + "." + [System.IO.Path]::GetDirectoryName($outputPath).Replace([System.IO.Path]::DirectorySeparatorChar, ".")) $areaNamespace = if ($Area) { [T4Scaffolding.Namespaces]::Normalize($defaultNamespace + ".Areas.$Area") } else { $defaultNamespace } $dbContextNamespace = if($foundDbContextType) { $foundDbContextType.Namespace.FullName } else { [T4Scaffolding.Namespaces]::Normalize($areaNamespace + ".Models") } $repositoriesNamespace = [T4Scaffolding.Namespaces]::Normalize($areaNamespace + ".Models") $modelTypePluralized = Get-PluralizedWord $foundModelType.Name $relatedEntities = [Array](Get-RelatedEntities $foundModelType.FullName -Project $project) if (!$relatedEntities) { $relatedEntities = @() } $templateName = if($Repository) { "ControllerWithRepository" } else { "ControllerWithContext" } Add-ProjectItemViaTemplate $outputPath -Template $templateName -Model @{ ControllerName = $ControllerName; ModelType = [MarshalByRefObject]$foundModelType; PrimaryKey = [string]$primaryKey; DefaultNamespace = $defaultNamespace; AreaNamespace = $areaNamespace; Namespace = $dbContextNamespace; RepositoriesNamespace = $repositoriesNamespace; ModelTypeNamespace = $modelTypeNamespace; ControllerNamespace = $controllerNamespace; #DbContextType = if($foundDbContextType) { $foundDbContextType.Name } else { $DbContextType }; Repository = $repositoryName; ModelTypePluralized = [string]$modelTypePluralized; RelatedEntities = $relatedEntities; } -SuccessMessage "Added controller {0}" -TemplateFolders $TemplateFolders -Project $Project -CodeLanguage $CodeLanguage -Force:$Force if (!$NoChildItems) { $controllerNameWithoutSuffix = [System.Text.RegularExpressions.Regex]::Replace($ControllerName, "Controller$", "", [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) if ($ViewScaffolder) { Scaffold Views -ViewScaffolder $ViewScaffolder -Controller $controllerNameWithoutSuffix -ModelType $foundModelType.FullName -Area $Area -Layout $Layout -SectionNames $SectionNames -PrimarySectionName $PrimarySectionName -ReferenceScriptLibraries:$ReferenceScriptLibraries -Project $Project -CodeLanguage $CodeLanguage -Force:$Force } }
PowerShellCorpus/GithubGist/tanordheim_76fc9343e687a5efcd66_raw_67993ef604a0b6026417068d96434829bf1ef632_DeployAzureWebsite.ps1
tanordheim_76fc9343e687a5efcd66_raw_67993ef604a0b6026417068d96434829bf1ef632_DeployAzureWebsite.ps1
param ( [Parameter(Position = 0, Mandatory=$True)] [string]$ProjectName, [Parameter(Position = 1, Mandatory=$True)] [string]$SiteName, [Parameter(Position = 2, Mandatory=$True)] [string]$Environment ) $NewRelicLicenseKey = "<license key>" $PackagePath = "$ProjectName.csproj.zip" $StagingSiteName = "$SiteName(staging)" $ApplicationEnvironment = "Testing"; if ($Environment -eq "production") { $ApplicationEnvironment = "Production"; } function AbortDeployment( $message ) { Write-Output "##teamcity[buildStatus status='FAILURE' text='$message']" Exit 1 } function StartTeamCityBlock( $name ) { Write-Output "##teamcity[blockOpened name='$name']" } function StopTeamCityBlock( $name ) { Write-Output "##teamcity[blockClosed name='$name']" } function LogTeamCityStatus( $message ) { Write-Output "##teamcity[message text='$message']" } if (!(Test-Path "$PackagePath")) { AbortDeployment "Web site package $PackagePath not found" } # # Initialize the Azure environment. # $SubscriptionName = "<Azure subscription name>" Select-AzureSubscription "$SubscriptionName" # # Stop the current staging web site and prepare for a new deployment. # function DeployPackageToStaging() { StartTeamCityBlock "Staging deployment" LogTeamCityStatus "Disabling NewRelic RPM profiling" $appSettings = @{ "COR_ENABLE_PROFILING" = "0"; } try { Set-AzureWebsite -Name "$SiteName" -Slot "staging" -AppSettings $appSettings -Verbose -ErrorAction Stop } catch { Write-Host "Exception caught during NewRelic deactivation ($($_.Exception.GetType().FullName)): $($_.Exception.Message)" AbortDeployment "Unable to deactivate NewRelic RPM" } LogTeamCityStatus "Deploying web site $StagingSiteName" try { Publish-AzureWebsiteProject -Name "$SiteName" -Slot "staging" -Package "$PackagePath" -Verbose -ErrorAction Stop } catch { Write-Host "Exception caught during deployment ($($_.Exception.GetType().FullName)): $($_.Exception.Message)" AbortDeployment "Unable to deploy website" } LogTeamCityStatus "Enabling NewRelic RPM profiling" $appSettings = @{ "COR_ENABLE_PROFILING" = "1"; "COR_PROFILER" = "{71DA0A04-7777-4EC6-9643-7D28B46A8A41}"; "COR_PROFILER_PATH" = "C:\Home\site\wwwroot\newrelic\NewRelic.Profiler.dll"; "NEWRELIC_HOME" = "C:\Home\site\wwwroot\newrelic"; "NEWRELIC_LICENSEKEY" = "$NewRelicLicenseKey"; "ApplicationEnvironment" = "$ApplicationEnvironment"; "NewRelic.AppName" = "$SiteName"; } try { Set-AzureWebsite -Name "$SiteName" -Slot "staging" -AppSettings $appSettings -Verbose -ErrorAction Stop } catch { Write-Host "Exception caught during NewRelic deactivation ($($_.Exception.GetType().FullName)): $($_.Exception.Message)" AbortDeployment "Unable to deactivate NewRelic RPM" } StopTeamCityBlock "Staging deployment" } # # Swap the current staging web site to the production site. # function SwapStagingToProduction() { StartTeamCityBlock "Production swap" LogTeamCityStatus "Swapping staging deployment to production" try { Switch-AzureWebsiteSlot -Name "$SiteName" -Force -Verbose -ErrorAction Stop } catch { Write-Host "Exception caught during slot swapping ($($_.Exception.GetType().FullName)): $($_.Exception.Message)" AbortDeployment "Unable to swap staging site to production" } StopTeamCityBlock "Production swap" } # # Main entry point; start the deployment process # DeployPackageToStaging SwapStagingToProduction LogTeamCityStatus "Azure Web Site $ProjectName successfully deployed to environment $Environment" Write-Output "##teamcity[buildStatus status='SUCCESS']"
PowerShellCorpus/GithubGist/andreaswasita_d9bc7f0ba1b557600ce5_raw_37363ca581e3d4167bd61b64ee4af533126803dd_Get-AzureVMExtension%20IaaSAntimalware.ps1
andreaswasita_d9bc7f0ba1b557600ce5_raw_37363ca581e3d4167bd61b64ee4af533126803dd_Get-AzureVMExtension%20IaaSAntimalware.ps1
$servicename = Read-Host -Prompt 'Azure Cloud Service:' $name = Read-Host -Prompt 'Azure VM:' # Get the VM $vm = Get-AzureVM –ServiceName $servicename –Name $name # Get Microsoft Antimalware Agent on Virtual Machine Get-AzureVMExtension -Publisher Microsoft.Azure.Security -ExtensionName IaaSAntimalware -Version 1.* -VM $vm.VM
PowerShellCorpus/GithubGist/mgreenegit_c366f14ed82c6139aa3c_raw_1a00aa7e182cfad964cd1d1f98afbe2bf1179a48_RemoteDesktop.ps1
mgreenegit_c366f14ed82c6139aa3c_raw_1a00aa7e182cfad964cd1d1f98afbe2bf1179a48_RemoteDesktop.ps1
# Run each commented section individually # Download new modules from the DSC Resource Kit Install-Module xRemoteDesktopAdmin, xNetworking # Generate a Configuration MOF file Configuration RemoteDesktop { Import-DscResource -ModuleName xRemoteDesktopAdmin, xNetworking Node localhost { xFirewall RemoteDesktopPort3389 { Name = 'Remote Desktop' DisplayGroup = 'Remote Desktop' Ensure = 'Present' Access = 'Allow' State = 'Enabled' Profile = 'Domain' Direction = 'Inbound' Protocol = 'TCP' LocalPort = 3389 } xRemoteDesktopAdmin EnableRemoteDesktop { Ensure = 'Present' UserAuthentication = 'Secure' } } } RemoteDesktop -outputpath C:\RDP\MOF # (WMF5) Test if the configuration is already true Compare-DscConfiguration -Path C:\RDP\MOF -Verbose # Apply the Configuration Start-DscConfiguration -Path C:\RDP\MOF -Wait -Verbose # Verify the Configuration Get-DscConfiguration
PowerShellCorpus/GithubGist/jhorsman_7adf1ce64e8870abfeb6_raw_f197a42b8ede1f546c28eae36f830bc3b289dcee_ServerAsWorkstation.ps1
jhorsman_7adf1ce64e8870abfeb6_raw_f197a42b8ede1f546c28eae36f830bc3b289dcee_ServerAsWorkstation.ps1
function SetOrAdd-ItemProperty ($key, $name, $value) { if (!(Test-Path $key)) { New-Item $key > $null } Set-ItemProperty $key $name $value } function Disable-ShutdownEventTracker { # source: http://technet.microsoft.com/en-us/library/cc776766(v=ws.10).aspx Out-BoxstarterLog "Disable: Shutdown Event Tracker..." SetOrAdd-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" ` "ShutdownreasonOn" ` 0 } function Disable-CrtlAltDeleteAtLogon { # source: http://www.win2008workstation.com/disabling-the-ctrlaltdel-prompt/#comment-113 Out-BoxstarterLog "Disable: Crtl+Alt+Delete at login..." SetOrAdd-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" ` "DisableCAD" ` 1 } function Enable-PerformanceForPrograms { # source: http://social.technet.microsoft.com/Forums/en-US/winservergen/thread/be3eb9a9-8266-406f-97ad-ef7d9f06cd46/ Out-BoxstarterLog "Enabling: Performance for Programs..." SetOrAdd-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\PriorityControl" ` "Win32PrioritySeparation" ` 38 } function Disable-ServerManagerAtLogon { # source: http://serverfault.com/questions/402440/turn-off-server-manager-on-login Out-BoxstarterLog "Disabling: opening Server Manager at logon..." SetOrAdd-ItemProperty "HKLM:\Software\Microsoft\ServerManager" ` "DoNotOpenServerManagerAtLogon" ` 1 } function Enable-AudioService { Out-BoxstarterLog "Enabling: Audio service..." Set-Service Audiosrv -startuptype automatic } function Reboot-IfNoThemesService { $service = Get-Service | where { $_.ServiceName -eq "Themes" } if ($service) { Out-BoxstarterLog "Themes service exists. No reboot requires." } else { Out-BoxstarterLog "Themes service does not exist. Performing reboot..." Invoke-Reboot } } function Enable-ThemesService { Out-BoxstarterLog "Enabling: Themes service..." Set-Service Themes -startuptype automatic } function Enable-DesktopExperience { Import-Module ServerManager Out-BoxstarterLog "Enabling: Desktop Experience..." Add-WindowsFeature Desktop-Experience } function Enable-PowerShellISE { Import-Module ServerManager Out-BoxstarterLog "Enabling: PowerShell Integrate Scripting Environment (ISE)..." Add-WindowsFeature PowerShell-ISE } function Enable-TelnetClient { Import-Module ServerManager Out-BoxstarterLog "Enabling: Telnet Client..." Add-WindowsFeature Telnet-Client } function Set-MoreExplorerOptions { param( [switch] $lockTheTaskBar, [switch] $showAllFoldersInExplorerNavigation, [switch] $automaticallyExpandToCurrentFolderInExplorerNavigation ) $key = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" if ($lockTheTaskBar) { Set-ItemProperty $key TaskbarSizeMove 0 } if ($showAllFoldersInExplorerNavigation) { Set-ItemProperty $key NavPaneShowAllFolders 1 } if ($automaticallyExpandToCurrentFolderInExplorerNavigation) { Set-ItemProperty $key NavPaneExpandToCurrentFolder 1 } } try { $Boxstarter.RebootOk = $true Install-WindowsUpdate -AcceptEula Disable-UAC Disable-InternetExplorerESC Update-ExecutionPolicy Unrestricted Set-ExplorerOptions -showHidenFilesFoldersDrives -showFileExtensions Set-MoreExplorerOptions -lockTheTaskBar -showAllFoldersInExplorerNavigation -automaticallyExpandToCurrentFolderInExplorerNavigation Enable-RemoteDesktop Disable-ShutdownEventTracker Disable-CrtlAltDeleteAtLogon Enable-PerformanceForPrograms Disable-ServerManagerAtLogon Enable-DesktopExperience Enable-AudioService Reboot-IfNoThemesService Enable-ThemesService Enable-PowerShellISE Enable-TelnetClient cinstm Console2 cinstm notepadplusplus cinstm sublimetext2 cinstm GoogleChrome cinstm Firefox cinstm beyondcompare cinstm fiddler cinstm windirstat cinstm sysinternals $sublimeDir = "$env:programfiles\Sublime Text 2" Install-ChocolateyPinnedTaskBarItem "$sublimeDir\sublime_text.exe" Write-ChocolateySuccess 'ServerAsWorkstation' } catch { Write-ChocolateyFailure 'ServerAsWorkstation' $($_.Exception.Message) throw }
PowerShellCorpus/GithubGist/urda_7164939_raw_ce486066e91774886c85932adc6a90e73ce87b57_Get-Checksum.ps1
urda_7164939_raw_ce486066e91774886c85932adc6a90e73ce87b57_Get-Checksum.ps1
function Get-Checksum { Param ( [string]$File=$(throw("You must specify a filename to get the checksum of.")), [ValidateSet("sha1","md5")] [string]$Algorithm="sha1" ) $ActualFile = Resolve-Path $File $fs = New-Object System.IO.FileStream("$($ActualFile.Path)", "Open") $algo = [type]"System.Security.Cryptography.$Algorithm" $crypto = $algo::Create() $hash = [BitConverter]::ToString($crypto.ComputeHash($fs)).Replace("-", "") $fs.Close() $hash }
PowerShellCorpus/GithubGist/zvolkov_5e312919ce31135e366f_raw_836275fbf5085b0d78e5acd3fa3fba8747c35228_devimage.ps1
zvolkov_5e312919ce31135e366f_raw_836275fbf5085b0d78e5acd3fa3fba8747c35228_devimage.ps1
Set-ExecutionPolicy Unrestricted Set-ExplorerOptions –showFileExtensions -EnableShowFullPathInTitleBar Set-TaskbarSmall Install-WindowsUpdate –AcceptEula cinstm VisualStudio2012Premium -InstallArguments "/Features:'WebTools SQL'" cinstm VisualStudio2013Premium -InstallArguments "/Features:'WebTools SQL'" cinst resharper cinstm Firefox cinstm googlechrome cinstm 7zip cinstm javaruntime cinstm notepadplusplus.install #cinstm MsSqlServer2012Express
PowerShellCorpus/GithubGist/angusmacdonald_8584382_raw_0e7a55aba96c3d94f7f6efa65f18f6a73e528ae8_Get-DuplicateFileNames.ps1
angusmacdonald_8584382_raw_0e7a55aba96c3d94f7f6efa65f18f6a73e528ae8_Get-DuplicateFileNames.ps1
# Created by Angus Macdonald (amacdonald AT aetherworks.com) # This takes the path of a directory to search recursively for files with the same name. # The directory must be ended with a slash. [CmdletBinding()] param ( [string] $Path ) # Use current working directory if none is specified. if (-not $Path) { $Path = (Get-Location).ProviderPath } Get-ChildItem -Path $Path -Recurse | # Get all files. where { ! $_.PSIsContainer } | # This clause removes directories. Group-Object -Property Name | # Group on name Where-Object { $_.Count -gt 1 } # Remove those without duplicates
PowerShellCorpus/GithubGist/GuruAnt_7213409_raw_4d5cb3c08f8c94e156b77cd34561be807033cb31_VMAndGuestNameMismatchFinder.ps1
GuruAnt_7213409_raw_4d5cb3c08f8c94e156b77cd34561be807033cb31_VMAndGuestNameMismatchFinder.ps1
# Get all of the VMs as an object $objVMs = Get-VM # Loop through all of the VMs ForEach ($objVM in $objVMs){ # Get the VM Guest object (which contains the DNS information) $objGuest = Get-VMGuest -VM $objVM # Set a variable to the VM object name $objVMName = $objVM.Name # Set a variable to the DNS name $objVMFQDN = $objGuest.Hostname # Sometimes the FQDN is empty or blank, so we screen those out with an "If not equals" If (($objVMFQDN -ne "") -and ($objVMFQDN -ne $null)){ # The host name is the first part of the FQDN, so we split it, and take the first (0) segment as our host name $objVMHostName = $objVMFQDN.split('.')[0] } Else { $objVMHostName = $null } # Check that the host name is not null, and if the hostname does not match the VM name, echo the results If (($objVMHostName -ne $null) -and ($objVMName -notlike $objVMHostName)){ # Write the results on one line, the VM object name, then the host name in square brackets. The "`" is an escape character Write-Host $objVMName `[$objVMHostName`] } }
PowerShellCorpus/GithubGist/matthewbadeau_3284562_raw_542c4d8c0e3246f5411bdf0cd33e39b51fefaa08_gistfile1.ps1
matthewbadeau_3284562_raw_542c4d8c0e3246f5411bdf0cd33e39b51fefaa08_gistfile1.ps1
function Get-HMACSHA1([string]$publicKey, [string]$privateKey){ $hmacsha = New-Object System.Security.Cryptography.HMACSHA1 [byte[]]$publicKeyBytes = [System.Text.Encoding]::ASCII.GetBytes($publicKey) [byte[]]$privateKeyBytes = [System.Text.Encoding]::ASCII.GetBytes($privateKey) $hmacsha.Key = $privateKeyBytes [byte[]]$hash = $hmacsha.ComputeHash($publicKeyBytes) $return = [System.BitConverter]::ToString($hash).Replace("-","").ToLower() return $return } function ConvertTo-Base64([string] $toEncode){ [byte[]]$toEncodeAsBytes = [System.Text.ASCIIEncoding]::ASCII.GetBytes($toEncode) [string]$returnValue = [System.Convert]::ToBase64String($toEncodeAsBytes) return $returnValue } [string]$publicKey = "PUBLIC_KEY" [string]$privateKey = "PRIVATE_KEY" [string]$mashapeURI = "https://_.p.mashape.com/api/" [string]$hash = Get-HMACSHA1 $publicKey $privateKey [string]$signature = ConvertTo-Base64($publicKey + ":" + $hash) $header = @{"X-Mashape-Authorization" = $signature} Invoke-WebRequest -Uri $mashapeURI -Headers $header -Verbose
PowerShellCorpus/GithubGist/pkirch_ab9c9ec3cd2314b47438_raw_e3a659e29f06bc01d2d86c8b2d0c353a4e44b65b_MVA02-Endpoints.ps1
pkirch_ab9c9ec3cd2314b47438_raw_e3a659e29f06bc01d2d86c8b2d0c353a4e44b65b_MVA02-Endpoints.ps1
# sample 1 Get-AzureVM | Get-AzureEndpoint # sample 2 Get-AzureVM | Get-AzureEndpoint | Select-Object -Property Vip, Name, Port, LocalPort | Format-Table -AutoSize # sample 3 Get-AzureVM | ForEach-Object { # Save the current VM for use in the nested ForEach. $vm = $_ # Get all endpoints of the current VM. $endpoints = Get-AzureEndpoint -VM $vm # Iterate all endpoints of the current VM. $output = $endpoints | ForEach-Object { # Create our own set of properties we want for output. $hashtable = @{ServiceName=$vm.ServiceName; InstanceName=$vm.InstanceName; DNSName=$vm.DNSName; Protocol=$_.Name; Vip=$_.Vip; ExternalPort=$_.Port; InternalPort=$_.LocalPort} # Create a new PowerShell object for output. New-Object PSObject -Property $hashtable } $output } | Format-Table -Property ServiceName, InstanceName, Vip, Protocol, ExternalPort, InternalPort, DNSName -AutoSize
PowerShellCorpus/GithubGist/tinchou_8709569_raw_a09fdbe01b2fc4177ed56a21d8f4132ccc835e25_AzureSDKTestPath.ps1
tinchou_8709569_raw_a09fdbe01b2fc4177ed56a21d8f4132ccc835e25_AzureSDKTestPath.ps1
try { $key = 'HKLM:\SOFTWARE\Microsoft\Microsoft SDKs\ServiceHosting' $registryProperty = Get-ChildItem $key -ErrorAction Stop | Sort CreationTime -Descending | Select -First 1 | Get-ItemProperty -ErrorAction Stop $fullVersion = ($registryProperty | Select FullVersion).FullVersion $installPath = ($registryProperty | Select InstallPath).InstallPath if ($fullVersion -lt "2.2.0000.0") { throw } $ref1 = "${installPath}ref\Microsoft.WindowsAzure.Storage.dll" $ref2 = "${installPath}ref\Microsoft.WindowsAzure.StorageClient.dll" if (-not(Test-Path $ref1) -or -not(Test-Path $ref2)) { throw } } catch { throw "Windows Azure Storage SDK wasn't found. Please check you have installed the dependencies." }
PowerShellCorpus/GithubGist/miriyagi_6779410_raw_0a836f0e024ce0baba34cc54c274c02d60e3e8c2_Archive-OldOutlookAttachments.ps1
miriyagi_6779410_raw_0a836f0e024ce0baba34cc54c274c02d60e3e8c2_Archive-OldOutlookAttachments.ps1
# Archive-OldOutlookAttachments.ps1 # Dual-licensed under CC0 1.0 (http://creativecommons.org/publicdomain/zero/1.0/) # or NYSL Version 0.9982 (http://www.kmonos.net/nysl/NYSL.TXT) $ErrorActionPreference = "Stop" [object] $outlook = New-Object -ComObject Outlook.Application [object] $folder = $outlook.Session.Accounts[1].Session.PickFolder() [object] $items = $folder.Items [object] $item = $items.Find("[ReceivedTime] < '" + [DateTime]::Now.AddMonths(-1).ToString() + "' ") if (!(Test-Path -PathType Container -LiteralPath "${env:USERPROFILE}\Outlook")) { New-Item -ItemType Directory -Path "${env:USERPROFILE}\Outlook" | Out-Null } while ($item) { if ($item.Attachments.Count -gt 0) { Write-Output "$($item.Subject) ($($item.Attachments.Count))" [int] $oldSize = $item.Size while ($item.Attachments.Count -gt 0) { $attachment = $item.Attachments.Item(1); $attachment.SaveAsFile("${env:USERPROFILE}\Outlook\" + $item.ConversationID + "_" + $attachment.FileName) $attachment.Delete() $item.Save } [int] $newSize = $item.Size Write-Output "$oldSize -> $newSize ($([int]($newSize * 100 / $oldSize))%)" } $item = $items.FindNext() }
PowerShellCorpus/GithubGist/RhysC_5328485_raw_269fe1dd14d3d77b1e5031f9f4f15a11ce371cc0_GetInstalledApps.ps1
RhysC_5328485_raw_269fe1dd14d3d77b1e5031f9f4f15a11ce371cc0_GetInstalledApps.ps1
#32 bit path - "hklm:\software\microsoft\windows\currentversion\uninstall" $regInstallPath = "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" $installed = gci $regInstallPath | foreach { gp $_.PSPath } | select DisplayVersion,InstallDate,ModifyPath,Publisher,UninstallString,Language,DisplayName | where { ($_.DisplayName -ne $null) -and ($_.DisplayName -ne "") }
PowerShellCorpus/GithubGist/toburger_4493889_raw_5faec90991a03d352896267d3991c7b71a2cf546_Get-GistFile.ps1
toburger_4493889_raw_5faec90991a03d352896267d3991c7b71a2cf546_Get-GistFile.ps1
param([Parameter(Mandatory)]$Id) $response = Invoke-WebRequest https://api.github.com/gists/$Id $gist = $response.Content | ConvertFrom-Json $gist.files | gm -MemberType NoteProperty | select -First 1 | % { $file = $gist.files."$($_.Name)" $file.content Write-Verbose "filename: $($file.filename)" Write-Verbose "language: $($file.language)" Write-Verbose "size: $($file.size)" } Write-Verbose "created: $([DateTime]$gist.created_at)" Write-Verbose "updated: $([DateTime]$gist.updated_at)" Write-Verbose "public: $($gist.public)" Write-Verbose "url: $($gist.html_url)" Write-Verbose "comments: $($gist.comments)"
PowerShellCorpus/GithubGist/mcollier_5309590_raw_252a0a68a7700beaace18381d662f0889f30caf5_AzurePublish.ps1
mcollier_5309590_raw_252a0a68a7700beaace18381d662f0889f30caf5_AzurePublish.ps1
#NOTE: This script is based on the Microsoft provided guidance example at # https://www.windowsazure.com/en-us/develop/net/common-tasks/continuous-delivery/. Param( [parameter(Mandatory=$true)] $serviceName, [parameter(Mandatory=$true)] $storageAccountName, [parameter(Mandatory=$true)] $storageAccountKey, [parameter(Mandatory=$true)] $cloudConfigLocation, [parameter(Mandatory=$true)] $packageLocation, $slot = "Staging", $deploymentLabel = $null, $timeStampFormat = "g", $alwaysDeleteExistingDeployments = 1, $enableDeploymentUpgrade = 1, [parameter(Mandatory=$true)] $selectedSubscription, $thumbprint, $subscriptionId, $location ) function SuspendDeployment() { write-progress -id 1 -activity "Suspending Deployment" -status "In progress" Write-Output "$(Get-Date –f $timeStampFormat) - Suspending Deployment: In progress" $suspend = Set-AzureDeployment -Slot $slot -ServiceName $serviceName -Status Suspended write-progress -id 1 -activity "Suspending Deployment" -status $opstat Write-Output "$(Get-Date –f $timeStampFormat) - Suspending Deployment: $opstat" } function DeleteDeployment() { SuspendDeployment write-progress -id 2 -activity "Deleting Deployment" -Status "In progress" Write-Output "$(Get-Date –f $timeStampFormat) - Deleting Deployment: In progress" $removeDeployment = Remove-AzureDeployment -Slot $slot -ServiceName $serviceName Write-Output "$(Get-Date –f $timeStampFormat) - Deleting Deployment: $opstat" sleep -Seconds 10 } function UploadPackage() { # As of the Windows Azure PowerShell cmdlets v0.6.11, there is no support for uploading files to blob storage. # The New-AzureDeployment cmdlet requires the .cspkg file to be in blob storage. To work around this current limitation, # use the Cerebrata Powershell cmdlets (http://www.cerebrata.com/products/azure-management-cmdlets/introduction) $blobFile = Get-ChildItem $packageLocation $script:packageBlob = Import-File -File $packageLocation -BlobContainerName "mydeployments" -BlobName $blobFile.Name -DisplayProgress ` -AccountName $storageAccountName -AccountKey $storageAccountKey } function Publish() { CreateService $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot if ($deployment -eq $null) { write-host "No deployment is detected. Creating a new deployment. " } #check for existing deployment and then either upgrade, delete + deploy, or cancel according to $alwaysDeleteExistingDeployments and $enableDeploymentUpgrade boolean variables if ($deployment.Name -ne $null) { switch ($alwaysDeleteExistingDeployments) { 1 { UploadPackage switch ($enableDeploymentUpgrade) { 1 { Write-Output "$(Get-Date –f $timeStampFormat) - Deployment exists in $servicename. Upgrading deployment." UpgradeDeployment } 0 #Delete then create new deployment { Write-Output "$(Get-Date –f $timeStampFormat) - Deployment exists in $servicename. Deleting deployment." DeleteDeployment CreateNewDeployment } } # switch ($enableDeploymentUpgrade) } 0 { Write-Output "$(Get-Date –f $timeStampFormat) - ERROR: Deployment exists in $servicename. Script execution cancelled." exit } } } else { UploadPackage 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" $newdeployment = New-AzureDeployment -Verbose -Slot $slot -Package $packageBlob.BlobUrl -Configuration $cloudConfigLocation -label $deploymentLabel -ServiceName $serviceName -ErrorVariable err -ErrorAction continue if ($err.count -ne 0) { Write-Error "$(Get-Date –f $timeStampFormat) - ERROR: Deployment creating new deployment in $servicename. Script execution cancelled." exit 1 } StartInstances } function CreateService() { $svc = Get-AzureService -ServiceName $servicename if ($svc -eq $null) { New-AzureService -ServiceName $servicename -Location $location } } function UpgradeDeployment() { write-progress -id 3 -activity "Upgrading Deployment" -Status "In progress" Write-Output "$(Get-Date –f $timeStampFormat) - Upgrading Deployment: In progress" Set-AzureDeployment -Upgrade -ServiceName $serviceName -Mode Auto -Label $deploymentLabel -Package $packageBlob.BlobUrl -Configuration $cloudConfigLocation -Slot $slot -Force StartInstances } function StartInstances() { # write-progress -id 4 -activity "Starting Instances" -status "In progress" # Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instances: In progress" # # $run = Set-AzureDeployment -Slot $slot -ServiceName $serviceName -Status Running $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot $oldStatusStr = @("") * $deployment.RoleInstanceList.Count while (-not(AllInstancesRunning($deployment.RoleInstanceList))) { $i = 1 foreach ($roleInstance in $deployment.RoleInstanceList) { $instanceName = $roleInstance.InstanceName $instanceStatus = $roleInstance.InstanceStatus # Did the status change? if ($oldStatusStr[$i - 1] -ne $roleInstance.InstanceStatus) { $oldStatusStr[$i - 1] = $roleInstance.InstanceStatus Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instance '$instanceName': $instanceStatus" } write-progress -id (4 + $i) -activity "Starting Instance '$instanceName'" -status "$instanceStatus" $i = $i + 1 } sleep -Seconds 1 $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot } $i = 1 foreach ($roleInstance in $deployment.RoleInstanceList) { $instanceName = $roleInstance.InstanceName $instanceStatus = $roleInstance.InstanceStatus if ($oldStatusStr[$i - 1] -ne $roleInstance.InstanceStatus) { $oldStatusStr[$i - 1] = $roleInstance.InstanceStatus Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instance '$instanceName': $instanceStatus" } write-progress -id (4 + $i) -activity "Starting Instance '$instanceName'" -status "$instanceStatus" $i = $i + 1 } $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot $opstat = $deployment.Status write-progress -id 4 -activity "Starting Instances" -status $opstat Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instances: $opstat" } function AllInstancesRunning($roleInstanceList) { foreach ($roleInstance in $roleInstanceList) { if ($roleInstance.InstanceStatus -ne "ReadyRole") { return $false } } return $true } cls Write-Output "$(Get-Date –f $timeStampFormat) - Windows Azure Cloud App deploy script started." Write-Host "Service Name = $serviceName" Write-Host "Storage Account = $storageAccountName" Write-Host "Storage Account Key = $storageAccountKey" Write-Host "Configuration File = $cloudConfigLocation" Write-Host "Package File = $packageLocation" Write-Host "Deployment Slot = $slot" Write-Host "Label = $deploymentLabel" Write-Host "Timestamp Format = $timeStampFormat" Write-Host "Delete Existing Deployment = $alwaysDeleteExistingDeployments" Write-Host "Perform Upgrade = $enableDeploymentUpgrade" Write-Host "Subscription Name = $selectedSubscription" Write-Host "Subscription Id = $subscriptionId" Write-Host "Management Certificate Thumbprint = $thumbprint" Write-Host "Deployment Region = $location" $DebugPreference = 'SilentlyContinue' $script:packageBlob = "" # Set the path to the Windows Azure management certificate. # For TFS build servers, this is often LocalMachine\My. # For local development, this can be either LocalMachine\My or CurrentUser\My (really any place you can access). $certPath = "cert:\CurrentUser\My\" + $thumbprint Write-Host "Using certificate: " $certPath $cert = Get-Item $certPath if ($cert -eq $null) { Write-Error "Unable to locate specified certificate by thumbprint." exit 1 } # Manually set the Windows Azure subscription details. $subscriptionTemp = Get-AzureSubscription | Where-Object {$_.SubscriptionName -eq $selectedSubscription} if ($subscriptionTemp -eq $null) { Set-AzureSubscription -CurrentStorageAccount $storageAccountName -SubscriptionName $selectedSubscription -Certificate $cert ` -SubscriptionId $subscriptionId } # Clear out any previous Windows Azure subscription details in the current context (just to be safe). Select-AzureSubscription -Clear # Select (by friendly name entered in the 'Set-AzureSubscription' cmdlet) the Windows Azure subscription to use. Select-AzureSubscription $selectedSubscription # Build the label for the deployment. Currently using the current time. Can be pretty much anything. if ($deploymentLabel -eq $null) { $currentDate = Get-Date $deploymentLabel = $serviceName + " - v" + $currentDate.ToUniversalTime().ToString("yyyyMMdd.HHmmss") } Write-Output "$(Get-Date –f $timeStampFormat) - Preparing deployment of $deploymentLabel for Subscription ID $subscriptionId." # Execute the steps to publish the package. Publish $deployment = Get-AzureDeployment -slot $slot -serviceName $serviceName $deploymentUrl = $deployment.Url $deploymentId = $deployment.DeploymentId Write-Output "$(Get-Date –f $timeStampFormat) - Creating New Deployment, Deployment ID: $deploymentId." Write-Output "$(Get-Date –f $timeStampFormat) - Created Cloud App with URL $deploymentUrl." Write-Output "$(Get-Date –f $timeStampFormat) - Windows Azure Cloud App deploy script finished."
PowerShellCorpus/GithubGist/nopslider_c8db16d30339faaa12ac_raw_283086fac85f74767c0d5d37a2d2845d1219184e_gistfile1.ps1
nopslider_c8db16d30339faaa12ac_raw_283086fac85f74767c0d5d37a2d2845d1219184e_gistfile1.ps1
Get-ADUser -Filter * -Properties * ` | where {($_.enabled -eq $true) -and ($_.lockedout -eq $false)} ` | where {$_.passwordlastset -lt (Get-Date).AddYears(-1)} ` | select SamAccountName, passwordlastset ` | sort passwordlastset
PowerShellCorpus/GithubGist/forsythetony_09057749fa755a3a18a2_raw_7808710c22bf264117cea80f678fa0599b0d6843_convertVideos.ps1
forsythetony_09057749fa755a3a18a2_raw_7808710c22bf264117cea80f678fa0599b0d6843_convertVideos.ps1
# Function definitions function getUserData { Do { $rootPath = Read-Host "Enter the path to the folder containing video files (NOT /userid)" # $rootPath = "C:\Users\muengrcerthospkinect\Desktop\testing" $pathTest = Test-Path $rootPath if (!$pathTest) { Write-Host "Path provided was not valid, try again." } } while ($pathTest -eq $false) Do { $userID = Read-Host "Enter the userID (Enter all to search all files)" $isValidID = checkUserIDString $userID Write-Host $isValidID.message $userID = $isvalidID.path } while ($isValidID.isValid -eq $false) $rootPathLength = $rootPath.length - 1 if($rootPath[$rootPathLength] -ne "\") { $rootPath = "$rootPath\" } $folderPath = ($rootPath + $userID); $startDate = Read-Host "Enter the start date for the date range in the format M/d/YYYY h:m AM/PM" # $startDate = "5/20/2013" $endDate = Read-Host "Enter the end date for the date range in the format M/d/YYYY h:m AM/PM" # $endDate = "5/20/2013" $startParseString = checkDateString $startDate $endParseString = checkDateString $endDate $startDate = [dateTime]::ParseExact($startDate, $startParseString, $null) $endDate = [dateTime]::ParseExact($endDate, $endParseString , $null) $userData = @{ "start" = $startDate; "end" = $endDate; "folderPath" = $folderPath; } return $userData } function checkUserIDString($string) { $length = $string.length if ($string -eq "all" -or $string -eq "All") { $package = @{ "isValid" = $true; "path" = ""; "message" = "User has chosen to search all user IDs"; } return $package } if ($length -ne 3) { $package = @{ "isValid" = $false; "path" = $null; "message" = "The user ID entered is not of the right length. Please try again."; } return $package } if (!($string -match "^[0-9]*$")) { $package = @{ "isValid" = $false; "path" = $null; "message" = "The user ID entered is not a numeric value. Please try again."; } return $package } $package = @{ "isValid" = $true; "path" = $string; "message" = "The userID entered was in the correct format."; } return $package } function checkDateString($string) { $tokens = $string.Split(" ") $count = $tokens.length if ($count -eq 1) { $parseString = "M/d/yyyy" } elseif ($count -eq 2) { $parseString = "M/d/yyyy H:m" } elseif ($count -eq 3) { $parseString = "M/d/yyyy h:m tt" } return $parseString } function updateFilesInRange($range) { $pathToFiles = $range.folderPath # Selection all items within the $pathToFiles directory that meet the following conditions... # 1. It is not a directory # 2. It was created after the start of the date range # 3. It was created before the end of the date range <## Get-ChildItem -Path $pathToFiles | Where {$_.PSIsContainer -eq $true -and $_.Name -eq "KinectData"} | ForEach { Get-ChildItem -Path $_ -Recurse | Where-Object {$_.Name -like "*.avi" -and !$_.PSIsDirectory} | Foreach-Object{ $videoCreationDate = extractDate $_.Name if($videoCreationDate -ne $null -and $videoCreationDate -ge $range.start -and $videoCreationDate -le $range.end) { # $newName = $_.Basename + ".mp4"; #C:\Users\Bigben\Desktop\ffmpeg-20140519-git-76191c0-win64-static\bin\ffmpeg.exe "$_" -f mp4 -r 25 -s 320*240 -b 768 -ar 44000 -ab 112 $newName; # Here you would use the file path along with ffmpeg to do the conversion $newVideo = [io.path]::ChangeExtension($_.FullName, '.mp4') # Declare the command line arguments for ffmpeg.exe $ArgumentList = '-i "{0}" -an -b:v 64k -bufsize 64k -vcodec libx264 -pix_fmt yuv420p "{1}"' -f $_.FullName, $newVideo; # Display message show user the arguments list of the conversion $convertMessage = ("Converting video with argument list " + $ArgumentList) Write-Host $convertMessage # Start-Process -FilePath C:\Users\muengrcerthospkinect\Desktop\Kinect\ffmpeg.exe -ArgumentList $ArgumentList -Wait -NoNewWindow; } }} ##> Get-ChildItem -Path $pathToFiles | Where {$_.PSIsContainer -eq $true -and $_.Name -eq "KinectData"} | Foreach { Get-ChildItem -Path $_.FullName | Where-Object {$_.Name -like "*.avi" -and !$_.PSIsDirectory} | ForEach-Object { $videoCreationDate = extractDate $_.Name if($videoCreationDate -ne $null -and $videoCreationDate -ge $range.start -and $videoCreationDate -le $range.end) { # $newName = $_.Basename + ".mp4"; #C:\Users\Bigben\Desktop\ffmpeg-20140519-git-76191c0-win64-static\bin\ffmpeg.exe "$_" -f mp4 -r 25 -s 320*240 -b 768 -ar 44000 -ab 112 $newName; # Here you would use the file path along with ffmpeg to do the conversion $newVideo = [io.path]::ChangeExtension($_.FullName, '.mp4') # Declare the command line arguments for ffmpeg.exe $ArgumentList = '-i "{0}" -an -b:v 64k -bufsize 64k -vcodec libx264 -pix_fmt yuv420p "{1}"' -f $_.FullName, $newVideo; # Display message show user the arguments list of the conversion $convertMessage = ("Converting video with argument list " + $ArgumentList) Write-Host $convertMessage # Start-Process -FilePath C:\Users\muengrcerthospkinect\Desktop\Kinect\ffmpeg.exe -ArgumentList $ArgumentList -Wait -NoNewWindow; } } } } function extractDate($path) { $pathTokens = $path -split "-" $dateTokens = $pathTokens[1] -split "_" $timeTokens = $pathTokens[2] -split "_" $timeString = ($dateTokens[0] + "/" + $dateTokens[1] + "/" + $dateTokens[2] + " " + $timeTokens[0] + ":" + $timeTokens[1] + ":" + $timeTokens[2]) $dateObject = [dateTime]::ParseExact($timeString, "MM/dd/yyyy HH:mm:ss" , $null) Write-Host $timeString return $dateObject } # Main program $userData = getUserData Write-Host ("Start Date: " + $userData.start) Write-Host ("End Date: " + $userData.end) Write-Host ("Folder path: " + $userData.folderPath) updateFilesInRange $userData
PowerShellCorpus/GithubGist/thinktainer_6762746_raw_9ccfba495f0de5666acc5300d64c41713ed65e9c_publish_azure.ps1
thinktainer_6762746_raw_9ccfba495f0de5666acc5300d64c41713ed65e9c_publish_azure.ps1
Param( $serviceName = "", $storageAccountName = "", $packageLocation = "", $cloudConfigLocation = "", $environment = "Staging", $deploymentLabel = "ContinuousDeploy to $servicename", $timeStampFormat = "g", $alwaysDeleteExistingDeployments = 1, $enableDeploymentUpgrade = 1, $selectedsubscription = "default", $subscriptionDataFile = "", $containerName = "ps1deploys" ) function Publish() { $deployment = Get-AzureDeployment -ServiceName $serviceName -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. " } #check for existing deployment and then either upgrade, delete + deploy, or cancel according to $alwaysDeleteExistingDeployments and $enableDeploymentUpgrade boolean variables if ($deployment.Name -ne $null) { switch ($alwaysDeleteExistingDeployments) { 1 { switch ($enableDeploymentUpgrade) { 1 #Update deployment inplace (usually faster, cheaper, won't destroy VIP) { Write-Output "$(Get-Date -f $timeStampFormat) - Deployment exists in $servicename. Upgrading deployment." UpgradeDeployment } 0 #Delete then create new deployment { Write-Output "$(Get-Date -f $timeStampFormat) - Deployment exists in $servicename. Deleting deployment." DeleteDeployment CreateNewDeployment } } # switch ($enableDeploymentUpgrade) } 0 { Write-Output "$(Get-Date -f $timeStampFormat) - ERROR: Deployment exists in $servicename. Script execution cancelled." exit } } #switch ($alwaysDeleteExistingDeployments) } else { CreateNewDeployment } } function UploadToStorageContainer() { $containerState = Get-AzureStorageContainer -Name $containerName -ea 0 if ($containerState -eq $null) { New-AzureStorageContainer -Name $containerName | out-null } Set-AzureStorageBlobContent -File $packageLocation -Container $containerName -Blob $blob -Force| Out-Null $script:packageLocation = (Get-AzureStorageBlob -blob $blobName -Container $containerName).ICloudBlob.uri.AbsoluteUri } function CreateNewDeployment() { UploadToStorageContainer 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 $packageLocation -Configuration $cloudConfigLocation -label $deploymentLabel -ServiceName $serviceName $completeDeployment = Get-AzureDeployment -ServiceName $serviceName -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" StartInstances } function UpgradeDeployment() { UploadToStorageContainer 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 $packageLocation -Configuration $cloudConfigLocation -label $deploymentLabel -ServiceName $serviceName -Force $completeDeployment = Get-AzureDeployment -ServiceName $serviceName -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" } function DeleteDeployment() { write-progress -id 2 -activity "Deleting Deployment" -Status "In progress" Write-Output "$(Get-Date -f $timeStampFormat) - Deleting Deployment: In progress" #WARNING - always deletes with force $removeDeployment = Remove-AzureDeployment -Slot $slot -ServiceName $serviceName -Force write-progress -id 2 -activity "Deleting Deployment: Complete" -completed -Status $removeDeployment Write-Output "$(Get-Date -f $timeStampFormat) - Deleting Deployment: Complete" } function StartInstances() { write-progress -id 4 -activity "Starting Instances" -status "In progress" Write-Output "$(Get-Date -f $timeStampFormat) - Starting Instances: In progress" $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot $runstatus = $deployment.Status if ($runstatus -ne 'Running') { $run = Set-AzureDeployment -Slot $slot -ServiceName $serviceName -Status Running } $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot $oldStatusStr = @("") * $deployment.RoleInstanceList.Count while (-not(AllInstancesRunning($deployment.RoleInstanceList))) { $i = 1 foreach ($roleInstance in $deployment.RoleInstanceList) { $instanceName = $roleInstance.InstanceName $instanceStatus = $roleInstance.InstanceStatus if ($oldStatusStr[$i - 1] -ne $roleInstance.InstanceStatus) { $oldStatusStr[$i - 1] = $roleInstance.InstanceStatus Write-Output "$(Get-Date -f $timeStampFormat) - Starting Instance '$instanceName': $instanceStatus" } write-progress -id (4 + $i) -activity "Starting Instance '$instanceName'" -status "$instanceStatus" $i = $i + 1 } sleep -Seconds 1 $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot } $i = 1 foreach ($roleInstance in $deployment.RoleInstanceList) { $instanceName = $roleInstance.InstanceName $instanceStatus = $roleInstance.InstanceStatus if ($oldStatusStr[$i - 1] -ne $roleInstance.InstanceStatus) { $oldStatusStr[$i - 1] = $roleInstance.InstanceStatus Write-Output "$(Get-Date -f $timeStampFormat) - Starting Instance '$instanceName': $instanceStatus" } $i = $i + 1 } $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot $opstat = $deployment.Status write-progress -id 4 -activity "Starting Instances" -completed -status $opstat Write-Output "$(Get-Date -f $timeStampFormat) - Starting Instances: $opstat" } function AllInstancesRunning($roleInstanceList) { foreach ($roleInstance in $roleInstanceList) { if ($roleInstance.InstanceStatus -ne "ReadyRole") { return $false } } return $true } #configure powershell with Azure 1.7 modules Import-Module Azure #configure powershell with publishsettings for your subscription $pubsettings = $subscriptionDataFile Import-AzurePublishSettingsFile $pubsettings Set-AzureSubscription -CurrentStorageAccount $storageAccountName -SubscriptionName $selectedsubscription #set remaining environment variables for Azure cmdlets $subscription = Get-AzureSubscription $selectedsubscription $subscriptionname = $subscription.subscriptionname $subscriptionid = $subscription.subscriptionid $slot = $environment #main driver - publish & write progress to activity log Write-Output "$(Get-Date -f $timeStampFormat) - Azure Cloud Service deploy script started." Write-Output "$(Get-Date -f $timeStampFormat) - Preparing deployment of $deploymentLabel for $subscriptionname with Subscription ID $subscriptionid." Publish $deployment = Get-AzureDeployment -slot $slot -serviceName $servicename $deploymentUrl = $deployment.Url Write-Output "$(Get-Date -f $timeStampFormat) - Created Cloud Service with URL $deploymentUrl." Write-Output "$(Get-Date -f $timeStampFormat) - Azure Cloud Service deploy script finished."
PowerShellCorpus/GithubGist/ser1zw_2160887_raw_2dcb0cb6f2528cc2afa5181a5eb4c683cef21e0b_dragdrop.ps1
ser1zw_2160887_raw_2dcb0cb6f2528cc2afa5181a5eb4c683cef21e0b_dragdrop.ps1
# PowerShell Drag & Drop sample # Usage: # powershell -sta -file dragdrop.ps1 # (-sta flag is required) # Function DragDropSample() { [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $form = New-Object Windows.Forms.Form $form.text = "Drag&Drop sample" $listBox = New-Object Windows.Forms.ListBox $listBox.Dock = [System.Windows.Forms.DockStyle]::Fill $handler = { if ($_.Data.GetDataPresent([Windows.Forms.DataFormats]::FileDrop)) { foreach ($filename in $_.Data.GetData([Windows.Forms.DataFormats]::FileDrop)) { $listBox.Items.Add($filename) } } } $form.AllowDrop = $true $form.Add_DragEnter($handler) $form.Controls.Add($listBox) $form.ShowDialog() } DragDropSample | Out-Null
PowerShellCorpus/GithubGist/guitarrapc_8426022_raw_66af7720ea4db570fc382ad33f8be824bfda2270_ToastNotification-Sample.ps1
guitarrapc_8426022_raw_66af7720ea4db570fc382ad33f8be824bfda2270_ToastNotification-Sample.ps1
# Code conversion from C# to PowerShell # http://msdn.microsoft.com/en-us/library/windows/apps/hh802768.aspx # nuget Windows 7 API Code Pack -Shell # http://nugetmusthaves.com/Package/Windows7APICodePack-Shell # Install-Package Windows7APICodePack-Shell Add-Type -Path .\Microsoft.WindowsAPICodePack.dll Add-Type -Path .\Microsoft.WindowsAPICodePack.Shell.dll # create toast template TO xml [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null [xml]$toastXml = ([Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastImageAndText04)).GetXml() <# # これでもいいが template type の違いに注意 [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null $toastTemplate = [Windows.UI.Notifications.ToastTemplateType]::ToastImageAndText01 [xml]$toastXml = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent($toastTemplate).GetXml() #> # message to show on toast $stringElements = $toastXml.GetElementsByTagName("text") for ($i = 0; $i -lt $stringElements.Count; $i++) { $stringElements[$i].AppendChild($toastXml.CreateTextNode("Line " + $i)) > $null } <# # こっちもあり $stringElements = $toastXml.GetElementsByTagName("text") | select -First 1 $stringElements.AppendChild($toastXml.CreateTextNode("Test Toast Notification")) > $null #> # no image $imageElements = $toastXml.GetElementsByTagName("image") $imageElements[0].src = "file:///" + "" # convert from System.Xml.XmlDocument to Windows.Data.Xml.Dom.XmlDocument $windowsXml = New-Object Windows.Data.Xml.Dom.XmlDocument $windowsXml.LoadXml($toastXml.OuterXml) $APP_ID = "hoge" $shortcutPath = [Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData) + "\Microsoft\Windows\Start Menu\Programs\hoge.lnk"; # send toast notification $toast = New-Object Windows.UI.Notifications.ToastNotification ($windowsXml) [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($APP_ID).Show($toast)
PowerShellCorpus/GithubGist/aanari_2635030_raw_a1e16893dc95b72508b1bf527aa7d8e7094ee9b4_changelog.ps1
aanari_2635030_raw_a1e16893dc95b72508b1bf527aa7d8e7094ee9b4_changelog.ps1
$commitlog = '<!doctype html><html><body>' foreach($line in git log --no-merges --pretty=%H%n%B){ if ($line -match '\w{40}') { $commit = git show $line -- Properties/AssemblyInfo.cs [string] $vers = $commit -match '\+\[assembly: AssemblyVersion\("(\d\.\d\.\d\.\d)"\)\]' if ($vers) { $vnum = $vers.Split('\"')[1] if ($vnum) { $line = '<hr><span class="version">Version ' + $vnum + ':</span>' } else { $line = '' } } else { $line = '' } } if ($line) { $commitlog += ($line + '<br/>') } } $commitlog += '<style>body{font-family:sans-serif;font-size:0.9em;color:#333;line-height:1.3;}hr{margin:0.75em 0;color:#FCFCFC;background-color:#FCFCFC;}.version{font-weight:bold;font-size:1.1em;color:#777;}</style>' $commitlog += '</body></html>' $commitlog | Out-File -Encoding UTF8 Changelog.html echo "Changelog generated successfully"
PowerShellCorpus/GithubGist/RMcD_24fac061e33422f26a3d_raw_567cb5f9d530e46e4aa06749209dc8909eb73da4_gistfile1.ps1
RMcD_24fac061e33422f26a3d_raw_567cb5f9d530e46e4aa06749209dc8909eb73da4_gistfile1.ps1
$cloudService="corp-ods-db" $ilb="corp-ods-lb" $subnet="AlwaysOn-Static" $IP="10.10.4.7" Add-AzureInternalLoadBalancer -ServiceName $cloudService -InternalLoadBalancerName $ilb –SubnetName $subnet –StaticVNetIPAddress $IP $vmNames=@("corp-ods-db1","corp-ods-db2") $endPointName="SQLServer" $prot="tcp" $localPort=1433 $publicPort=1433 $probePort=59999 $probeProt="TCP" foreach ($vmName in $vmNames) { Get-AzureVM –ServiceName $cloudService –Name $vmName | Add-AzureEndpoint -Name $endPointName -LBSetName "$endPointName-LB" -Protocol $prot -LocalPort $localPort -PublicPort $publicPort –ProbePort $probePort -ProbeProtocol $probeProt -DirectServerReturn $true -InternalLoadBalancerName $ilb | Update-AzureVM }
PowerShellCorpus/GithubGist/pfmoore_21d3450bb413a8713053_raw_642b7d8287661f77fefe153f06b811b905af2ba1_vex.ps1
pfmoore_21d3450bb413a8713053_raw_642b7d8287661f77fefe153f06b811b905af2ba1_vex.ps1
[CmdletBinding(DefaultParameterSetName="ByName")] Param ( [Parameter(Position=0, Mandatory=$true, ParameterSetName="ByName")] [String] $VE, [Parameter(Position=1)] [ScriptBlock]$sb, [Parameter(Mandatory=$true, ParameterSetName="ByPath")] [String] $Path, [Switch]$Make, [Switch]$Remove, [Switch]$Temp, [String]$CWD ) # -Path pathname ($ve is $venvroot/$ve) # -Make creates first # -Remove removes after # -Temp creates and removes # -Cwd changes directory # # Not implemented yet # --venv use python -m venv instead of virtualenv # --python python executable # --config config file # # If $sb is empty, open a nested prompt $venvroot = (Resolve-Path "~/.virtualenvs").Path # A temporary VE is made at start and removed at end if ($Temp) { $Make = $true $Remove = $true } # A named VE is stored in $venvroot if ($PsCmdlet.ParameterSetName -eq "ByName") { $Path = (Join-Path $venvroot $VE) } if ($Make) { # Make sure the virtualenv does not already exist if (Test-Path -PathType Container $Path) { throw "Directory $Path already exists" } # If $venvroot doesn't exist, create it if (($PsCmdlet.ParameterSetName -eq "ByName") -and ! (Test-Path -PathType Container $venvroot)) { $null = New-Item -Type Directory $venvroot } # Make the virtualenv virtualenv $Path } # Check the virtualenv exists if (! (Test-Path -PathType Container $Path)) { throw "Virtualenv $Path does not exist" } # Work out the full pathname, the Scripts directory and the location of Python $Path = (Resolve-Path $Path).Path $scripts = (Join-Path $Path Scripts) $python = (Join-Path $scripts python.exe) if (! (Test-Path -PathType Leaf $python)) { throw "Virtualenv $Path does not exist" } $oldpath = $env:PATH $oldvenv = $env:VIRTUAL_ENV if ($cwd) { pushd $cwd } try { $env:PATH = $scripts + ';' + $env:PATH $env:VIRTUAL_ENV = $Path if ($sb) { & $sb } else { $host.EnterNestedPrompt() } } finally { if ($cwd) { popd } $env:PATH = $oldpath $env:VIRTUAL_ENV = $oldenv } # Remove the virtualenv if requested if ($Remove) { Remove-Item -Recurse $Path }
PowerShellCorpus/GithubGist/r-tanner-f_5367976_raw_682629cc19941a270a5c89d432b202b78034b402_check_iexplorer_memory.ps1
r-tanner-f_5367976_raw_682629cc19941a270a5c89d432b202b78034b402_check_iexplorer_memory.ps1
$IESessions = Get-WmiObject Win32_PerfRawData_PerfProc_Process | Where {$_.Name -like "iexplore*"} ForEach ($ie in $IEsessions) {$pws += $ie.WorkingSetPrivate} $pws = $pws/1024/1024/1024 $pws = [System.Math]::Round($pws,2) $output = "$pws GB Working Set|'PrivateWorkingSet(GB)'=$pws`G;4;5;0;8;" Write-Host $output
PowerShellCorpus/GithubGist/jrampon_fb985c8ebf978c940230_raw_5fbc76e419ca954349e8f5e39a0f81d68e6d67c2_boxstarter-bootstrap.ps1
jrampon_fb985c8ebf978c940230_raw_5fbc76e419ca954349e8f5e39a0f81d68e6d67c2_boxstarter-bootstrap.ps1
# From a command prompt: # START http://boxstarter.org/package/nr/url?<raw-url> # Boxstarter options $Boxstarter.RebootOk=$true # Allow reboots? $Boxstarter.NoPassword=$false # Is this a machine with no login password? $Boxstarter.AutoLogin=$true # Save my password securely and auto-login after a reboot # Basic setup Update-ExecutionPolicy Unrestricted Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -DisableShowProtectedOSFiles -EnableShowFileExtensions -EnableShowFullPathInTitleBar Enable-MicrosoftUpdate Enable-RemoteDesktop Disable-InternetExplorerESC Disable-UAC if (Test-PendingReboot) { Invoke-Reboot } # Update Windows and reboot if necessary Install-WindowsUpdate -AcceptEula if (Test-PendingReboot) { Invoke-Reboot }
PowerShellCorpus/GithubGist/jeffpatton1971_8440245_raw_b433ad297d450cd43cb21576aa952a56b86e778e_New-RulesFromNetstat.ps1
jeffpatton1971_8440245_raw_b433ad297d450cd43cb21576aa952a56b86e778e_New-RulesFromNetstat.ps1
<# Create FW rules for TCP and UDP Listening Ports netstat -an -p tcp |Select-String "Listening" netstat -an -p udp |Select-String "Listening" for each entry in netstat create firewall rule name = -p tcp|udp port port # description = automatic allow rule generated by powershell on get-date Perhaps as part of this also create a dsc configuration document #> $netstat = netstat -a -n -o -p TCP $netstat += netstat -a -n -o -p UDP [regex]$regexTCP = '(?<Protocol>\S+)\s+((?<LAddress>(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?))|(?<LAddress>\[?[0-9a-fA-f]{0,4}(\:([0-9a-fA-f]{0,4})){1,7}\%?\d?\]))\:(?<Lport>\d+)\s+((?<Raddress>(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?))|(?<RAddress>\[?[0-9a-fA-f]{0,4}(\:([0-9a-fA-f]{0,4})){1,7}\%?\d?\]))\:(?<RPort>\d+)\s+(?<State>\w+)\s+(?<PID>\d+$)' [regex]$regexUDP = '(?<Protocol>\S+)\s+((?<LAddress>(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?))|(?<LAddress>\[?[0-9a-fA-f]{0,4}(\:([0-9a-fA-f]{0,4})){1,7}\%?\d?\]))\:(?<Lport>\d+)\s+(?<RAddress>\*)\:(?<RPort>\*)\s+(?<PID>\d+)' $Listening = @() foreach ($Line in $Netstat) { switch -regex ($Line.Trim()) { $RegexTCP { $MyProtocol = $Matches.Protocol $MyLocalAddress = $Matches.LAddress $MyLocalPort = $Matches.LPort $MyRemoteAddress = $Matches.Raddress $MyRemotePort = $Matches.RPort $MyState = $Matches.State $MyPID = $Matches.PID $MyProcessName = (Get-Process -Id $Matches.PID -ErrorAction SilentlyContinue).ProcessName $MyProcessPath = (Get-Process -Id $Matches.PID -ErrorAction SilentlyContinue).Path $MyUser = (Get-WmiObject -Class Win32_Process -Filter ("ProcessId = "+$Matches.PID)).GetOwner().User } $RegexUDP { $MyProtocol = $Matches.Protocol $MyLocalAddress = $Matches.LAddress $MyLocalPort = $Matches.LPort $MyRemoteAddress = $Matches.Raddress $MyRemotePort = $Matches.RPort $MyState = $Matches.State $MyPID = $Matches.PID $MyProcessName = (Get-Process -Id $Matches.PID -ErrorAction SilentlyContinue).ProcessName $MyProcessPath = (Get-Process -Id $Matches.PID -ErrorAction SilentlyContinue).Path $MyUser = (Get-WmiObject -Class Win32_Process -Filter ("ProcessId = "+$Matches.PID)).GetOwner().User } } $LineItem = New-Object -TypeName PSobject -Property @{ Protocol = $MyProtocol LocalAddress = $MyLocalAddress LocalPort = $MyLocalPort RemoteAddress = $MyRemoteAddress RemotePort = $MyRemotePort State = $MyState PID = $MyPID ProcessName = $MyProcessName ProcessPath = $MyProcessPath User = $MyUser } if ($LineItem.LocalAddress = "0.0.0.0") { if (($LineItem.State) -and ($LineItem.State.ToUpper() -eq "LISTENING")) { if ($LineItem.User) { $User = $LineItem.User.ToLower() } else { $User = "system" } if (($User -ne "system") -and ($User -ne "updatususer") -and ($User -notlike "network*") -and ($User -notlike "local s*")) { if ($LineItem.ProcessName.ToLower() -ne "system") { $Listening += $LineItem } } } } } # # $Listening contains a list of services/applications listening on a given port + protocol # foreach ($Listener in $Listening) { $Protocol = $Listener.Protocol.ToUpper() $Port = $Listener.LocalPort New-NetFirewallRule ` -DisplayName "Allow $($Protocol) traffic over port $($Port)" ` -Name "AUTOGEN_$($Protocol)_$($Port)" ` -Action Allow ` -Description $Listener ` -Direction Inbound ` -Enabled True ` -LocalPort $Listener.LocalPort ` -Protocol $Listener.Protocol }
PowerShellCorpus/GithubGist/guitarrapc_85288a1450a15e1d7bb5_raw_3e73a2856b1d47b0f640fd06fc28fd5b096585d5_CanEvaluate.ps1
guitarrapc_85288a1450a15e1d7bb5_raw_3e73a2856b1d47b0f640fd06fc28fd5b096585d5_CanEvaluate.ps1
"{{0}}" -f $hoge.hoge
PowerShellCorpus/GithubGist/jorvik_6a3b431506619e0a2c24_raw_3085bf34c4fec8a9f9514c275f60f3031bdc5d46_PartAlign.ps1
jorvik_6a3b431506619e0a2c24_raw_3085bf34c4fec8a9f9514c275f60f3031bdc5d46_PartAlign.ps1
$partitions = Get-WmiObject -computerName "." Win32_DiskPartition $partitions | foreach { Get-WmiObject -computerName "." -query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='$($_.DeviceID)'} WHERE AssocClass = Win32_LogicalDiskToPartition" | add-member -membertype noteproperty PartitionName $_.Name -passthru | add-member -membertype noteproperty Block $_.BlockSize -passthru | add-member -membertype noteproperty StartingOffset $_.StartingOffset -passthru | add-member -membertype noteproperty StartSector $($_.StartingOffset/$_.BlockSize) -passthru | add-member -membertype noteproperty BadAlign4k $($_.StartingOffset % 4096) -passthru } | Select SystemName, Name, PartitionName, Block, StartingOffset, StartSector, BadAlign4k
PowerShellCorpus/GithubGist/sjwaight_b9723e3488d98873dd91_raw_61f799b75222dd37877a33b33caad94369678d96_create-linux-vm.ps1
sjwaight_b9723e3488d98873dd91_raw_61f799b75222dd37877a33b33caad94369678d96_create-linux-vm.ps1
# Script assumes you have setup your subscription and # have a default storage account in West US. # You should change these to values you want. $cloudService = "{cloudservice}" $hostname = "{dockermanagementhost}" $linuxUser = "{linxuser}" $linuxPass = "{linxpasswd}" $location = "West US" # use CentOS 7 image $centOSImageName = (Get-AzureVMImage | Where-Object {$_.ImageName -like "*OpenLogic-CentOS-70*"})[0].ImageName New-AzureVMConfig -Name $hostname -InstanceSize Small -ImageName $centOSImageName | Add-AzureProvisioningConfig –Linux –LinuxUser $linuxUser -Password $linuxPass | New-AzureVM -ServiceName $cloudService -Location $location
PowerShellCorpus/GithubGist/alexspence_f474ae7656c910004354_raw_60932486ee99d8d33519b5a2936cbe3431e8ff7f_RavenDefrag.ps1
alexspence_f474ae7656c910004354_raw_60932486ee99d8d33519b5a2936cbe3431e8ff7f_RavenDefrag.ps1
param( [parameter(Mandatory=$true)] [string] $databaseDirectory ) Function Format-FileSize() { Param ([int]$size) If ($size -gt 1TB) {[string]::Format("{0:0.00} TB", $size / 1TB)} ElseIf ($size -gt 1GB) {[string]::Format("{0:0.00} GB", $size / 1GB)} ElseIf ($size -gt 1MB) {[string]::Format("{0:0.00} MB", $size / 1MB)} ElseIf ($size -gt 1KB) {[string]::Format("{0:0.00} kB", $size / 1KB)} ElseIf ($size -gt 0) {[string]::Format("{0:0.00} B", $size)} Else {""} } Write-Host "Running Database recovery and defragment with database directory: $databaseDirectory" $databases = dir $databaseDirectory -Directory $totalBefore = 0 $totalAfter = 0 foreach ($database in $databases){ $currentDatabaseFullname = $database.FullName cd $currentDatabaseFullname $databaseFile = "$currentDatabaseFullname\data" $beforeLength = (Get-Item $databaseFile).Length iex "esentutl /d data" $afterLength = (Get-Item $databaseFile).Length $totalBefore += $beforeLength $totalAfter += $afterLength Write-Host "Processed $currentDatabaseFullname. Size Before: $(Format-FileSize($beforeLength)) Size After: $(Format-FileSize($afterLength))" } Write-Host "Done Processing. Size Before: $(Format-FileSize($totalBefore)) Size After: $(Format-FileSize($totalAfter))" cd $PSScriptRoot
PowerShellCorpus/GithubGist/bigoals365_7f6831e5361e507ea007_raw_efaa9818a3f73340ddc0ae1e72866581b311aa03_find_suspect_kbs.ps1
bigoals365_7f6831e5361e507ea007_raw_efaa9818a3f73340ddc0ae1e72866581b311aa03_find_suspect_kbs.ps1
# find_suspect_kbs.ps1 # MS14-045: Description of the security update for kernel-mode drivers: August 12, 2014 # http://support.microsoft.com/kb/2982791 # # http://blogs.technet.com/b/heyscriptingguy/archive/2011/08/22/use-powershell-to-easily-find-information-about-hotfixes.aspx gwmi -cl win32_reliabilityRecords -filter "sourcename = 'Microsoft-Windows-WindowsUpdateClient'" | where { $_.message -match 'KB2982791' -OR $_.message -Match 'KB2970228' -OR $_.message -Match 'KB2975719' -OR $_.message -Match 'KB2975331'} | FT @{LABEL = "date";EXPRESSION = {$_.ConvertToDateTime($_.timegenerated)}}, message -autosize –wrap
PowerShellCorpus/GithubGist/roberto-reale_86814193428f11601470_raw_60038f5305f924ce0dd0e9b4f453e558f08ae303_rename_files_iso8601.ps1
roberto-reale_86814193428f11601470_raw_60038f5305f924ce0dd0e9b4f453e558f08ae303_rename_files_iso8601.ps1
# # rename a bunch of files as follows # # DDMONYYYY_NAME.EXT ==> YYYY-MM-DD_NAME.EXT # # i.e. it changes the date to ISO 8601 form # # for each file in the local path Get-ChildItem -name |% { # old filename is in the form DDMONYYYY_NAME.EXT (e.g. 26APR1982_foobar.txt) $old_filename = $_; # extract the date part (e.g., 26APR1982) $old_date_string = $($old_filename.Substring(0, 9)); # extract the suffix part (e.g.. foobar.txt); $filename_suffix = $_.Substring(10); # convert the date part to a date object $date = [datetime]::Parse($old_date_string); # represent the date object as a ISO 8601 date (e.g., 1982-04-26) $new_date_string = $date.ToString("yyyy-MM-dd"); # build up the new filename (e.g. 1982-04-26_foobar.txt) $new_filename = [string]::join("_", ($new_date_string, $filename_suffix)); # rename the file move $old_filename $new_filename; }
PowerShellCorpus/GithubGist/victorvogelpoel_6683232_raw_666c9c83dd59b0473a773b1946475a919dee4adb_Test-PortalDeployment.ps1
victorvogelpoel_6683232_raw_666c9c83dd59b0473a773b1946475a919dee4adb_Test-PortalDeployment.ps1
# Test-PortalDeployment.ps1 # Written for SharePoint 2007, but with a few adaptations it'll work for later versions as well... # This is a example of testing SharePoint portal artefact deployment and configuration using PSaint testing framework # Victor Vogelpoel / Macaw ([email protected]) # September 2013 # See blogpost at http://blog.victorvogelpoel.nl # # Note: SharePoint 2007 requires PowerShell v2 (not v3), # so start PowerShell session with "PowerShell -version 2" # # 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. Set-PSDebug -Strict Set-StrictMode -Version Latest # Allways stop at an error $global:ErrorActionPreference = "Stop" # Load SharePoint assemblies [reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null $PSScriptRoot = $MyInvocation.MyCommand.Path | Split-Path # Directory /Test/ function Initialize-TestFramework { [CmdletBinding(SupportsShouldProcess=$false)] param ( [Parameter(HelpMessage="If the test framework was loaded before, the force switch will unload the framework before loading it again")] [switch]$Force ) $modulesDirectory = Join-Path $PSScriptRoot "Modules" # Directory "/Test/Modules/ $rootDirectory = $script:modulesDirectory | Split-Path # Directory $moduleNames = "Reflection", "PSaint" $loadedModules = @(Get-Module $moduleNames | select -ExpandProperty name) if (($loadedModules.Length -eq 0) -or $Force) { if ($loadedModules.Length -gt 0) { Write-Host "Unloading modules $($loadedModules -join ', ')." Remove-Module $loadedModules -ErrorAction SilentlyContinue -Force } # Load Module Reflection and PSaint, TypeExtensions and FormatExtensions Write-Host "Loading module: Reflection ..." Import-Module "$modulesDirectory\Reflection\Reflection.psd1" -Force -Global # if (!(Test-Path variable:global:ReflectionTypeExtensionLoaded)) # { # Set-Variable -Name "ReflectionTypeExtensionLoaded" -Scope global -Value $true -Force # Update-TypeData "$modulesDirectory\Reflection\extensionMethods.ps1xml" # } Write-Host "Loading module: PSaint ..." Import-Module "$modulesDirectory\PSaint\PSaint.psd1" -Force -Global } <# .SYNOPSIS Initialize the PSaint test framework for use: load the PSaint module .DESCRIPTION Initialize the Testing framework by loading PSaint and Reflection modules and Type-/Format extensions. .PARAMETER Force If the test framework was loaded before, the force switch will unload the framework before loading it again. Note that the type/format extensions cannot be reloaded. .LINK about_MacawPowerShell about_MacawPowerShell_Tests #> } ##--------------------------------------------------------------------------------------------------------------------------------------------------- function Get-SPSolution { [CmdletBinding(SupportsShouldProcess=$false)] param ( [Parameter(Mandatory=$false, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Name of the solution")] [Alias("SolutionName")] [string[]]$Name = "*" # name can contain wildcards ) process { foreach ($aName in $Name) { Write-Output ([Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions | where { $_.Name -like $aName}) } } <# .SYNOPSIS Get all solutions from the SharePoint solution store or the solution specified by name .DESCRIPTION .PARAMETER $Name One or more names of the wsp to get the SPSolution; name may be a wildcard! if not specified, all SPSolutions are returned; .NOTES Author : Victor Vogelpoel .LINK .EXAMPLE [ps] Get-SPSolution | select name,deployed Name Deployed ---- -------- lapointe.sharepoint.stsadm.commands.wsp True radeditormoss.wsp True .EXAMPLE [ps] Get-SPSolution -name "radeditormoss.wsp" | select name Name ---- radeditormoss.wsp .EXAMPLE [ps] Get-SPSolution -name "rad*.wsp" | select name Name ---- radeditormoss.wsp .EXAMPLE [ps] Get-SPSolution -name "rad*.wsp", "lapointe*.wsp" | select name Name ---- radeditormoss.wsp lapointe.sharepoint.stsadm.commands.wsp #> } #--------------------------------------------------------------------------------------------------------------------------------------------------- function Add-SPSolution { [CmdletBinding(SupportsShouldProcess=$false)] param ( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Path to the WSP file")] [Alias("Filename")] [string[]]$Path ) process { foreach ($wspfile in $Path) { if ($PSCmdLet.ShouldProcess("$wspfile", "Add-SPSolution `"$wspfile`"")) { Write-Host "Adding SP solution `"$wspfile`"..." trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} } Write-Output ([Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions.Add($wspfile)) } } } } function Wait-SPSolutionJob { [CmdletBinding(SupportsShouldProcess=$true, DefaultParameterSetName="SolutionName")] param ( [Parameter(Mandatory=$true, Position=0, ParameterSetName="SolutionName", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Name of the solution")] [Alias("SolutionName")] [string]$Name, # name can contain wildcards, [Parameter(Mandatory=$true, Position=0, ParameterSetName="Solution", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Solution")] [Alias("Solution")] [Microsoft.SharePoint.Administration.SPSolution]$SPSolution ) process { if ($psCmdlet.ParameterSetName -eq "Solution") { $Name = $SPSolution | Select -ExpandProperty Name } $solutions = Get-SPSolution -name $Name if ($solutions) { foreach ($solution in $solutions) { $solutionName = $solution.Name if ($solution.JobExists) { $waitForMax = 720 # after 720*5 = 3600 seconds , the script should exit while ($waitForMax -gt 0 -and $solution.JobExists -and (($solution.JobStatus -eq [Microsoft.SharePoint.Administration.SPRunningJobStatus]::Initialized) -or ($solution.JobStatus -eq [Microsoft.SharePoint.Administration.SPRunningJobStatus]::Scheduled))) { $waitForMax-- Write-Host "Job for solution `"$solutionName`" is `"$($solution.JobStatus)`". (Waiting 5 seconds for next update...)" Start-Sleep -Seconds 5 # wait 5 second # Re-get the solution object $solution = Get-SPSolution -name $solutionName } } } } else { Write-Verbose "No solution found for name `"$name`": nothing to wait for." } } } function Install-SPSolution { [CmdletBinding(SupportsShouldProcess=$true, DefaultParameterSetName="SolutionName")] param ( [Parameter(Mandatory=$true, Position=0, ParameterSetName="SolutionName", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Name of the solution")] [Alias("SolutionName")] [string[]]$Name, # name can contain wildcards, [Parameter(Mandatory=$true, Position=0, ParameterSetName="Solution", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Solution")] [Alias("Solution")] [Microsoft.SharePoint.Administration.SPSolution[]]$SPSolution, [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Optional URL to retract the solution from")] [string]$Url = "", [Parameter(Mandatory=$false, HelpMessage="Optional to deploy the solution to all Content URLs")] [switch]$AllContentUrls, [Parameter(Mandatory=$false, HelpMessage="Optional to indicate that deployment to GAC is allowed")] [switch]$AllowGACDeployment, [Parameter(Mandatory=$false, HelpMessage="Optional to force deployment of the solution")] [switch]$Force ) begin { $dateToGuaranteeInstantAction = [datetime]::Now.AddDays(-2) $whatif = ($PSBoundParameters["Whatif"] -eq $true) } process { if ($psCmdlet.ParameterSetName -eq "Solution") { $Name = $SPSolution | Select -ExpandProperty Name } $solutions = Get-SPSolution -name $name foreach ($solution in $solutions) { if ($solution) { $solutionName = $solution.Name # Construct a commandtext $verboseCommand = "Install-SPSolution $solutionName" if (!([string]::IsNullOrEmpty($url))) { $verboseCommand = ($verboseCommand + " to url=$url" ) } elseif ($allContentUrls) { $verboseCommand = ($verboseCommand + " to all content urls" ) } $verboseCommand = ($verboseCommand + ", allowGACDeployment=$allowGACDeployment, force=$force") if ($PSCmdLet.ShouldProcess("Solution `"$($solution.Name)`" on url=$url, allcontenturls=$allContentUrls", "Install-SPSolution")) { if ($solution.ContainsWebApplicationResource) { $webApplicationsCollection = $null $verboseText = "" if ($allContentUrls) { # Get all content webapplications $webApplicationsCollection = Get-SPWebApplicationCollection $verboseText = "all content URLs" } elseif ([string]::IsNullOrEmpty($url)) { throw "ERROR: Solution contains webapplication resources; please specify -url or -AllContentUrls" } else { # Get the webapplication for the specified url $webApplicationsCollection = Get-SPWebApplicationCollection -url $url if (!$webApplicationsCollection) { throw "ERROR: Cannot find webapplication with url `"$url`"" } $verboseText = $url } Write-Host "Deploying $solutionName to $verboseText allowGACDeployment=$allowGACDeployment, force=$force..." trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} } $solution.Deploy($dateToGuaranteeInstantAction, $allowGACDeployment, $webApplicationsCollection, $force) } else { Write-Host ("Deploying $solutionName globally; allowGACDeployment=$allowGACDeployment, force=$force...") trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} } $solution.Deploy($dateToGuaranteeInstantAction, $allowGACDeployment, $force) } # Allways wait for the job to finish (or for a timeout) Wait-SPSolutionJob -name $solutionName # Now test if the deployment was successful: $testsolution = Get-SPSolution -name $solutionName if ($testsolution) { if ($testsolution.LastOperationResult -ne "DeploymentSucceeded") { throw "ERROR: solution `"$solutionName`" deployment failed; LastOperationResult is $($testsolution.LastOperationResult); Details: $($testsolution.LastOperationDetails)" } Write-Host $testsolution.LastOperationDetails } } } else { if ($whatif) { Write-Host "What if: cannot find any solutions with name `"$Name`"; deployment aborted" } else { throw "ERROR: cannot find any solutions with name `"$Name`"; deployment aborted" } } } } } ##--------------------------------------------------------------------------------------------------------------------------------------------------- # Get-SPWebApplicationCollection gets a typed generic Collection<SPWebApplication> function Get-SPWebApplicationCollection { [CmdletBinding(SupportsShouldProcess=$false)] param ( [Parameter(Mandatory=$false, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="URL of any zone in the SharePoint webapp to return the WebApplication object(s) for")] [string]$url = "" ) process { Enter try { $coll = New-GenericObject2 -typename System.Collections.ObjectModel.Collection -typeParameters ([Microsoft.SharePoint.Administration.SPWebApplication]) # Copy collection... Get-SPWebApplication -url $url | foreach { $coll.psbase.Add($_) } #explanation of oddball return syntax lies here: #http://stackoverflow.com/questions/695474 return @(,$coll) } finally { Leave } } } # http://www.leeholmes.com/blog/CreatingGenericTypesInPowerShell.aspx function New-GenericObject2 { param( [string] $typeName = $(throw "Missing: a generic type name"), [string[]] $typeParameters = $(throw "Missing: the type parameters"), [object[]] $constructorParameters ) ## Create the generic type name $genericTypeName = $typeName + '`' + $typeParameters.Count $genericType = [Type] $genericTypeName if(-not $genericType) { throw "Could not find generic type $genericTypeName" } ## Bind the type arguments to it [type[]] $typedParameters = $typeParameters $closedType = $genericType.MakeGenericType($typedParameters) if(-not $closedType) { throw "Could not make closed type $genericType" } ## Create the closed version of the generic type $instance = ,[Activator]::CreateInstance($closedType, $constructorParameters) return $instance } function Remove-SPSolution { [CmdletBinding(SupportsShouldProcess=$true, DefaultParameterSetName="SolutionName")] param ( [Parameter(Mandatory=$true, Position=0, ParameterSetName="SolutionName", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Name of the solution")] [Alias("SolutionName")] [string[]]$Name, # name can contain wildcards, [Parameter(Mandatory=$true, Position=0, ParameterSetName="Solution", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Solution")] [Alias("Solution")] [Microsoft.SharePoint.Administration.SPSolution[]]$SPSolution ) process { $whatif = ($PSBoundParameters["Whatif"] -eq $true) if ($psCmdlet.ParameterSetName -eq "Solution") { $Name = $SPSolution | Select -ExpandProperty Name } foreach ($solname in $Name) { $solutions = Get-SPSolution -name $solname if ($solutions) { foreach ($solution in $solutions) { if ($solution) { if ($PSCmdLet.ShouldProcess($solution.Name, "Remove-SPSolution")) { Write-Host "Deleting SP Solution $($solution.Name)..." trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} } $solution.Delete() } } } } else { if ($whatif) { Write-Host "What if: cannot find any solutions with name `"$Name`"'; nothing is deleted" } else { throw "ERROR: No solution(s) found in SharePoint solution store with name `"$Name`"" } } } } } function Uninstall-SPSolution { [CmdletBinding(SupportsShouldProcess=$true, DefaultParameterSetName="SolutionName")] param ( [Parameter(Mandatory=$true, Position=0, ParameterSetName="SolutionName", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Name of the solution")] [Alias("SolutionName")] [string[]]$Name, # name can contain wildcards, [Parameter(Mandatory=$true, Position=0, ParameterSetName="Solution", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Solution")] [Alias("Solution")] [Microsoft.SharePoint.Administration.SPSolution[]]$SPSolution, [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Optional URL to retract the solution from")] [string]$Url = "", [Parameter(Mandatory=$false, HelpMessage="Optional to retract the solution from all Content URLs")] [switch]$allContentUrls ) begin { $dateToGuaranteeInstantAction = [datetime]::Now.AddDays(-2) $whatif = ($PSBoundParameters["Whatif"] -eq $true) } process { if ($psCmdlet.ParameterSetName -eq "Solution") { $Name = $SPSolution | Select -ExpandProperty Name } #$solutions = [Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$wspname] $solutions = Get-SPSolution -name $Name if ($solutions) { foreach ($solution in $solutions) { if ($solution) { $solutionName = $solution.Name if ($PSCmdLet.ShouldProcess("Solution `"$($solution.Name)`" on url=$url, allcontenturls=$allContentUrls", "Retract-SPSolution")) { if ($solution.ContainsWebApplicationResource) { # retract from webapplications $webApplicationsCollection = $null $verboseText = "" if ($allContentUrls) { # Get all content webapplications $webApplicationsCollection = Get-SPWebApplicationCollection $verboseText = "all content URLs" } elseif ([string]::IsNullOrEmpty($url)) { throw "ERROR: Solution contains webapplication resources; please specify -url or -AllContentUrls" } else { # Get the webapplication for the specified url $webApplicationsCollection = Get-SPWebApplicationCollection -url $url if ($webApplicationsCollection -eq $null) { throw "ERROR: cannot find webapplication for $url; aborting retract" } $verboseText = $url } Write-Host "Retracting SP Solution `"$($solution.Name)`" from $verboseText..." # Retract from the webapplication; SharePoint adds a job that is executed by the Timer service trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} } $solution.Retract($dateToGuaranteeInstantAction, $webApplicationsCollection) } else { Write-Host "Retracting SP Solution `"$($solution.Name)`" globally..." # Retract globally; SharePoint adds a job that is executed by the Timer service trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} } $solution.Retract($dateToGuaranteeInstantAction) } # Always wait for the job to finish Wait-SPSolutionJob -name $solutionName # Now test if the retraction was successful: $testsolution = Get-SPSolution -name $solutionName if ($testsolution) { if ($testsolution.LastOperationResult -ne "RetractionSucceeded") { throw "ERROR: solution $solutionName retraction failed; LastOperationResult is $($testsolution.LastOperationResult); Details: $($testsolution.LastOperationDetails)" } Write-Host $testsolution.LastOperationDetails } } else { Write-Verbose "Retract-SPSolution: ShouldProcess yielded false: solution `"$($solution.Name)`" was not retracted." } } } } else { if ($Whatif) { Write-Host "What if: cannot find any solutions with name `"$Name`"'; nothing is retracted" } else { throw "ERROR: cannot find any solution for `"$Name`" in the solution store. Retract aborted" } } } } function Get-SPWebApplication { [CmdletBinding(SupportsShouldProcess=$false)] param ( [Parameter(Mandatory=$false, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="URL of any zone in the SharePoint webapp to return the WebApplication object(s) for")] [string]$url = "" ) process { try { Write-Output ([Microsoft.SharePoint.Administration.SPWebService]::ContentService.WebApplications | where { $url -eq "" -or ( $_.GetResponseUri([Microsoft.SharePoint.Administration.SPUrlZone]::Default) -eq $url -or $_.GetResponseUri([Microsoft.SharePoint.Administration.SPUrlZone]::Intranet) -eq $url -or $_.GetResponseUri([Microsoft.SharePoint.Administration.SPUrlZone]::Internet) -eq $url -or $_.GetResponseUri([Microsoft.SharePoint.Administration.SPUrlZone]::Extranet) -eq $url -or $_.GetResponseUri([Microsoft.SharePoint.Administration.SPUrlZone]::Custom) -eq $url) }) } catch { Write-Error "ERROR while getting SharePoint webapplication object for url `"$url`": $_" Write-Error "Please check event log for errors, which may include problems logging in into the SharePoint databases" } } } ##--------------------------------------------------------------------------------------------------------------------------------------------------- function Get-SPFeature { [CmdLetBinding(SupportsShouldProcess=$false, defaultParameterSetname="IdentityOnly")] param ( [Parameter(Position=0, Mandatory=$false, parameterSetName="IdentityOnly", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Id of the feature")] [Parameter(Position=0, Mandatory=$false, parameterSetName="Farm", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Id of the feature")] [Parameter(Position=0, Mandatory=$false, parameterSetName="Web", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Id of the feature")] [Parameter(Position=0, Mandatory=$false, parameterSetName="Site", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Id of the feature")] [Parameter(Position=0, Mandatory=$false, parameterSetName="WebApplication", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Id of the feature")] [string]$Identity = "", [Parameter(Mandatory=$false, parameterSetName="Farm", ValueFromPipelineByPropertyName=$true, HelpMessage="Specifies that if this parameter is used, only enabled farm Features are displayed.")] [switch]$Farm, [Parameter(Mandatory=$true, parameterSetName="Site", ValueFromPipelineByPropertyName=$true, HelpMessage="Specifies the SPSite to find the features for")] [Microsoft.SharePoint.SPSite]$Site, [Parameter(Mandatory=$true, parameterSetName="Web", ValueFromPipelineByPropertyName=$true, HelpMessage="Specifies the SPWeb to find the features for")] [Microsoft.SharePoint.SPWeb]$Web, [Parameter(Mandatory=$true, parameterSetName="WebApplication", ValueFromPipelineByPropertyName=$true, HelpMessage="Specifies the URL of the webapplication to get features for")] [Alias("url")] [string]$WebAppUrl, [Parameter(Mandatory=$false, parameterSetName="IdentityOnly", ValueFromPipelineByPropertyName=$true, HelpMessage="Limits the display result; if 'all' is specified, all features are displayed; if a number, the number must be greater than 0; default value is 200")] [Parameter(Mandatory=$false, parameterSetName="Farm", ValueFromPipelineByPropertyName=$true, HelpMessage="Limits the display result; if 'all' is specified, all features are displayed; if a number, the number must be greater than 0; default value is 200")] [Parameter(Mandatory=$false, parameterSetName="Web", ValueFromPipelineByPropertyName=$true, HelpMessage="Limits the display result; if 'all' is specified, all features are displayed; if a number, the number must be greater than 0; default value is 200")] [Parameter(Mandatory=$false, parameterSetName="Site", ValueFromPipelineByPropertyName=$true, HelpMessage="Limits the display result; if 'all' is specified, all features are displayed; if a number, the number must be greater than 0; default value is 200")] [Parameter(Mandatory=$false, parameterSetName="WebApplication", ValueFromPipelineByPropertyName=$true, HelpMessage="Limits the display result; if 'all' is specified, all features are displayed; if a number, the number must be greater than 0; default value is 200")] [ValidateScript({ $limitInt = 0; ($Limit -eq "All" -or ([int]::TryParse($Limit, [ref]$limitInt) -and $limitInt -gt 0 )) })] [string]$Limit = "200" ) # SPFarm.FeatureDefinitions Returns the list of all installed features in the server farm. # SPWebApplication.Features Returns a list of activated virtual server-scoped features for the SharePoint Foundation Web application. # SPWebService.Features Returns the administrative features that have been activated at the server farm scope. # SPSite.Features Returns the list of activated features for the site collection. # SPWeb.Features Returns the list of activated features for a site. # SPFeatureDefinition.ActivationDependencies Returns the list of features upon which activation of another feature depends. # QueryFeatures(Guid) Returns a list of all of the site collection-scoped and Web site-scoped features of the given GUID. begin { $allFeatures = [Microsoft.SharePoint.Administration.SPFarm]::Local.FeatureDefinitions $webapplicationFeatures = $null switch ($PSCmdlet.ParameterSetName) { "Site" { $siteFeatures = $site.Features } "web" { $webFeatures = $web.Features } "webapplication" { $webapp = Get-SPWebApplication -url $WebAppUrl if ($webapp) { $webapplicationFeatures = $webapp.Features } else { throw "Cannot find SharePoint WebApplication for URL `"$WebAppUrl`"" } } } } process { $limitInt = [int]::MaxValue if ($Limit -ne "All") { $limitInt = [int]$Limit } switch ($PSCmdlet.ParameterSetName) { "IdentityOnly" { $allFeatures | where { $Identity -eq "" -or $_.Id -eq $Identity -or $_.DisplayName -eq $Identity } | select -First $limitInt break; } "Farm" { $allFeatures | where { $_.Scope -eq "Farm" -and ($Identity -eq "" -or $_.Id -eq $Identity -or $_.DisplayName -eq $Identity) } | select -First $limitInt break; } "Site" { $siteFeatures | select -ExpandProperty Definition | where { $Identity -eq "" -or $_.Id -eq $Identity -or $_.DisplayName -eq $Identity } | select -First $limitInt break; } "Web" { $webFeatures | select -ExpandProperty Definition | where { $Identity -eq "" -or $_.Id -eq $Identity -or $_.DisplayName -eq $Identity } | select -First $limitInt break; } "WebApplication" { $webapplicationFeatures | select -ExpandProperty Definition | where { $Identity -eq "" -or $_.Id -eq $Identity -or $_.DisplayName -eq $Identity } | select -First $limitInt break; } default { throw "Cannot find parametersetName `"$($PSCmdlet.ParameterSetName)`"" } } } } ##--------------------------------------------------------------------------------------------------------------------------------------------------- # Initialize PSaint Initialize-TestFramework ##--------------------------------------------------------------------------------------------------------------------------------------------------- Test-Code "Solution `"framework_v1*.WSP`" is installed in SharePoint solution store" { arrange { $solutionName = "framework_v1*.WSP" } act { $solution = Get-SPSolution $solutionName # NOTE: mijn Get-SPSolution voor SharePoint 2007 ondersteunt wildcards! } assert { Assert-That { $solution –ne $null } -FailMessage "Solution `"$solutionName`" not found in solution store" } } # Above Test-Code call will yield a TestResult object like this: # Result Name FailMessage # ------ ---- -------- # Fail Solution framework_v*.WSP is installed in solution store Solution "framework_v*.WSP" not found in solution store ##--------------------------------------------------------------------------------------------------------------------------------------------------- Test-Code "Feature `"Error Page control adapter`" is activated (at web application scope)" { arrange { $webAppUrl = "http://portal.nl" $featureIdentity = "Feature-ErrorPageControlAdapter" $featureIsInstalled = $false $webAppScopedFeatureIsActivated = $false } act { # Get the feature from the list of all installed features in the server farm $feature = Get-SPFeature -Identity $featureIdentity $featureIsInstalled = ($feature -ne $null -and $feature.Status -eq "Online") if ($featureIsInstalled) { $webAppScopedFeatureIsActivated = ((Get-SPFeature -Identity $featureIdentity -WebAppUrl $webAppUrl) -ne $null) } } assert { Assert-That { $featureIsInstalled } -FailMessage "Feature `"$featureIdentity`" is not installed in the farm." Assert-That { $webAppScopedFeatureIsActivated } -FailMessage "Feature `"$featureIdentity`" is not activated at webapplication `"$webAppUrl`"." } } # Above Test-Code call will yield a TestResult object like this: # Result Name FailMessage # ------ ---- -------- # Fail Solution framework_v*.WSP is installed in solution store Solution "framework_v*.WSP" not found in solution store
PowerShellCorpus/GithubGist/sneal_b006e5a8cbe50f04202a_raw_9989018c0cf57a0d71de4e63417bc3c93d352900_vagrant-shell.ps1
sneal_b006e5a8cbe50f04202a_raw_9989018c0cf57a0d71de4e63417bc3c93d352900_vagrant-shell.ps1
$command = "<%= options[:command] %>" + '; exit $LASTEXITCODE' $user = '<%= options[:username] %>' $password = '<%= options[:password] %>' $task_name = "WinRM_Elevated_Shell" $out_file = "$env:SystemRoot\Temp\WinRM_Elevated_Shell.log" if (Test-Path $out_file) { del $out_file } $task_xml = @' <?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Principals> <Principal id="Author"> <UserId>{user}</UserId> <LogonType>Password</LogonType> <RunLevel>HighestAvailable</RunLevel> </Principal> </Principals> <Settings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <StartWhenAvailable>false</StartWhenAvailable> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>false</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>PT2H</ExecutionTimeLimit> <Priority>4</Priority> </Settings> <Actions Context="Author"> <Exec> <Command>cmd</Command> <Arguments>{arguments}</Arguments> </Exec> </Actions> </Task> '@ $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $encoded_command = [Convert]::ToBase64String($bytes) $arguments = "/c powershell.exe -EncodedCommand $encoded_command &gt; $out_file 2&gt;&amp;1" $task_xml = $task_xml.Replace("{arguments}", $arguments) $task_xml = $task_xml.Replace("{user}", $user) $schedule = New-Object -ComObject "Schedule.Service" $schedule.Connect() $task = $schedule.NewTask($null) $task.XmlText = $task_xml $folder = $schedule.GetFolder("\") $folder.RegisterTaskDefinition($task_name, $task, 6, $user, $password, 1, $null) | Out-Null $registered_task = $folder.GetTask("\$task_name") try { $registered_task.Run($null) | Out-Null } Catch [System.IO.FileNotFoundException] { $registered_task.Run($null) | Out-Null } $timeout = 10 $sec = 0 while ( (!($registered_task.state -eq 4)) -and ($sec -lt $timeout) ) { Start-Sleep -s 1 $sec++ } function SlurpOutput($out_file, $cur_line) { if (Test-Path $out_file) { get-content $out_file | select -skip $cur_line | ForEach { $cur_line += 1 Write-Host "$_" } } return $cur_line } $cur_line = 0 do { Start-Sleep -m 100 $cur_line = SlurpOutput $out_file $cur_line } while (!($registered_task.state -eq 3)) $exit_code = $registered_task.LastTaskResult [System.Runtime.Interopservices.Marshal]::ReleaseComObject($schedule) | Out-Null exit $exit_code
PowerShellCorpus/GithubGist/blart_7ee038e1799fe9293704_raw_92ced43527c4b7130ef857f4eb2d27419fc72975_check_sqlagent_jobs.ps1
blart_7ee038e1799fe9293704_raw_92ced43527c4b7130ef857f4eb2d27419fc72975_check_sqlagent_jobs.ps1
# SQL Agent Job Status - check_mk local plugin check. # Copyright 2014 Iomart Hosting Limited - [email protected]. # Directions for use: # # Place in the check_mk plugin directory. # Edit the check_mk ini file to allow execution of ps1 powershell files. # Edit c:\program files (x86)\check_mk\sqlservers.txt to contain the server (and instance if applicable) # Reset our output buffer size as we shouldn't do any line wrapping. $host.UI.RawUI.BufferSize=new-object System.Management.Automation.Host.Size(2048,50) # Load SMO extension [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null; # Get List of sql servers to check $sqlservers = Get-Content "C:/Program Files (x86)/check_mk/sqlservers.txt"; # Loop through each sql server from sqlservers.txt foreach($sqlserver in $sqlservers) { # Create an SMO Server object $srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver; # For each jobs on the server foreach($job in $srv.JobServer.Jobs) { $jobName = $job.Name; $jobEnabled = $job.IsEnabled; $jobLastRunOutcome = $job.LastRunOutcome; $jobLastRunDate = $job.LastRunDate $checkName = "SQL Agent Status $jobName" $checkName = $checkName.replace(" ", "_") # Skip jobs that are not enabled. if ($jobEnabled -eq "True") { # default for each job. $status = 3 $statusText = 'UNKNOWN' # Successfully completed. if($jobLastRunOutcome -eq "Failed") { $status = 2 $statusText = 'CRITICAL' } elseif ($jobLastRunOutcome -eq "Succeeded") { $status = 0 $statusText = 'OK' } Write-Host $status $checkName - "$statusText - Job last run status: $jobLastRunOutcome at $jobLastRunDate"; } } }
PowerShellCorpus/GithubGist/jesslilly_3c95849273d6220711d7_raw_0cc9833bd0a67edce08463a6cfba03369f4784e7_Microsoft.PowerShell_profile.ps1
jesslilly_3c95849273d6220711d7_raw_0cc9833bd0a67edce08463a6cfba03369f4784e7_Microsoft.PowerShell_profile.ps1
# # vi $profile # C:\Users\userid\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 # new-alias vi "C:\Program Files\Sublime Text 2\sublime_text.exe" new-alias grep select-string
PowerShellCorpus/GithubGist/GuruAnt_7216369_raw_61797328bac65e63d9df860f917d88509de51823_ManuallyCreateLinkedClonesInvSphere.ps1
GuruAnt_7216369_raw_61797328bac65e63d9df860f917d88509de51823_ManuallyCreateLinkedClonesInvSphere.ps1
# Script to deploy linked clones # List of custom attributes which you're wanting to copy from the template or parent to the newly created machine # (Machines deployed from templates no longer inherit CAs in vSphere 4.0) # These help us track provenance, and provide information to the user $arrStrAttributesToCopy = @( "AD Object Location", "Customisation", "Infrastructure Consultant", "Logon Administrator Name", "Logon Administrator Password", "Logon User Name", "Logon User Password", "Mobilisation Consultant", "Project", "Role", ) # Name of the Custom Attribute on the parent which contains the name of the customisation to use $CustomFieldName = "Customisation" Function DeployLinkedClone ($strSourceVM, $intToBeDeployed, $intStartDeployingAtNumber, $CustomFieldName){ # Bases the name of the machine on the second part of the string split by spaces. This assumes that the template follows the standard naming convention of "Tmpl [Name] x.x" $strMachinePrefix = ($strSourceVM.split(' ')[1]) $objVM = Get-VM $strSourceVM $viewVM = $objVM | Get-View $objCustomization = Get-OSCustomizationSpec ($objVM.CustomFields.Item($CustomFieldName)) # Ensure that the machines does not have a non persistent HD If ($objVM | Get-HardDisk | Where-Object {$_.Persistence -like "IndependentNonPersistent"}){ Write-Host $objTemplate has a non-persistent HD! } # If the customisation, as specified in the parent's custom attribute does not exist, then quit. If (!$objCustomization){ Write-Host Customisation ($objVM.CustomFields.Item($CustomFieldName)) not found. Exiting. Break } $i = 1 Do { # Convert the single digit integer (i.e., "1") into a double digit (i.e., "01") $strMachineNumber = ("{0:0#}" -f $intStartDeployingAtNumber) # Concatenate the machine name prefix (from the template name) with the double-digit integer, which is incrememted on each loop $strMachineBeingDeployed = $strMachinePrefix+$strMachineNumber # Check that the machine doesn't already exist If ((Get-VM -Name $strMachineBeingDeployed -ErrorAction SilentlyContinue)){ Write-Host "Machine $strMachineBeingDeployed already exists!" Break } # Let the user know what's going on Write-Host "" Write-Host "Deploying new linked-clone " -NoNewline Write-Host $strMachineBeingDeployed -ForegroundColor Blue -NoNewline Write-Host ", from template " -NoNewline Write-Host $strSourceVM -ForegroundColor Blue -NoNewline Write-Host ", using customisation " -NoNewline Write-Host $objCustomization -ForegroundColor Blue -NoNewline Write-Host ", on the same Host as the parent" -NoNewline Write-Host "" # Create the new machine using all these variables $objFolder = $viewVM.parent $specClone = New-Object Vmware.Vim.VirtualMachineCloneSpec # Get the most recent snapshot attached to the machine $specClone.Snapshot = $viewVM.Snapshot.CurrentSnapshot # Create an object to represent the location of the clone $specClone.Location = New-Object Vmware.Vim.VirtualMachineRelocateSpec # This is the move-type that specifies the new disk backing (which is the bit that makes a linked clone) $specClone.Location.DiskMoveType = "createNewChildDiskBacking" # Run the task with the specified parameters $task = $viewVM.CloneVM_Task($objFolder, $strMachineBeingDeployed, $specClone) Get-VIObjectByVIView $task | Wait-Task | Out-Null # Get the object for the machine which was just deployed $objTargetVM = Get-VM $strMachineBeingDeployed # Apply the customisation specification to the newly created clone Set-VM -VM $objTargetVM -OSCustomizationSpec $objCustomization -Confirm:$false # Start the clone Start-VM -VM $objTargetVM # Get the view (needed for writing custom attributes) $viewTarget = $objTargetVM | Get-View # Loop through each of the custom attributes which are to be copied ForEach ($arrStrAttributeToCopy in $arrStrAttributesToCopy){ # Read the attribute from the source template $objAttribute = $objVM.CustomFields.Item($arrStrAttributeToCopy) # Apply the attribute to the machine object $viewTarget.setCustomValue($arrStrAttributeToCopy,$objAttribute) } # Set the "Template" custom attribute to the parent templates $arrStrAttributeToCopy = "Template" $viewTarget.setCustomValue($arrStrAttributeToCopy,$strSourceTemplate) # Increment the number used for naming the machines $intStartDeployingAtNumber ++ # Increment the number used to count the number of machines deployed $i ++ } # Continue to loop while the number of machines deployed is less than the number required While ($i -le $intToBeDeployed) } # Get the current time (for timing how long the script took to run) $dteStart = Get-Date # Name of source VM, should be persistent, should have a snapshot and the customisation specified in the nominated custom attribute $strSourceVM = "Tmpl Capture 1.0" # Number to be deployed $intToBeDeployed = 25 # Number to start deploying from $intStartDeployingAtNumber = 1 DeployLinkedClone $strSourceVM $intToBeDeployed $intStartDeployingAtNumber $CustomFieldName # Name of source VM, should be persistent, should have a snapshot and the customisation specified in the nominated custom attribute $strSourceVM = "Tmpl Packaging 1.0" # Number to be deployed $intToBeDeployed = 25 # Number to start deploying from $intStartDeployingAtNumber = 1 DeployLinkedClone $strSourceVM $intToBeDeployed $intStartDeployingAtNumber $CustomFieldName # Name of source VM, should be persistent, should have a snapshot and the customisation specified in the nominated custom attribute $strSourceVM = "Tmpl Verification 1.0" # Number to be deployed $intToBeDeployed = 25 # Number to start deploying from $intStartDeployingAtNumber = 1 DeployLinkedClone $strSourceVM $intToBeDeployed $intStartDeployingAtNumber $CustomFieldName $dteEnd = Get-Date $dteDiff = New-TimeSpan $dteStart $dteEnd $timeTaken = [math]::round($dteDiff.totalMinutes, 2) Write-Host "" Write-Host "It took" $timeTaken "minutes for these machines to deploy" # End of script
PowerShellCorpus/GithubGist/mrdaemon_758948_raw_77e8522804f897f9d4a7dd31555309d5d45eb03d_hyperv-r2-configonly-import.ps1
mrdaemon_758948_raw_77e8522804f897f9d4a7dd31555309d5d45eb03d_hyperv-r2-configonly-import.ps1
<# .SYNOPSIS Safely Imports Hyper-V Virtual Machines that were exported as configuration only, without State Data (snapshots, VHDs, etc). .DESCRIPTION Hyper-V 2008 R2 removed the option to export a Virtual Machine without its State Data (Snapshots, Virtual Disk Images (VHDs), Suspend State), as configuration only through the GUI. The functionality is still there, only it is not exposed through the Hyper-V Manager snap-in in R2. Many scripts and resources exist to perform such an export, namely the PowerShell management Library for Hyper-V (see links). However, there are very few, if any usable tools that leverage the new ImportVirtualSystemEx() API to perform an import of such a configuration-only export. This cmdlet attempts to remedy this. It will copy the specified VM Export to a sensible location based on the current global setting for VM Data location in Hyper-V, and then assuming the VHD files are in the right place and the Virtual Networks still have the same friendly names, reattach everything together and import the virtual machine back into Hyper-V. This was written because there is no direct upgrade path between Hyper-V Server 2008 and Hyper-V Server 2008 R2. .PARAMETER ExportDirectory Specifies either a Directory or a list of directories where the Configuration Only exports can be found. Each directory must contain the 'config.xml' file in the root along with the "Virtual Machines" directory containing the actual configuration. .INPUTS You can pipe a collection of directories into Import-HVConfigOnlyVM. They will all be processed. .OUTPUTS System.Object - may be formatted as a table, contains a report of the operations in its property members. .NOTES The script must be ran locally on the Hyper-V server. It also will only work on Hyper-V R2 and Powershell 2.0. .EXAMPLE Import a config only export of a virtual machine stored at E:\Export\VMSVR03 C:\PS> Import-HVConfigOnlyVM -ExportDirectory E:\Export\VMSVR03 .EXAMPLE Import all the exports stored in E:\Export C:\PS> gci E:\Export | where { $_.PSIsContainer -eq $true } | Import-HVConfigOnlyVM .LINK https://github.com/mrdaemon/hyper-v_utils Script page and code repository on GitHub .LINK http://www.raptorized.com Author's Blog .LINK http://pshyperv.codeplex.com/ PowerShell management Library for Hyper-V (only vaguely related) #> function Import-HVConfigOnlyVM { [OutputType([System.Object])] [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact="Medium" )] Param ( [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Enter path to exported VM directory (containing config.xml)")] [ValidateScript({ (Test-Path (Join-Path $_ "config.xml") -PathType Leaf) -and (Test-Path (Join-Path $_ "Virtual Machines") -PathType Container) })] [alias("FullName", "Path")] [string[]]$ExportDirectory ) BEGIN { # Local settings and local-scope WMI class instances ##################################################### # Sane default for Errors behavior. # You shouldn't override it anyways. $ErrorActionPreference = "Stop" # Hyper-V WMI Namespace $hyperv_namespace = "root/virtualization" # VirtualSystemManagementService and # VirtualSystemManagementSettingData WMI instances $vsms = Get-WmiObject -Namespace $hyperv_namespace -Class "MsVM_virtualSystemManagementService" $hyperv_config = Get-WmiObject -NameSpace $hyperv_namespace -Class "MsVM_VirtualSystemManagementServiceSettingData" # List of currently configured Virtual Networks from the # Hyper-V server configuration, for validation purposes. [String[]]$vswitches = Get-WmiObject -NameSpace $hyperv_namespace -Class "MsVM_VirtualSwitch" | foreach( $_.ElementName.toString()) # Array to hold the result set populated with our custom report objects [System.Object[]]$statusdataset = @() } PROCESS { write-host "Importing config-only Virtual machine in", $ExportDirectory # Reporting Object, contains all the status data. # It is pushed into a global array and returned when the script # is done executing. $importstatus = New-Object System.Object # Construct new destination root from the default Hyper-V VM storage # path, the system default name of "Virtual Machines" as a subdirectory, # and the the top level directory (which should be the name of the VM). # TODO: make this a parameter. $newroot = Join-Path (Join-Path $hyperv_config.DefaultExternalDataRoot "Virtual Machines") (get-item $ExportDirectory).Name # There's no way we can continue if the data set already exists. if (Test-Path $newroot -PathType Container) { $err = "The destination path $newroot already exists!`n", "Aborting..." throw $err } # Copy the export files to their final location in $newroot, # they will be imported in-place, since we do not enable CreateCopy. # Copy-Item creates target Directories if they don't already exist. Write-Host "Copying configuration to $newroot..." if($PSCmdlet.ShouldProcess) { Copy-Item $ExportDirectory -Destination $newroot -Container -Recurse } # Fetch current import settings data from files in new data root $importconfig = $vsms.GetVirtualSystemImportSettingData("$newroot").ImportSettingData Write-Host "Processing configuration for", $importconfig.Name # Populate our status object with what we have gathered so far: $importstatus | Add-Member # Alter importation settings to reuse current and default values. # This is how to specify where the data actually lives. # http://msdn.microsoft.com/en-us/library/dd379577(v=VS.85).aspx $importconfig.CreateCopy = $false $importconfig.GenerateNewId = $false $importconfig.SourceSnapshotDataRoot = $hyperv_config.DefaultVirtualHardDiskPath $importconfig.SourceResourcePaths = $importconfig.CurrentResourcePaths $importconfig.TargetNetworkConnections = $importconfig.SourceNetworkConnections # Validate (at least roughly) import settings foreach ($path in $importconfig.SourceResourcePaths) { if(Test-Path -Path $path -PathType Leaf) { Write-Host "Found Resource $path ." } else { Write-Warning ("Warning, missing ressource: $path!`n", "You will be able to continue but you will have to reattach", "the missing volumes to the virtual machines after the import." -join " ") } } # Perform Importation of system. $result = $vsms.ImportVirtualSystemEx("$newroot", $importconfig.PSBase.GetText(1)) # Apparently, calling ImportVirtualSystemEx forks a process/thread asynchronously, # returning a CIM_ConcreteJob class instance with the job details. # This is translated in Powershell as a Job, but the translation is not flawless. if ($result.ReturnValue -eq 4096) { # Getting WMI Job object reference. $job = [WMI]$result.Job # Process our job status in a loop while it is in one of the following states: # 2 - Never Started # 3 - Starting # 4 - Running # http://msdn.microsoft.com/en-us/library/cc136808(v=VS.85).aspx#properties while ($job.JobState -eq 2 -or $job.JobState -eq 3 -or $job.JobState -eq 4) { # Display and update the lovely progress bar. Write-Progress $job.Caption -Status "Importing VM" -PercentComplete $job.PercentComplete start-sleep 1 # Update the ref, it doesn't do that by itself. $job = [WMI]$result.Job } # Complete Progress bar and move on. Write-Progress "Importing Virtual Machine" -Status "Done." -PercentComplete 100 # JobState 7 means Successfully Completed. # There are a billion other things that could be returned here, # and frankly, I don't care. Enjoy your generic error code. if($job.JobState -eq 7) { Write-Output "System in $ExportDirectory successfully imported in $newroot." } else { Write-Error "System failed to import. Error value:", $job.Errorcode, $job.ErrorDescription } } else { # Return code was not 4096, which is "Job Started". # This means no job was forked. There can be only two outcomes # to this entire ordeal. Let's Address them in the laziest way possible. $msg = "ImportVirtualSystemEx() returned prematurely with status" if($result.ReturnValue -eq 0) { Write-Warning $msg, "0 (Success)" } else { Write-Error $msg, $result.ReturnValue } } } }
PowerShellCorpus/GithubGist/alienone_a464db9660fe65c8df9c_raw_4b26a1c4c27a75775fd92ea6556a3d254aa8aa11_get_stats.ps1
alienone_a464db9660fe65c8df9c_raw_4b26a1c4c27a75775fd92ea6556a3d254aa8aa11_get_stats.ps1
Function Get-ComputerStats { param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNull()] [string[]]$ComputerName ) process { foreach ($c in $ComputerName) { $avg = Get-WmiObject win32_processor -computername $c | Measure-Object -property LoadPercentage -Average | Foreach {$_.Average} $mem = Get-WmiObject win32_operatingsystem -ComputerName $c | Foreach {"{0:N2}" -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize)} $free = Get-WmiObject Win32_Volume -ComputerName $c -Filter "DriveLetter = 'C:'" | Foreach {"{0:N2}" -f (($_.FreeSpace / $_.Capacity)*100)} new-object psobject -prop @{ ComputerName = $c AverageCpu = $avg MemoryUsage = $mem PercentFree = $free } } } } Function MainFunction{ $env:COMPUTERNAME | Get-ComputerStats | Format-Table } MainFunction
PowerShellCorpus/GithubGist/philipproplesch_5830384_raw_58475e8aef4e918d1fe43c11708902998082383b_SQLServerRebuildIndexes.ps1
philipproplesch_5830384_raw_58475e8aef4e918d1fe43c11708902998082383b_SQLServerRebuildIndexes.ps1
$serverName = "" $userName = "" $password = "" $maxFragmentation = 10 $databases = @("Sitecore_Core", "Sitecore_Master", "Sitecore_Web") [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") $connection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection $connection.ServerInstance = $serverName if ($userName -and $password) { $connection.LoginSecure = $false $connection.Login = $userName $connection.Password = $password } $server = New-Object Microsoft.SqlServer.Management.Smo.Server($connection) ForEach ($database in $server.Databases) { if($databases -and $databases -notcontains $database.Name) { continue; } ForEach ($table in $database.Tables) { Write-Host "$database -> $table" ForEach ($index in $table.Indexes) { $fragmentation = $index.EnumFragmentation() | ForEach-Object { $_.AverageFragmentation } Write-Host "`t$index ($fragmentation %)" -ForegroundColor Yellow if ($fragmentation -ge $maxFragmentation) { $index.Rebuild() Write-Host "`tThe index has been rebuilded successfully." -ForegroundColor Green } } } }
PowerShellCorpus/GithubGist/adefran83_8600591_raw_2f168607be5282a2796eccbd248a7c8c7c3333d3_rename.ps1
adefran83_8600591_raw_2f168607be5282a2796eccbd248a7c8c7c3333d3_rename.ps1
//Navigate to directory where files need to be renamed are Dir | Rename-Item –NewName { $_.name –replace “ “,”_” }
PowerShellCorpus/GithubGist/davideicardi_a8247230515177901e57_raw_7d126d5f1e5283306083dca6fe414bed4506b847_kuduSiteUpload.ps1
davideicardi_a8247230515177901e57_raw_7d126d5f1e5283306083dca6fe414bed4506b847_kuduSiteUpload.ps1
Param( [Parameter(Mandatory = $true)] [string]$websiteName, [Parameter(Mandatory = $true)] [string]$sourceDir, [string]$destinationPath = "/site/wwwroot" ) # Usage: .\kuduSiteUpload.ps1 -websiteName mySite -sourceDir C:\Temp\mydir Function d3-KuduUploadDirectory { param( [string]$siteName = $( throw "Missing required parameter siteName"), [string]$sourcePath = $( throw "Missing required parameter sourcePath"), [string]$destinationPath = $( throw "Missing required parameter destinationPath") ) $zipFile = [System.IO.Path]::GetTempFileName() + ".zip" d3-ZipFiles -zipfilename $zipFile -sourcedir $sourcePath d3-KuduUploadZip -siteName $siteName -sourceZipFile $zipFile -destinationPath $destinationPath } Function d3-KuduUploadZip { param( [string]$siteName = $( throw "Missing required parameter siteName"), [string]$sourceZipFile = $( throw "Missing required parameter sourceZipFile"), [string]$destinationPath = $( throw "Missing required parameter destinationPath") ) $webSite = Get-AzureWebsite -Name $siteName $timeOutSec = 600 $username = $webSite.PublishingUsername $password = $webSite.PublishingPassword $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password))) $baseUrl = "https://" + $siteName + ".scm.azurewebsites.net" $apiUrl = d3-JoinParts ($baseUrl, "api/zip", $destinationPath) '/' Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method PUT -InFile $sourceZipFile -ContentType "multipart/form-data" -TimeoutSec $timeOutSec } Function d3-JoinParts { param ([string[]] $Parts, [string] $Separator = '/') # example: # d3-JoinParts ('http://mysite','sub/subsub','/one/two/three') '/' $search = '(?<!:)' + [regex]::Escape($Separator) + '+' #Replace multiples except in front of a colon for URLs. $replace = $Separator ($Parts | ? {$_ -and $_.Trim().Length}) -join $Separator -replace $search, $replace } Function d3-ZipFiles { Param( [Parameter(Mandatory = $true)] [String]$zipfilename, [Parameter(Mandatory = $true)] [String]$sourcedir ) Add-Type -Assembly System.IO.Compression.FileSystem $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $false) } $startTime = Get-Date d3-KuduUploadDirectory -siteName $websiteName -sourcePath $sourceDir -destinationPath $destinationPath $finishTime = Get-Date Write-Host (" Total time used (minutes): {0}" -f ($finishTime - $startTime).TotalMinutes)
PowerShellCorpus/GithubGist/absolutejam_357efb1cc7f0e8b743b2_raw_340835f3a9fa8ee04660a37a4efa7a5e8cdba53c_reset-user-passwords.ps1
absolutejam_357efb1cc7f0e8b743b2_raw_340835f3a9fa8ee04660a37a4efa7a5e8cdba53c_reset-user-passwords.ps1
# ------------------------------------------------------------------------ # Edit these! $Password = 'apple' # The password you want to set $TargetOU = 'Test OU' # Apply to all users in this OU # You can use the * wildcard in $TargetOU # ------------------------------------------------------------------------ $SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force $ADUsers = Get-ADUser -Filter * -SearchBase ( Get-ADOrganizationalUnit -Filter "Name -like '$TargetOU'" ) -SearchScope OneLevel ForEach ( $ADUser in $ADUsers) { Set-ADAccountPassword -Identity $ADUser -NewPassword $SecurePassword }
PowerShellCorpus/GithubGist/yoshimov_3817081_raw_8c2ca7817f38e382ccc867c7538c4cc14598a40a_first-chocolatey.ps1
yoshimov_3817081_raw_8c2ca7817f38e382ccc867c7538c4cc14598a40a_first-chocolatey.ps1
# @powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.github.com/gist/3817081/first-chocolatey.ps1'))" # install Chocolatey iex ((new-object net.webclient).DownloadString('http://bit.ly/psChocInstall')) # basic cinst vlc cinst 7zip cinst pdfcreator cinst keepass cinst git cinst ccleaner cinst unlocker cinst apache.ant cinst virtualclonedrive cinst xyzzy cinst vim cinst putty cinst groovy cinst freemind cinst dia cinst evernote cinst adobereader # Synergy should be the last one. It will reboot machine silently. cinst synergy
PowerShellCorpus/GithubGist/stil_9299946_raw_632f0d5d1c162206e960532dd352838e53c2e882_backup.ps1
stil_9299946_raw_632f0d5d1c162206e960532dd352838e53c2e882_backup.ps1
# CONFIGURATION $dirToBackup = "C:\Users\John" # path to directory we back up (no following backslash) $outputDir = "E:\bak" # path directory we store our backups (no following backslash) $params = '-t7z', '-r', '-ms=off', '-mx1' # THE SCRIPT $fullBackup = $outputDir + "\full.7z" if (Test-Path ($fullBackup)) { # Let's check whether full backup exists Write-Host "Full backup already exists" $args = ,'u' + $params $args += '-u-', "-up0q3r2x2y2z0w2!`"$($outputDir)\diff-$(Get-Date -format "yyyyMMdd-HHmmss").7z`"" $args += $fullBackup, $dirToBackup } else { $args = , ('a') + $params + $fullBackup + $dirToBackup } & 7z $args
PowerShellCorpus/GithubGist/phansch_3813881_raw_d856757192138cd212f1477e5bf9e13376aa92c5_GitHub.PowerShell_profile.ps1
phansch_3813881_raw_d856757192138cd212f1477e5bf9e13376aa92c5_GitHub.PowerShell_profile.ps1
function shorten-path([string] $path) { $loc = $path.Replace($HOME, '~') # remove prefix for UNC paths $loc = $loc -replace '^[^:]+::', '' # make path shorter like tabs in Vim, # handle paths starting with \\ and . correctly return ($loc -replace '\\(\.?)([^\\])[^\\]*(?=\\)','\$1$2') } function prompt { if(Test-Path .git) { # retrieve branch name $symbolicref = (git symbolic-ref HEAD) $branch = $symbolicref.substring($symbolicref.LastIndexOf("/") +1) # retrieve branch status $differences = (git diff-index HEAD --name-status) $git_mod_count = [regex]::matches($differences, 'M\s').count $git_add_count = [regex]::matches($differences, 'A\s').count $git_del_count = [regex]::matches($differences, 'D\s').count $branchData = " +$git_add_count ~$git_mod_count -$git_del_count" # write status string (-n : NoNewLine; -f : ForegroundColor) write-host 'GIT' -n -f White write-host ' {' -n -f Yellow write-host (shorten-path (pwd).Path) -n -f White write-host ' [' -n -f Yellow write-host $branch -n -f Cyan write-host $branchData -n -f Red write-host ']' -n -f Yellow write-host ">" -n -f Yellow } else { # write status string write-host 'PS' -n -f White write-host ' {' -n -f Yellow write-host (shorten-path (pwd).Path) -n -f White write-host ">" -n -f Yellow } return " " }
PowerShellCorpus/GithubGist/pepoluan_5832392_raw_19823bc99e52514a6db255a9046e0ba270fc67fc_Get-Ancestors.ps1
pepoluan_5832392_raw_19823bc99e52514a6db255a9046e0ba270fc67fc_Get-Ancestors.ps1
Function Get-Ancestors() { # The [switch] decorator allows specifying parameters as a flag param( $Identity, [switch]$Silent, [switch]$IncludeAllProperties ) # Initialize the hashtable and the .Net Queue $Ancestors = @{} $Queue = New-Object System.Collections.Queue Function getParents($d) { # The -IncludeAllProperties switch of ActiveRoles Shell *totally* ignore # whatever value we assign to it (e.g., specifying "-IncludeAllProperties:false" # will result in identical result as specifying "-IncludeAllProperties". # That is why we need to 'build' the parameter set $params = @{ Identity = $d } If ($IncludeAllProperties) { $params += @{ IncludeAllProperties = $True } } $parents = Get-QADMemberOf @params ForEach ($p in $parents) { If (! $Ancestors.ContainsKey($p.DN) ) { If (! $Silent) { Write-Host "." -NoNewLine } $Ancestors.Add($p.DN,$p) $Queue.Enqueue($p) } } } $o = $Identity Do { getParents $o If ($Queue.Count -ge 1) { $o = $Queue.Dequeue() } Else { Break } } Until ($false) Write-Host "" # The type of $Ancestors.Values is ValueCollection, we flatten it to an # array to simplify further processing. For example: If you want to get the # n-th member of the result, you can simply wrap this function's # incantations in parens ( ) and specify an array index. E.g. : # (Get-Ancestors username)[2] @( $Ancestors.Values ) }
PowerShellCorpus/GithubGist/n-fukuju_8487498_raw_cdd93509bdb2130315b812b9b2d80e20001b69d2_getfoldersize.ps1
n-fukuju_8487498_raw_cdd93509bdb2130315b812b9b2d80e20001b69d2_getfoldersize.ps1
# [int] カレントパスのフォルダサイズ (Get-ChildItem -Recurse -Force | Measure-Object -Sum Length).Sum # [string, int][] カレントパス配下に存在する各フォルダのサイズ Get-ChildItem | Select-Object Name,@{name="Size";expression={(Get-ChildItem $_.FullName -Recurse -Force | Measure-Object Length -Sum).Sum}}
PowerShellCorpus/GithubGist/cromwellryan_3383306_raw_ff1486584c1b541d6f78615cf622885718fa0f0e_host.ps1
cromwellryan_3383306_raw_ff1486584c1b541d6f78615cf622885718fa0f0e_host.ps1
function start-host($root) { $iisexpress = "$env:ProgramFiles\\IIS Express\\iisexpress.exe" if (!(test-path $iisexpress)) { write-error "Unable to locate IIS Express at $iisexpress" return } $approot = resolve-path $root write-host "Starting iisexpress at $approot" start $iisexpress @('/path:' + $approot) }
PowerShellCorpus/GithubGist/GuruAnt_7216184_raw_cda8a9f518d27d32997b99e0afd3c218c33e2dd2_getVCenterBuildNumbers.ps1
GuruAnt_7216184_raw_cda8a9f518d27d32997b99e0afd3c218c33e2dd2_getVCenterBuildNumbers.ps1
# Script to connect to a list of vCenter Servers, and get their version numbers, as well as the version numbers of their hosts # Ben Neise # 02/10/09 # Array of vCenter Servers $arrVCenterServers = @("server1","server2","server3") # Create empty arrays for the results $arrTableVCs = @() $arrTableHosts = @() # Loop through the array of vCenter servers specified above ForEach ($strVCenterServer in $arrVCenterServers){ # Connect to the VC $objVCenterServer = Connect-VIServer $strVCenterServer # Version info about the VC you are connected to $viewVCenterServer = Get-View serviceinstance # Add custom attributes to each VC objects for version and build $objVCenterServer | Add-Member -Name Version -type noteproperty -value ($viewVCenterServer.content.about.Version) -Force $objVCenterServer | Add-Member -Name Build -type noteproperty -value ($viewVCenterServer.content.about.Build) -Force # Add the VC object to the results array $arrTableVCs += $objVCenterServer # When connected to loop through the hosts managed by the VC ForEach ($objHost in (Get-VMhost | Sort-Object)){ # Get the view for the current host $viewHost = $objHost | Get-View # Add custom attributes to the host object for VC server, Host and Version $objHost | Add-Member -Name VCServer -type noteproperty -value $objVCenterServer.Name -Force $objHost | Add-Member -Name Host -type noteproperty -value $viewHost.Name -Force $objHost | Add-Member -Name Version -type noteproperty -value $viewHost.Config.Product.Version -Force # Add the host object to the results array $arrTableHosts += $objHost } # Disconnect from the VC server Disconnect-VIServer -Confirm:$False } # Output the VC results (can be modified to output to a CSV with Export-CSV) $arrTableVCs | Select-Object Name, Version, Build | Sort-Object Name # Output the Host results (can be modified to output to a CSV with Export-CSV) $arrTableHosts | Select-Object VCServer, Host, Version, Build | Format-Table # End of script
PowerShellCorpus/GithubGist/Mimieam_4942208_raw_1418af26522c6aff0810d196af604dd90d736238_Syncy.ps1
Mimieam_4942208_raw_1418af26522c6aff0810d196af604dd90d736238_Syncy.ps1
Unregister-Event FileDeleted Unregister-Event FileCreated Unregister-Event FileChanged [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon $contextMenu = New-Object System.Windows.Forms.ContextMenu $MenuItem = New-Object System.Windows.Forms.MenuItem $objNotifyIcon.ContextMenu = $contextMenu $objNotifyIcon.contextMenu.MenuItems.AddRange($MenuItem) # $objNotifyIcon.contextMenu.MenuItems.Add($MenuItem) $MenuItem.Text = "Exit" # $MenuItem.add_Click({ Get-EventSubscriber | ? {$_.SourceObject -like "System.IO.FileSystemWatcher"} | Unregister-Event FileDeleted | Unregister-Event FileCreated | Unregister-Event FileChanged $objNotifyIcon.Visible = $false Write-Host "Please restart service ASAP" }) $MenuItem.add_Click({ Unregister-Event FileDeleted Unregister-Event FileCreated Unregister-Event FileChanged $objNotifyIcon.Visible = $false Write-Host "Please restart service ASAP" }) $Source = 'C:\Users\LiliEAm\Dropbox\Projects\Scrabble' # Enter the root path you want to monitor. $NewDestPath ='C:\Users\LiliEAm\Documents\GitHub\MScrab' $filter = '*.*' # You can enter a wildcard filter here. # In the following line, you can change 'IncludeSubdirectories' to $true if required. $watcher = New-Object IO.FileSystemWatcher $Source, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} # Here, all three events are registerd. You need only subscribe to events that you need: Register-ObjectEvent $watcher Created -SourceIdentifier FileCreated -Action { $name = $Event.SourceEventArgs.Name $changeType = $Event.SourceEventArgs.ChangeType $timeStamp = $Event.TimeGenerated Write-Host "The file '$name' was $changeType at $timeStamp" -fore green $objNotifyIcon.Icon = "C:\Users\LiliEAm\Dropbox\Training\Google_Appengine_T\helloworld_unOptimized\Original\H9.ico" $objNotifyIcon.BalloonTipIcon = "Info" $objNotifyIcon.BalloonTipText = "The file '$name' was $changeType at $timeStamp" $objNotifyIcon.BalloonTipTitle = "$changeType" $objNotifyIcon.Visible = $True $objNotifyIcon.ShowBalloonTip(10000) # $objNotifyIcon.Dispose(); Out-File -FilePath outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp" Copy-Item -Path $($Event.SourceEventArgs.FullPath) -Destination $NewDestPath } Unregister-Event FileDeleted Register-ObjectEvent $watcher Deleted -SourceIdentifier FileDeleted -Action { $name = $Event.SourceEventArgs.Name $changeType = $Event.SourceEventArgs.ChangeType $timeStamp = $Event.TimeGenerated Write-Host "The file '$name' was $changeType at $timeStamp" -fore red $objNotifyIcon.Icon = "C:\Users\LiliEAm\Dropbox\Training\Google_Appengine_T\helloworld_unOptimized\Original\H9.ico" $objNotifyIcon.BalloonTipIcon = "Info" $objNotifyIcon.BalloonTipText = "The file '$name' was $changeType at $timeStamp" $objNotifyIcon.BalloonTipTitle = "$changeType" $objNotifyIcon.Visible = $True $objNotifyIcon.ShowBalloonTip(10000) # $objNotifyIcon.Dispose(); Out-File -FilePath outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp" $ItemToRemove = "$NewDestPath\$name" Write-Host "Removing item : $ItemToRemove" remove-item -Path $ItemToRemove # Copy-Item -Path $($event.sourceEventArgs.FullPath) -Destination $NewDestPath } Register-ObjectEvent $watcher Changed -SourceIdentifier FileChanged -Action { $name = $Event.SourceEventArgs.Name $changeType = $Event.SourceEventArgs.ChangeType $timeStamp = $Event.TimeGenerated Write-Host "The file '$name' was $changeType at $timeStamp" -fore white $objNotifyIcon.Icon = "C:\Users\LiliEAm\Dropbox\Training\Google_Appengine_T\helloworld_unOptimized\Original\H9.ico" $objNotifyIcon.BalloonTipIcon = "Info" $objNotifyIcon.BalloonTipText = "The file '$name' was $changeType at $timeStamp" $objNotifyIcon.BalloonTipTitle = "$changeType" $objNotifyIcon.Visible = $True $objNotifyIcon.ShowBalloonTip(10000) # $objNotifyIcon.Dispose(); Out-File -FilePath outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp" Copy-Item -Path $($event.sourceEventArgs.FullPath) -Destination $NewDestPath }
PowerShellCorpus/GithubGist/johannvs_5661056_raw_442d41adfefac723b8c5435843e396b97cfa073a_New-MailboxExport.ps1
johannvs_5661056_raw_442d41adfefac723b8c5435843e396b97cfa073a_New-MailboxExport.ps1
<# .SYNOPSIS New-MailboxExport.ps1 - Export an Exchange Mailbox to PST remotely. .DESCRIPTION Export an Exchange Mailbox to PST remotely instead of using the Exchange Management Shell. .PARAMETER RemoteExchangeServer FQDN of Exchange Server to where a PSSession will be established for the export request. .PARAMETER User The SAMAccountName of the user for which the mailbox must be exported to PST. .PARAMETER PSTFilePath The shared path to where the PST will be exported. The user that executes the script must have write permissions to the share. .PARAMETER EmailFrom (Optional) From email adrress. .PARAMETER EmailTo To email address. Email will be sent to this email. .PARAMETER SMTPServer SMTP server that is used to send the email. .EXAMPLE .\New-MailboxExport.ps1 -RemoteExchangeServer -exchange.test.local -User test.user -PSTFilePath \\fileserver.test.local\Export -EmailTo [email protected] -SMTPServer mail.test.local Will start an export request for the mailbox of test.user to be exported to \\fileserver.test.local\Export\test.user.pst. Will watcht the export request status and write progress to console. Will send an email to [email protected] via the mail.test.local smtp server. Email will come from [email protected]. .EXAMPLE .\New-MailboxExport.ps1 -RemoteExchangeServer -exchange.test.local -User test.user -PSTFilePath \\fileserver.test.local\Export -EmailTo [email protected] -EmailFrom [email protected] -SMTPServer mail.test.local Will start an export request for the mailbox of test.user to be exported to \\fileserver.test.local\Export\test.user.pst. Will watcht the export request status and write progress to console. Will send an email to [email protected] via the mail.test.local smtp server. Email will come from [email protected]. .NOTES Written By: Johann van Schalkwyk Email: [email protected] Twitter: @scallie_84 Change Log V1.0, 28/5/2013 - Initial version V1.1, 28/5/2013 - Changed Get-Credential code to use the current user info. Changed the variable $25Sent, $50Sent and $75Sent to Boolean. - Changed the email sent code so that if a mailbox jumps from 49% to 52% complete the email notification is not missed. V2.0, 29/5/2113 - Removed Remote from script name that caused confusion. #> [CmdletBinding()] Param( [Parameter(Mandatory=$True, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, HelpMessage='FQDN of Exchange server to where a PSSession will be established for the export request.')] [String] $RemoteExchangeServer = "exchange.test.local" , [Parameter(Mandatory=$True, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, HelpMessage='Active Directory username of user which mailbox is exported.')] [String] $User = "test.user" , [Parameter(Mandatory=$True, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, HelpMessage='Shared directory where PST will be exported to. User that executes the request must have Read/Write permissions to share.')] [String] $PSTFilePath = "\\fileserver.test.local\Export" , [Parameter(Mandatory=$False, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, HelpMessage='From email address used in email notification.')] [Alias('From', 'Sender')] [String] $EmailFrom = "[email protected]" , [Parameter(Mandatory=$True, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, HelpMessage='Email address that will receive the notification.')] [Alias('To', 'Recipient')] [String] $EmailTo = "[email protected]" , [Parameter(Mandatory=$True, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, HelpMessage='SMTP Server used for sending the email notifications.')] [Alias('EmailServer')] [String] $SMTPServer = "smtp.test.local" ) Write-Verbose "Gets Credentials required for open PSSession" $Credential = $host.ui.PromptForCredential("Enter Required Credentials", "Please enter your user name and password for $env:userdomain domain.", "$env:userdomain\$env:username", "") Write-Verbose "Uses the $RemoteExchangeServer parameter to populate the required ConnectionUri variable for the PSSession" $ConnectionUri = "http://$RemoteExchangeServer/Powershell" Write-Verbose "Uses the $PSTFilePath parameter to populate the required FilePath variable for the Export Request" $ExportPath = "$PSTFilePath\$User.pst" Write-Verbose "Establishes a PSSession to the $RemoteExchangeServer" $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ConnectionUri -Authentication Kerberos -Credential $Credential Write-Verbose "Start the Export Request" Invoke-Command -Session $Session -ScriptBlock { Param($Remote_User, $Remote_ExportPath) New-MailboxExportRequest -Mailbox $Remote_User -FilePath $Remote_ExportPath } -ArgumentList $User, $ExportPath -HideComputerName Write-Verbose "Gets initial mailbox export request status and populates required variables" $ExportStats = Invoke-Command -Session $Session -ScriptBlock { Param($Remote_User) Get-MailboxExportRequest -Mailbox $Remote_User | Get-MailboxExportRequestStatistics } -ArgumentList $User -HideComputerName $SourceAlias = $ExportStats.SourceAlias $PercentComplete = $ExportStats.PercentComplete $ExportStatus = $ExportStats.Status $25Sent = $False $50Sent = $False $75Sent = $False Write-Verbose "While mailbox export request status is 'Queued', Sleep for 30seconds then gets mailbox export request status again." WHILE ($ExportStatus -eq "Queued") { Start-Sleep 30 $ExportStats = Invoke-Command -Session $Session -ScriptBlock { Param($Remote_User) Get-MailboxExportRequest -Mailbox $Remote_User | Get-MailboxExportRequestStatistics } -ArgumentList $User -HideComputerName $SourceAlias = $ExportStats.SourceAlias $PercentComplete = $ExportStats.PercentComplete $ExportStatus = $ExportStats.Status } Write-Verbose "While mailbox export request is 'InProgess', Show the progess in the console with Write-Progess" WHILE ($ExportStatus -eq "InProgress") { $ExportStats = Invoke-Command -Session $Session -ScriptBlock { Param($Remote_User) Get-MailboxExportRequest -Mailbox $Remote_User | Get-MailboxExportRequestStatistics } -ArgumentList $User -HideComputerName $SourceAlias = $ExportStats.SourceAlias $PercentComplete = $ExportStats.PercentComplete $ExportStatus = $ExportStats.Status Clear-Host Write-Progress -Activity "Exchange Mailbox Export for $SourceAlias" -Status "Percent Complete: $PercentComplete" -PercentComplete $ExportStats.PercentComplete Write-Verbose "If the mailbox export is 25% complete send an email to $EmailTo" IF ($25Sent -eq $False ) { IF ($PercentComplete -ge "25" -and $PercentComplete -lt "49") { $MessageContent = "The Exchange Mailbox Export for $SourceAlias is 25% complete." Send-MailMessage -To $EmailTo -From $EmailFrom -Subject "Exchange Mailbox Export" -SmtpServer $SMTPServer -BodyAsHtml -Body $MessageContent -Priority High $25Sent = $True } } Write-Verbose "If the mailbox export is 50% complete send an email to $EmailTo" IF ($50Sent -eq $False ) { IF ($PercentComplete -ge "50" -and $PercentComplete -lt "74") { $MessageContent = "The Exchange Mailbox Export for $SourceAlias is 50% complete." Send-MailMessage -To $EmailTo -From $EmailFrom -Subject "Exchange Mailbox Export" -SmtpServer $SMTPServer -BodyAsHtml -Body $MessageContent -Priority High $50Sent = $True } } Write-Verbose "If the mailbox export is 75% complete send an email to $EmailTo" IF ($75Sent -eq $False ) { IF ($PercentComplete -ge "75" -and $PercentComplete -lt "99") { $MessageContent = "The Exchange Mailbox Export for $SourceAlias is 75% complete." Send-MailMessage -To $EmailTo -From $EmailFrom -Subject "Exchange Mailbox Export" -SmtpServer $SMTPServer -BodyAsHtml -Body $MessageContent -Priority High $75Sent = $True } Start-Sleep 30 } } Write-Verbose "If the mailbox export request status is 'Failed', resume the mailbox export request and send email to $EmailTo that the request failed." IF ($ExportStatus -eq "Failed") { Invoke-Command -Session $Session -ScriptBlock { Param($Remote_User) Get-MailboxExportRequest -Mailbox $Remote_User | Resume-MailboxExportRequest } -ArgumentList $User -HideComputerName $MessageContent = "The Exchange Mailbox Export for $SourceAlias failed but was resumed." Send-MailMessage -To $EmailTo -From $EmailFrom -Subject "Exchange Mailbox Export" -SmtpServer $SMTPServer -BodyAsHtml -Body $MessageContent -Priority High } Write-Verbose "If the mailbox export request is complete, remove the mailbox export request and send email to $EmailTo that the export is complete." IF ($ExportStatus -eq "Completed") { Invoke-Command -Session $Session -ScriptBlock { Param($Remote_User) Get-MailboxExportRequest -Mailbox $Remote_User | Remove-MailboxExportRequest } -ArgumentList $User -HideComputerName $MessageContent = "The Exchange Mailbox Export for $SourceAlias is completed." Send-MailMessage -To $EmailTo -From $EmailFrom -Subject "Exchange Mailbox Export" -SmtpServer $SMTPServer -BodyAsHtml -Body $MessageContent -Priority High } Write-Verbose "Close Remote-PSSession" Remove-PSSession -Session $Session
PowerShellCorpus/GithubGist/originalmind_3815479_raw_c2d498770fda9786146239d32dd68671f3852c76_gistfile1.ps1
originalmind_3815479_raw_c2d498770fda9786146239d32dd68671f3852c76_gistfile1.ps1
$webDeployArgs = '-verb:sync -retryAttempts:10 -retryInterval:2000 -source:runCommand="%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -inputformat none -file ' + $SERVER_INSTALL_PATH + 'srv_configure_staff_site.ps1",dontUseCommandExe=true,waitInterval=10000,waitAttempts=6 -dest:auto,computerName=' + $deployServer Start-Process "$Env:SystemDrive\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe" -ArgumentList $webDeployArgs -NoNewWindow -Wait
PowerShellCorpus/GithubGist/briped_28603d3125e5fe72b99b_raw_2eba1e6bcbbbea3c469e49f57597eca2544485da_Move-ADGroupMembers.ps1
briped_28603d3125e5fe72b99b_raw_2eba1e6bcbbbea3c469e49f57597eca2544485da_Move-ADGroupMembers.ps1
Param( [parameter(Mandatory=$true, HelpMessage="Enter AD group to move from.")] [string] $SourceGroup, [parameter(Mandatory=$true, HelpMessage="Enter AD group to move to.")] [string] $TargetGroup ) Import-Module -Name ActiveDirectory -ErrorAction SilentlyContinue Get-ADGroupMember -Recursive -Identity $SourceGroup | ForEach-Object { $Error.Clear() Try { Write-Debug -Message "Add-ADGroupMember -Members $($_.SamAccountName)-Identity $($TargetGroup)" Add-ADGroupMember -Members $($_.SamAccountName) -Identity $($TargetGroup) } Catch { Write-Warning -Message "An error occurred when attempting to add $($_.SamAccountName)to $($TargetGroup)" } If (!$Error) { Try { Write-Debug -Message "Remove-ADGroupMember -Members $($_.SamAccountName)-Identity $($SourceGroup) -Confirm:$false" Remove-ADGroupMember -Members $($_.SamAccountName) -Identity $($SourceGroup) -Confirm:$false } Catch { Write-Warning -Message "An error occurred when attempting to remove $($_.SamAccountName)from $($SourceGroup)" } } }
PowerShellCorpus/GithubGist/andrewgunn_b2958ff0c773b165a857_raw_fd067d2f29939b10f9778b1fd0f48dd2ce6a3ed1_Git.ps1
andrewgunn_b2958ff0c773b165a857_raw_fd067d2f29939b10f9778b1fd0f48dd2ce6a3ed1_Git.ps1
# Prerequisites # - Download https://github.com/downloads/anurse/git-credential-winstore/git-credential-winstore.exe and copy it to C:/Program Files (x86)/Git/libexec/git-core $name = read-host "Enter your name" $emailAddress = read-host "Enter your email address" git config --global core.autocrlf true git config --global core.editor \"C:/Program Files (x86)/GitExtensions/GitExtensions.exe\" fileeditor git config --global credential.helper winstore git config --global diff.tool bc3 git config --global difftool.bc3.path "C:/Program Files (x86)/Beyond Compare 4/BComp.exe" git config --global difftool.beyondcompare3.path "C:/Program Files (x86)/Beyond Compare 4/BComp.exe" git config --global difftool.prompt false git config --global merge.tool bc3 git config --global mergetool.bc3.path "C:/Program Files (x86)/Beyond Compare 4/BComp.exe" git config --global mergetool.keepBackup false git config --global mergetool.prompt false git config --global push.default matching git config --global user.name "$name" git config --global user.email "$emailAddress" # Manual steps # ------------ # - Add a HOME environment variable with a value of %USERPROFILE% # - Open C:/tools/poshgit/dahlbyk-posh-git-*/profile.example.ps1 and comment/remove Start-SshAgent -Quiet # - Install Microsoft Visual Studio Tools for Git - http://visualstudiogallery.msdn.microsoft.com/abafc7d6-dcaa-40f4-8a5e-d6724bdb980c
PowerShellCorpus/GithubGist/orgimoto_5316573_raw_427eb405293fc9aa22f3bdd152d85beb5b16067b_Microsoft.PowerShell_profile.ps1
orgimoto_5316573_raw_427eb405293fc9aa22f3bdd152d85beb5b16067b_Microsoft.PowerShell_profile.ps1
#-- 設定値 --# $HistoryLogFile="${HOME}\AppFiles\Powershell\ps_history.xml" $MaximumHistoryCount = 10000 #-- 設定 --# Import-Clixml $HistoryLogFile | Add-History #-- 関数 --# function Save-History{ Get-History -Count $MaximumHistoryCount | Export-Clixml ${HistoryLogFile} } function e{ Save-History exit } function rm ($filePath) { Remove-Item -Confirm $filePath } function Select-History ([string]$Pattern='', [string[]]$Exclude=@()) { if($Exclude.Count -eq 0){ return Get-History -Count $MaximumHistoryCount | ?{ $_.CommandLine -like "*${Pattern}*" } } else { $regEx=($Exclude | % { [regex]::escape($_) } ) -join "|" return Get-History -Count $MaximumHistoryCount | ?{ $_.CommandLine -like "*${Pattern}*" } | ?{ $_.CommandLine -notmatch ${regEx}} } } <# .SYNOPSIS ランダムな文字列を作る .DESCRIPTION 文字列の長さ、記号有無を指定するとランダムな文字列を返す。 ランダムパスワード作成などに活用する。 .LINK http://powershell.com/cs/blogs/tips/archive/2010/12/13/create-random-passwords.aspx http://mtgpowershell.blogspot.jp/2010/12/%E3%83%A9%E3%83%B3%E3%83%80%E3%83%A0%E3%81%AA%E3%83%91%E3%82%B9%E3%83%AF%E3%83%BC%E3%83%89%E3%82%92%E4%BD%9C%E3%82%8Bget-random.html .NOTES デフォルトでは10桁の英数字文字列を返す。 .EXAMPLE mGet-RandomPassword.ps1 -length 7 -char 'abcdefghijklmnopqrstuvwxyz0123456789' #> function Get-RandomString([int]$Size=10, [bool]$IncludeSymbol=$false){ $characters='abcdefghkmnoprstuvwxyzABCDEFGHKLMNOPRSTUVWXYZ0123456789' if($IncludeSymbol){ $characters+='!"$%&/()=?*+#_' } # select random characters $random = 1..$Size | ForEach-Object { Get-Random -Maximum $characters.length } # output random pwd ($characters[$random] -join '') } #-- エイリアス --# Set-Alias sh Save-History Set-Alias ss Select-String Set-Alias which where.exe Remove-Item alias:diff -Force
PowerShellCorpus/GithubGist/breezhang_4544015_raw_c6aa6e6b8874d9cafc6e61369150be0f79adcf41_get_set_.ps1
breezhang_4544015_raw_c6aa6e6b8874d9cafc6e61369150be0f79adcf41_get_set_.ps1
${c:\a.file} = 12345 # set ${c:\a.file} = "" #empty ${c:\a.file} +="file" #apply ${c:\a.file} = ${c:\b.file} #copy file
PowerShellCorpus/GithubGist/wiking-at_a276d32211bb8228fe08_raw_0546cc6dbc0982f76fe977da91118042f5865adf_db-migration.ps1
wiking-at_a276d32211bb8228fe08_raw_0546cc6dbc0982f76fe977da91118042f5865adf_db-migration.ps1
Function Get-IniContent { <# .Synopsis Gets the content of an INI file .Description Gets the content of an INI file and returns it as a hashtable .Notes Author : Oliver Lipkau <[email protected]> Blog : http://oliver.lipkau.net/blog/ Date : 2014/06/23 Version : 1.1 #Requires -Version 2.0 .Inputs System.String .Outputs System.Collections.Hashtable .Parameter FilePath Specifies the path to the input file. .Example $FileContent = Get-IniContent "C:\myinifile.ini" ----------- Description Saves the content of the c:\myinifile.ini in a hashtable called $FileContent .Example $inifilepath | $FileContent = Get-IniContent ----------- Description Gets the content of the ini file passed through the pipe into a hashtable called $FileContent .Example C:\PS>$FileContent = Get-IniContent "c:\settings.ini" C:\PS>$FileContent["Section"]["Key"] ----------- Description Returns the key "Key" of the section "Section" from the C:\settings.ini file .Link Out-IniFile #> [CmdletBinding()] Param( [ValidateNotNullOrEmpty()] [ValidateScript({(Test-Path $_) -and ((Get-Item $_).Extension -eq ".ini")})] [Parameter(ValueFromPipeline=$True,Mandatory=$True)] [string]$FilePath ) Begin {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"} Process { Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing file: $Filepath" $ini = @{} switch -regex -file $FilePath { "^\[(.+)\]$" # Section { $section = $matches[1] $ini[$section] = @{} $CommentCount = 0 } "^(;.*)$" # Comment { if (!($section)) { $section = "No-Section" $ini[$section] = @{} } $value = $matches[1] $CommentCount = $CommentCount + 1 $name = "Comment" + $CommentCount $ini[$section][$name] = $value } "(.+?)\s*=\s*(.*)" # Key { if (!($section)) { $section = "No-Section" $ini[$section] = @{} } $name,$value = $matches[1..2] $ini[$section][$name] = $value } } Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing file: $path" Return $ini } End {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"} } Set-Location F:\Server1\db #$query = (dir -include *.ini -recurse | select-string 'bankmoney' ) $query = (dir -include *.ini -recurse | select-string 'wiking' ) #$query.Path #todo - build for loop to create the sql import file $iniconent = Get-IniContent $query.path $uid = $iniconent["Playerinfo"][“UID”] $name = $iniconent["Playerinfo"][“Name”] $lastside = $iniconent["Playerinfo"][“LastSide”] $bankmoney = $iniconent["Playerinfo"][“BankMoney”] "insert into table values $uid, $name, $lastside, $bankmoney"
PowerShellCorpus/GithubGist/belotn_4986539_raw_cc4a6989f605a99eebe7cd2d25b8a03c07b25c1f_move-datastore.ps1
belotn_4986539_raw_cc4a6989f605a99eebe7cd2d25b8a03c07b25c1f_move-datastore.ps1
$username ="MyUser" $password="MyPwd" $dsnfilename="Path/to/my/newdsn" Get-xaserver |% { $serverName = $_.servername $servername get-content New.dsn |%{ if ($_ -like '*WSID*') {"WSID=$servername" }else{$_} } | out-file "\\$($_.ServerNAme)\c$\Path\to\newdsn" $command = "cmd /c dsmaint config /user:$username /pwd:$password /dsn:$dsnfilename > c:\dsm_config.log" $process = [WMICLASS]"\\$serverName\ROOT\CIMV2:win32_process" $result = $process.Create($command) Start-Sleep -seconds 10 "Arret dépendant" $depsvc = Get-Service -ComputerName $serverName -name IMAService -dependentservices | Select -Property Name $depsvc | %{ $svc = Get-Service -ComputerName $serverName -name $_.Name $svc.Stop() while($svc.status -ne "Stopped"){ $svc = Get-Service -ComputerName $serverName -name $svc.NAme Start-Sleep -seconds 1 } } "Arret IMA" $service = Get-Service -ComputerName $serverName -name IMAService $service.stop() while($service.status -ne "Stopped"){ $service = Get-Service -ComputerName $serverName -name IMAService Start-Sleep -seconds 1 } "Relance IMA" $service.start() while($service.status -ne "Running"){ $service = Get-Service -ComputerName $serverName -name IMAService Start-Sleep -seconds 1 } "Relance dependant" $depsvc | %{ $svc = Get-Service -ComputerName $serverName -name $_.Name $svc.Start() while($svc.status -ne "Running"){ $svc = Get-Service -ComputerName $serverName -name $svc.NAme Start-Sleep -seconds 1 } } }
PowerShellCorpus/GithubGist/VoidVolker_f67765e7eaf0b898bdc6_raw_53e94eaf29fb044b51f52cffec3031cfe62eef02_powershell%20ftp%20http%20get%20unzip%20get-unzip.ps1
VoidVolker_f67765e7eaf0b898bdc6_raw_53e94eaf29fb044b51f52cffec3031cfe62eef02_powershell%20ftp%20http%20get%20unzip%20get-unzip.ps1
# Download the file to a specific location # get-unzip.ps1 "ftp://path/filename" "C:\path" "filename" $clnt = new-object System.Net.WebClient $url = $args[0] $folder = $args[1] $file = $args[2] $path = $($args[1]+"\"+$args[2]) $clnt.DownloadFile($url,$path) # Unzip the file to specified location $shell_app=new-object -com shell.application $zip_file = $shell_app.namespace($path) $destination = $shell_app.namespace($folder) $destination.Copyhere($zip_file.items())
PowerShellCorpus/GithubGist/pothedar_a295cbc9949d23d2b06b_raw_2b3e57ea2c1c23f02105b589f7bbf1ac277ec43a_InstallPackages.ps1
pothedar_a295cbc9949d23d2b06b_raw_2b3e57ea2c1c23f02105b589f7bbf1ac277ec43a_InstallPackages.ps1
param( [string] $SQLpass=$null, [string] $p4port=$null, [string] $p4user=$null, [string] $P4pass=$null ) # Boxstarter options # commenting these options since auto reboot is fickle and was found to run in loops #$Boxstarter.RebootOk=$false # Allow reboots #$Boxstarter.NoPassword=$false # Is this a machine with no login password #$Boxstarter.AutoLogin=$true # Save my password securely and auto-login after a reboot #eclipse install parameters $EclipseLoc = "C:\Eclipse-Kepler" $EclipseZip = "eclipse-standard-kepler-R-win32-x86_64.zip" $zipUrl = 'http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/kepler/R/eclipse-standard-kepler-R-win32.zip&r=1' $zip64Url = 'http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/kepler/R/eclipse-standard-kepler-R-win32-x86_64.zip&r=1' $downloadpath = "$env:Temp\$EclipseZip" # Collect username/Password for packages that are needed during installation if ($SQLpass -eq ""){ $SQLpass = Read-Host "Enter the sa password for SQL server installation" # get sa password for SQL server installation } if ($p4port -eq ""){ $p4port = Read-Host "Enter the perforce port. e.g. ssl:perforce:1666" } if ($p4user -eq ""){ $p4user = Read-Host "Enter the username to connect to the perforce depot" } if ($P4pass -eq ""){ $P4pass = Read-Host "Enter your perforce account password" } # Basic setup. If you run this script remotely do not run the two statements below because it interrupts the main thread and the winrm session will exit #Update-ExecutionPolicy Unrestricted #Enable-psremoting -force winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="512"}' winrm set winrm/config '@{MaxTimeoutms="1800000"}' winrm set winrm/config/service '@{AllowUnencrypted="true"}' winrm set winrm/config/client '@{AllowUnencrypted="true"}' Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions Enable-RemoteDesktop Disable-InternetExplorerESC Disable-UAC #browser cinst googlechrome #developer tools cinst powershell cinst 7zip cinst git cinst p4v cinst p4 cinst nodejs.install #Installs Node.exe and NPM under Program Files, and adds them to the SYSTEM PATH environment variable. cinst intellijidea-community #configure remoting for ansible. this is needed besides winrm config.creates a self signed certificate and sets up winrm for ansible. #iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1')) cinst ant cinst java.jdk cinst VisualStudio2013professional -InstallArguments "/Features:'SilverLight_Developer_Kit SQL WebTools'" cinst mssqlserver2012express -InstallArguments "/SECURITYMODE='SQL' /NPENABLED='0' /SQLSVCSTARTUPTYPE='Automatic' /AGTSVCSTARTUPTYPE='Automatic' /X86='False' /SAPWD=$SQLpass" ####eclipse install is not package based for now since chocolatey kepler package is broken # Setup Eclipse function Expand-ZIPFile($file, $destination) { $shell = new-object -com shell.application $zip = $shell.NameSpace($file) foreach($item in $zip.items()) { $shell.Namespace($destination).copyhere($item) } } function Create-WebClient(){ $webclient = new-object System.Net.WebClient return $webclient } function Download-Extract($url, $destination){ $webclient = Create-WebClient $webclient.DownloadFile($url,$destination) Expand-ZIPFile $destination $EclipseLoc } if(!(Test-Path $EclipseLoc)) { Write-Host "==========Installing Eclipse============" Write-Host "==========Downloading the zip and extracting it==========" New-Item -ItemType directory -Path $EclipseLoc Download-Extract $zip64Url $downloadpath Write-Host "==========creating eclipse shortcut==========" $WshShell = New-Object -ComObject WScript.Shell $Shortcut = $WshShell.CreateShortcut("$Home\Desktop\Eclipse.lnk") $Shortcut.TargetPath = "$EclipseLoc\Eclipse\Eclipse.exe" $Shortcut.Save() } else { Write-Host "==========Looks like eclipse is already installed.==========" } # other tools cinst fiddler4 cinst notepadplusplus #configure perforce and sync sources function runCommand($cmd, $successMessage){ write-host "Executing: $cmd" $cmdOutput = Invoke-Expression $cmd $exitCode = $lastexitcode write-host "output: $cmdOutput and the exitCode = $exitCode" if ($cmdOutput -contains $successMessage -or $exitCode -eq 0) { Write-Host "command executed successfully. Exiting now" return } #commenting the exit for now since azure vm's do not have access to perforce. So this always exits and makes the build red. #exit 1 $Error[0] #print the error message } # there should be no space before and after the equal sign in "P4PORT=$p4port" $p4client = 'varian1_halo' $setP4Port = "p4 set P4PORT=$p4port" $setP4Trust = "p4 trust -y" $setP4Client = "p4 set P4CLIENT=$p4client" $setP4User = "p4 set P4USER=$p4user" $login = "Write-Output $P4pass | p4 -u $p4user login" $sync = "p4 -u $p4user sync -f" runCommand $setP4Port "$p4port" runCommand $setP4Trust "Added trust for P4PORT" runcommand $setP4Client "P4CLIENT=$p4client" runCommand $setP4User "P4USER=$p4user" runCommand $login "User $p4user logged in" runcommand $sync ""
PowerShellCorpus/GithubGist/AbraaoAlves_1779808_raw_df3d46ce9e93d58c439d7b001d2fe22955954a85_GitForPS1.ps1
AbraaoAlves_1779808_raw_df3d46ce9e93d58c439d7b001d2fe22955954a85_GitForPS1.ps1
#Com git instalado, via powershell: #antes de executar o ps1: Set-ExecutionPolicy Unrestricted | responder S if(!$env:path.Contains("C:\Program Files (x86)\Git\bin")) { $env:path += ";C:\Program Files (x86)\Git\bin"; } if(!$env:path.Contains("C:\Program Files (x86)\Git\cmd")) { $env:path += ";C:\Program Files (x86)\Git\cmd"; } (new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex install-module posh-git cd $env:UserProfile\Documents\WindowsPowerShell .\Microsoft.PowerShell_profile.ps1
PowerShellCorpus/GithubGist/VertigoRay_6357306_raw_5331c85c3841c481b2a5b8c30d7844318b71f090_SearchAcrossMultipleDomainsInForest.FindAll.ps1
VertigoRay_6357306_raw_5331c85c3841c481b2a5b8c30d7844318b71f090_SearchAcrossMultipleDomainsInForest.FindAll.ps1
try { foreach ($res in $Search.FindAll()) { $User = $res.GetDirectoryEntry() $NewObject = New-Object PSObject Add-Member -InputObject $NewObject NoteProperty 'DistinguishedName' $User.DistinguishedName Add-Member -InputObject $NewObject NoteProperty 'SamAccountName' $User.SamAccountName $OutputList += $NewObject } } catch { if ($error[0] -ne $null) {Write-Debug $error[0]} } $OutputList
PowerShellCorpus/GithubGist/jpoul_1819706b6b157515be18_raw_32587b34fb0251b3066b21f4064211c64d720bc8_boxstarter.dev.spd.ps1
jpoul_1819706b6b157515be18_raw_32587b34fb0251b3066b21f4064211c64d720bc8_boxstarter.dev.spd.ps1
Set-ExecutionPolicy -ExecutionPolicy Bypass -Confirm:$false Disable-InternetExplorerESC Enable-RemoteDesktop Set-TaskbarOptions -UnLock $false Set-CornerNavigationOptions -EnableUsePowerShellOnWinX Set-StartScreenOptions -EnableBootToDesktop -EnableListDesktopAppsFirst -EnableDesktopBackgroundOnStart Set-WindowsExplorerOptions -EnableShowFileExtensions -EnableShowHiddenFilesFoldersDrives -EnableShowProtectedOSFiles -EnableShowFullPathInTitleBar cinst notepadplusplus.install cinst 7zip.install cinst GoogleChrome cinst ChocolateyGUI cinst adobereader cinst dropbox cinst PowerGUI cinst fiddler cinst webpi cinst Office365ProPlus cinst SharePointDesigner2013x32