full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/ylorn_11153460_raw_043d2538dcd541cfef8b128e5014a025519004a8_aria2_daemon.ps1
ylorn_11153460_raw_043d2538dcd541cfef8b128e5014a025519004a8_aria2_daemon.ps1
# troy at 164.218.21.198.tigernet.wifi.dyn.clemson.edu in ~ [15:17:28] $ ps aux|grep aria2c root 92 7.8 0.3 2464048 21292 ?? Ss 2:58PM 0:20.59 /usr/local/Cellar/aria2/1.18.5/bin/aria2c --conf-path=/Users/troy/.aria2/aria2.conf troy 990 0.0 0.0 2442000 632 s000 S+ 3:17PM 0:00.00 grep aria2c
PowerShellCorpus/GithubGist/harriha_11332150_raw_12cca0ee9d1d17a88a24438c174df0faade76496_show-wifi-passwords.ps1
harriha_11332150_raw_12cca0ee9d1d17a88a24438c174df0faade76496_show-wifi-passwords.ps1
(netsh wlan show profiles) | # Fetch all Wi-Fi profiles Select-String "\:(.+)$" | # Grab the profile name (note: not necessarily equal to SSID) %{$name=$_.Matches.Groups[1].Value.Trim(); $_} | # Store profile name to a var %{(netsh wlan show profile name="$name" key=clear)} | # Fetch profile details with clear-text password Select-String "Key Content\W+\:(.+)$" | # Grab the password %{$pass=$_.Matches.Groups[1].Value.Trim(); $_} | # Store password to a var %{[PSCustomObject]@{ PROFILE_NAME=$name;PASSWORD=$pass }} | # Construct an object to be able to use Format-Table Format-Table -AutoSize # Format the output Write-Host "" Write-Host "Press any key to continue..." Read-Host
PowerShellCorpus/GithubGist/Haacked_6251969_raw_619dc02739688268aa40bea1a4c5b4c1056df9c2_Microsoft.Powershell_profile.ps1
Haacked_6251969_raw_619dc02739688268aa40bea1a4c5b4c1056df9c2_Microsoft.Powershell_profile.ps1
$dir = (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent) Push-Location $dir . (Resolve-Path "$dir\vs2010.ps1") # . "Bradwils\profile.ps1" $env:path += ";" + (Get-Item "Env:ProgramFiles(x86)").Value + "\Git\bin" # Set up GitHub environment Write-Host "Setting up GitHub Environment" . (Resolve-Path "$env:LOCALAPPDATA\GitHub\shell.ps1") Write-Host "Setting up Posh-Git" . (Resolve-Path "$env:github_posh_git\profile.example.ps1") Pop-Location
PowerShellCorpus/GithubGist/gierschv_4642887_raw_93f6f46803fec590e426cb1c2a08354e2a902e5e_MusicJSON.ps1
gierschv_4642887_raw_93f6f46803fec590e426cb1c2a08354e2a902e5e_MusicJSON.ps1
# Epitech / EIP Technical assessment # VM EIP: Launch first `Set-ExecutionPolicy RemoteSigned` # Variables $basedir = "$env:HOMEDRIVE$env:HOMEPATH\Desktop\tmp" $nodeVersion = "v0.8.18" # Common $webClient = New-Object System.Net.WebClient $shell = New-Object -com shell.application # Create Base directory echo "[+] Creating $basedir" if (test-path $basedir) { Remove-Item -Recurse -Force -ErrorAction 0 $basedir | out-null } mkdir $basedir -ErrorAction 0 | out-null # Download and install Node.js echo "[+] Downloading http://nodejs.org/dist/$nodeVersion/node-$nodeVersion.msi" $webClient.DownloadFile("http://nodejs.org/dist/$nodeVersion/node-$nodeVersion-x86.msi","$basedir\node-$nodeVersion-x86.msi") echo "[+] Installing node-$nodeVersion-x86.msi" Start-Process -FilePath msiexec.exe -ArgumentList @("/i", "$basedir\node-$nodeVersion-x86.msi", "/qr") -Wait # Musicjson $zipGithub = "https://github.com/FlatIO/musicjson/archive/master.zip" echo "[+] Downloading $zipGithub" $webClient.DownloadFile($zipGithub, "$basedir\musicjson.zip") echo "[+] Unzipping $basedir\musicjson.zip" $shell.Namespace("$basedir").CopyHere($shell.Namespace("$basedir\musicjson.zip").Items(), 16) echo "[+] npm install -d" cd ($basedir + "\" + @($shell.Namespace("$basedir\musicjson.zip").Items())[0].Name) npm install -d -q # Musicjson test / Todo Cakefile instead of UNIX makefile ? echo "[=] JSHint" node_modules/.bin/jshint bin lib echo "[=] Unit tests" node_modules/.bin/nodeunit tests
PowerShellCorpus/GithubGist/PeteGoo_f3efb6c32ac65d0a1710_raw_5daccb158f10e87ad512e2efb755214221167ab8_Clone-SvnToGit.ps1
PeteGoo_f3efb6c32ac65d0a1710_raw_5daccb158f10e87ad512e2efb755214221167ab8_Clone-SvnToGit.ps1
<# .SYNOPSIS Clones an SVN repository usng git-svn, mapping users using Active Directory. .DESCRIPTION This function is a wrapper around git-svn that tries to resolve the names and email addresses of all users in the commit history .Parameter SvnPath The full path to the SVN repository .Parameter CloneFolderName An optional name for the folder into which the code will be cloned .EXAMPLE Clone-SvnToGit svn://mysvnserver/Projects/myproject Clone the SVN repo at Projects/myproject to a folder named myproject. .EXAMPLE Clone-SvnToGit svn://mysvnserver/Projects/myproject -CloneFolderName foo Clone the SVN repo at Projects/myproject to a folder named foo. #> function Clone-SvnToGit { [CmdletBinding()] param( [Parameter(Mandatory=$True, ValueFromPipeline=$True)] $SvnPath, [string] $CloneFolderName ) Write-Verbose "Getting the list of authors" $allAuthors = ([xml](svn log $SvnPath --stop-on-copy --xml)).log.logentry.author | Select -Unique if($LASTEXITCODE -ne 0){ Write-Error "There was a problem getting history from SVN. Make sure the path given is an SVN repository $SvnPath" return; } $tempAuthorsFile = [System.IO.Path]::GetTempFileName() Write-Verbose "Creating authors.txt file at $tempAuthorsFile" $authorMap = @() foreach($username in $allAuthors){ $displayName = Get-ADUserDisplayName $username if(!($displayName)){ $displayName = $username $title = "Unknown User" $message = "We could not find the display name of the user $username. What do you want to do?" $default = New-Object System.Management.Automation.Host.ChoiceDescription "&Default", ` "Use their display name as their real name." $specify = New-Object System.Management.Automation.Host.ChoiceDescription "&Specify", ` "Specify the display name manually." $options = [System.Management.Automation.Host.ChoiceDescription[]]($default, $specify) $result = $host.ui.PromptForChoice($title, $message, $options, 0) switch ($result) { 0 { } 1 { $displayName = Read-Host 'Please write the users display name. e.g. John Doe' } } } $authorMap += "{0} = {1}<{0}@mydomain.com>" -f $username, $displayName } $authorMap | Set-Content $tempAuthorsFile Write-Verbose ("Temp authors file created with {0} mapped authors" -f $authorMap.Length) Write-Verbose "Starting clone of SVN codebase" $output = (git svn clone -A $tempAuthorsFile $SvnPath $CloneFolderName) *>> git-svn-clone.log.txt if($LASTEXITCODE -ne 0){ Write-Error "There was a problem with the git clone. Check the log at git-svn-clone.log.txt" Get-Content .\git-svn-clone.log.txt | where {$_ -ne ""} | Select -Last 1 | Write-Error } else{ Write-Verbose "Done!" } } function Get-ADUserDisplayName{ [CmdletBinding()] param( [Parameter(Mandatory=$True, ValueFromPipeline=$True)] $Username ) $strFilter = "(&(objectCategory=User)(sAMAccountName=$Username))" $objDomain = New-Object System.DirectoryServices.DirectoryEntry $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.SearchRoot = $objDomain $objSearcher.PageSize = 1000 $objSearcher.Filter = $strFilter $objSearcher.SearchScope = "Subtree" $colProplist = @("name") foreach ($i in $colPropList){$_ = $objSearcher.PropertiesToLoad.Add($i)} $colResults = $objSearcher.FindAll() $user = $colResults | Select -First 1 return $user.Properties.name }
PowerShellCorpus/GithubGist/rgsteele_f08f817d955440bb98c4_raw_e3b8cba4e362d4639c18357312207268fc313f71_Deploy-Application.ps1
rgsteele_f08f817d955440bb98c4_raw_e3b8cba4e362d4639c18357312207268fc313f71_Deploy-Application.ps1
<# .SYNOPSIS This script performs the installation or uninstallation of an application(s). .DESCRIPTION The script is provided as a template to perform an install or uninstall of an application(s). The script either performs an "Install" deployment type or an "Uninstall" deployment type. The install deployment type is broken down in to 3 main sections/phases: Pre-Install, Install, and Post-Install. The script dot-sources the AppDeployToolkitMain.ps1 script which contains the logic and functions required to install or uninstall an application. To access the help section, .EXAMPLE Deploy-Application.ps1 .EXAMPLE Deploy-Application.ps1 -DeploymentMode "Silent" .EXAMPLE Deploy-Application.ps1 -AllowRebootPassThru -AllowDefer .EXAMPLE Deploy-Application.ps1 -Uninstall .PARAMETER DeploymentType The type of deployment to perform. [Default is "Install"] .PARAMETER DeployMode Specifies whether the installation should be run in Interactive, Silent or NonInteractive mode. Interactive = Default mode Silent = No dialogs NonInteractive = Very silent, i.e. no blocking apps. Noninteractive mode is automatically set if an SCCM task sequence or session 0 is detected. .PARAMETER AllowRebootPassThru Allows the 3010 return code (requires restart) to be passed back to the parent process (e.g. SCCM) if detected from an installation. If 3010 is passed back to SCCM a reboot prompt will be triggered. .PARAMETER TerminalServerMode Changes to user install mode and back to user execute mode for installing/uninstalling applications on Remote Destkop Session Host/Citrix servers .NOTES .LINK Http://psappdeploytoolkit.codeplex.com "#> Param ( [ValidateSet("Install","Uninstall")] [string] $DeploymentType = "Install", [ValidateSet("Interactive","Silent","NonInteractive")] [string] $DeployMode = "Interactive", [switch] $AllowRebootPassThru = $false, [switch] $TerminalServerMode = $false ) #*=============================================== #* VARIABLE DECLARATION Try { #*=============================================== #*=============================================== # Variables: Application $appVendor = "Lenovo" $appName = "Battery Program" $appVersion = "2014" $appArch = "" $appLang = "EN" $appRevision = "01" $appScriptVersion = "1.0.0" $appScriptDate = "07/08/2014" $appScriptAuthor = "rgsteele" #*=============================================== # Variables: Script - Do not modify this section $deployAppScriptFriendlyName = "Deploy Application" $deployAppScriptVersion = [version]"3.1.3" $deployAppScriptDate = "05/22/2014" $deployAppScriptParameters = $psBoundParameters # Variables: Environment $scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Definition # Dot source the App Deploy Toolkit Functions ."$scriptDirectory\AppDeployToolkit\AppDeployToolkitMain.ps1" #*=============================================== #* END VARIABLE DECLARATION #*=============================================== #*=============================================== #* PRE-INSTALLATION If ($deploymentType -ne "uninstall") { $installPhase = "Pre-Installation" #*=============================================== # Test whether the site is reachable $HTTP_Request = [System.Net.WebRequest]::Create('https://lenovobattery2014.orderz.com') $HTTP_Request.Timeout = 10000 try { $HTTP_Response = $HTTP_Request.GetResponse() $HTTP_Response.Close() } catch [System.Net.WebException] { $HTTP_Response = $_.Exception.Response } $HTTP_Status = [int]$HTTP_Response.StatusCode If ($HTTP_Status -eq 200) { Write-Log "The site is reachable" } Else { Write-Log "The site is unreachable, error $HTTP_Status" Exit-Script -ExitCode "1" } $message = @" This is an important safety message from ***YOUR COMPANY NAME HERE***. The manufacturer of this laptop has initiated a recall of a specific batch of laptop batteries. Affected batteries may overheat, posing a fire hazard. To verify whether the battery in this laptop is affected, a program will be run on your computer. If replacement is not required, you will see a dialog box saying "Your battery is not affected" or a web page saying "Your battery is not eligible for replacement." If the battery requires replacement, a web page will open with a message saying "Your battery is eligible for replacement". Click "Continue" and fill out the form to request the replacement battery. Until the replacement battery arrives, you should shut down the laptop, remove the battery, and only use the laptop with the AC adapter connected. Please click OK to start the test. "@ Show-DialogBox -Text $message -Title "Lenovo Battery Recall 2014" -Icon "Exclamation" Show-InstallationProgress -Topmost $false #*=============================================== #* INSTALLATION $installPhase = "Installation" #*=============================================== # Perform installation tasks here Execute-Process -FilePath "LenovoBattery.exe" -Arguments "/silent" #*=============================================== #* POST-INSTALLATION $installPhase = "Post-Installation" #*=============================================== # Perform post-installation tasks here # Uninstall the program $dir = (${env:ProgramFiles(x86)}, ${env:ProgramFiles} -ne $null)[0] + "\Lenovo Battery Utility 2014\unins000.exe" Execute-Process -FilePath $dir -Arguments "/SILENT" # Display a message at the end of the install $message2 = @" The test has completed. If your laptop was supplied with a spare battery, you will need to run this test again with the other battery installed. Please contact the IT Service Desk for further assistance. If you have any questions or concerns, please contact the IT Service Desk. "@ Show-DialogBox -Text $message2 -Title "Lenovo Battery Recall 2014" -Icon "Information" #*=============================================== #* UNINSTALLATION } ElseIf ($deploymentType -eq "uninstall") { $installPhase = "Uninstallation" #*=============================================== # No uninstallation required #*=============================================== #* END SCRIPT BODY } } Catch { $exceptionMessage = "$($_.Exception.Message) `($($_.ScriptStackTrace)`)"; Write-Log "$exceptionMessage"; Show-DialogBox -Text $exceptionMessage -Icon "Stop"; Exit-Script -ExitCode 1 } # Catch any errors in this script Exit-Script -ExitCode 0 # Otherwise call the Exit-Script function to perform final cleanup operations #*===============================================
PowerShellCorpus/GithubGist/guitarrapc_1da7d92a160e085507ee_raw_c76de783f34762ff28d293c656a6ca00949637ef_ChefRecipeAndDSCConfiguration.ps1
guitarrapc_1da7d92a160e085507ee_raw_c76de783f34762ff28d293c656a6ca00949637ef_ChefRecipeAndDSCConfiguration.ps1
# Chef Recipe rule [cookbook] 'Nae' do [Key_name] "[key_value]" [value_name] "[value_value]" end # Chef DSC call EnvironemtResource with : https://github.com/opscode-cookbooks/dsc env 'editor' do key_name "EDITOR" value "vim" end # DSC Configuration Sample environment editor { Name = "EDITOR" Value = "vim" }
PowerShellCorpus/GithubGist/xcud_4683707_raw_1f4f58f066285cf7cc5a52cdb2027af437ca0bc6_Load-Assembly.ps1
xcud_4683707_raw_1f4f58f066285cf7cc5a52cdb2027af437ca0bc6_Load-Assembly.ps1
<# .Synopsis Pipeable shortcut for [reflection.assembly]::LoadFrom. .Example PS> dir c:\foo.dll | Load-Assembly GAC Version Location --- ------- -------- False v2.0.50727 C:\foo.dll #> function Load-Assembly { param( [Parameter(Mandatory=$True, Position=0, ValueFromPipeline=$true)] $Path); [reflection.assembly]::LoadFrom($Path) }
PowerShellCorpus/GithubGist/rkeithhill_46b9c22407d067af8534_raw_17427eb4cbab23a64c82ca13a2044488dd263f2f_Go.ps1
rkeithhill_46b9c22407d067af8534_raw_17427eb4cbab23a64c82ca13a2044488dd263f2f_Go.ps1
<# .SYNOPSIS The go function allows you to prepopulate a list of common destinations accessed by a short key. .DESCRIPTION The go function allows you to prepopulate a list of common destinations accessed by a short key such as 'h' for your home directory. .PARAMETER Key Specifies the short name for your destination. If you do not specify the key, the command will list the valid key/destination pairs. .PARAMETER Destination Specifies a path when using the -Add parameter to add a key/destination path pair. .PARAMETER Add Specifies the specified Key and Destination parameters should be added. The pairings are saved to $home\Documents\WindowsPowerShell\gopaths.xml so they are available in new PowerShell sessions. .PARAMETER Remove Specifies the specified Key and its corresponding destination should be removed. .PARAMETER List Lists the available key/destination pairs. .PARAMETER Loads Loads from the data file and lists the available key/destination pairs. This is useful if you add a key/destination pair in a different PowerShell session and you want to use it in this session without having to exit and reload PowerShell. .EXAMPLE C:\PS> go Lists available key/destination combinations. .EXAMPLE C:\PS> go -Key h -Dest $home -Add Adds h as a key for your home directory. .EXAMPLE C:\PS> go h Goes to the directory paired to h. .EXAMPLE C:\PS> go h -Remove Removes the key h and the corresponding destination. #> function go { [CmdletBinding(DefaultParameterSetName='Navigate')] param( [Parameter(Position = 0, ParameterSetName='Navigate')] [Parameter(Mandatory, Position = 0, ParameterSetName='Add')] [Parameter(Mandatory, Position = 0, ParameterSetName='Remove')] [ValidateNotNullOrEmpty()] [string] $Key, [Parameter(Mandatory, Position = 1, ParameterSetName='Add')] [ValidateNotNullOrEmpty()] [string] $Destination, [Parameter(ParameterSetName='Add')] [switch] $Add, [Parameter(ParameterSetName='Remove')] [switch] $Remove, [Parameter(ParameterSetName='List')] [switch] $List, [Parameter(ParameterSetName='Load')] [switch] $Load ) begin { Set-StrictMode -Version Latest $dataFile = Join-Path (Split-Path $profile.CurrentUserAllHosts -Parent) 'gopaths.xml' if (Test-Path $dataFile) { $ht = Import-Clixml $dataFile } else { $ht = @{} } function ShowValidKeywords { if ($ht.Count -gt 0) { "Valid keywords are:" $ht.Keys | Sort | Select @{n='Key';e={$_}},@{n='Destination';e={$ht.$_}} | Format-Table -AutoSize } else { "No key/destination pairs have defined. Use the -Add parameter to add key/destination pairs." } } } end { if ($PSCmdlet.ParameterSetName -eq 'Add') { if (!(Test-Path $Destination)) { throw "The path '$Destination' must exist" } $ht.$key = $Destination $ht | Export-Clixml $dataFile } elseif ($PSCmdlet.ParameterSetName -eq 'Remove') { if (!$ht.ContainsKey($Key)) { Write-Error "'$Key' is not a valid destination key" } $ht.Remove($Key) $ht | Export-Clixml $dataFile } elseif ($PSCmdlet.ParameterSetName -eq 'List') { ShowValidKeywords } elseif ($PSCmdlet.ParameterSetName -eq 'Load') { $ht | Export-Clixml $dataFile ShowValidKeywords } elseif ($PSCmdlet.ParameterSetName -eq 'Navigate') { if (!$Key) { ShowValidKeywords } elseif ($ht.ContainsKey($Key)) { cd $ht[$Key] } else { Write-Error "'$Key' is not a valid destination key" ShowValidKeywords } } } }
PowerShellCorpus/GithubGist/guitarrapc_e9ffaf2c584ddfa772da_raw_bcd39a82326f0337c75ae2e2a3df363ebf252597_NetstedOtherFileConfigurationBad.ps1
guitarrapc_e9ffaf2c584ddfa772da_raw_bcd39a82326f0337c75ae2e2a3df363ebf252597_NetstedOtherFileConfigurationBad.ps1
# read nested child configuration Get-ChildItem -Path ChildConfiguration -File | %{ .$_.FullName } # parent netsted configuraion Configuraion NetstedConfiguration { param ( [Parameter(Mandatory = 1, Position = 0)] [string]$Node, [Parameter(Mandatory = 1, Position = 1)] [pscredential]$Credential ) Node $Node { Service {} Remote { Credential = $Credential } } }
PowerShellCorpus/GithubGist/joshtransient_5984704_raw_9194efedbfa654ac37bca566300f97ee9dea8303_Discover-SPFarm.ps1
joshtransient_5984704_raw_9194efedbfa654ac37bca566300f97ee9dea8303_Discover-SPFarm.ps1
#REGION Functions # the following two functions were stolen from: # mspowershell.blogspot.com/2009/02/t-sql-query-with-object-based-result.html function ConnectSQL { Param ($server, $query, $database) $conn = new-object ('System.Data.SqlClient.SqlConnection') $conn.ConnectionString = "Server=$server;Integrated Security=SSPI;Database=$database" $conn.Open() $sqlCmd = New-Object System.Data.SqlClient.SqlCommand $sqlCmd.CommandText = $query $sqlCmd.Connection = $conn $Rset = $sqlCmd.ExecuteReader() ,$Rset ## The comma is used to create an outer array, which PS strips off automatically when returning the $Rset } function QuerySQL { Param ($server, $query, $database = "master") $data = ConnectSQL $server $query $database while ($data.read() -eq $true) { $max = $data.FieldCount -1 $obj = New-Object Object for($i=0;$i -le $max;$i++) { $name = $data.GetName($i) $obj | Add-Member Noteproperty $name -value $data.GetValue($i) } $obj } } # This guy returns the word "No" if a SQL Server is not an alias, and the target's name if it is an alias function CheckSQLAlias($name) { $alias = "No" $cs = get-item HKLM:\Software\Microsoft\MSSQLServer\Client\ConnectTo foreach($prop in $cs.Property) { if($prop -eq $name) { $alias = $cs.GetValue($prop) } } $alias } function GetSubWebInfo($web) { # For the template attribute, this will write something like 'STS#0'--SPSite.GetWebTemplates() # has a property simply called .Template, which matches up to this value. $t = [string]::Format("{0}#{1}",$web.webTemplate,$web.Configuration) $t = [string]::Format("{0} ({1})",$t,$webTemps[$t].Title) # We calculate size by getting the sum of both SMI(List) and SMI(DocumentLibrary) # and do it for each subweb GUID (and convert to MBytes while we're at it)... $g = [string]::Format("{{{0}}}",$web.ID) $s = $smiLists |? { $_.WebGuid -eq $g } | measure Size -Sum | select -ExpandProperty sum $s += $smiDLibs |? { $_.WebGuid -eq $g } | measure Size -Sum | select -ExpandProperty sum $s = [Math]::Round($s/1048576,2) # ...and document count by getting the sum of items in SMI(DocumentLibrary) $d = $smiDLibs |? { $_.WebGuid -eq $g } | measure ItemCount -Sum | select -ExpandProperty sum # Theme has a bad problem of being empty quite often if($web.Theme -eq '') { $th = 'Default' } else { $th = $web.Theme } # Prep the data row and populate it $webHash = @{ SRU = $web.ServerRelativeURL Title = $web.Title Template = $t Size = $s Docs = $d MasterPage = $web.MasterURL Theme = $th Created = $web.Created LastModified = $web.LastItemModifiedDate GUID = $web.ID } # We're checking for associated owner group here. If it's only attached to a single web, we can # search the XML later and walk back up the tree to get its first ancestor with <uniqueOwners>. if($web.HasUniqueRoleAssignments) { $og = $web.associatedownergroup $uo = @{ Name = $og.name; Users = @() } foreach($user in $og.users) { # Let's expand out AD groups if we run into any of those... if($user.IsDomainGroup) { $ur = @{ Name = $user.name; Account = $user.loginname; SCAdmin = $user.issiteadmin; ADUsers = @() } # A bit of laziness here, using the default domain for querying AD. Script has not been tested # out on trusted domains or anything like that, so hopefully you only have one domain. $grp = ([adsiSearcher]"objectSid=$($user.sid)").FindOne() foreach($dn in $grp.Properties['member']) { $m = [adsi]"LDAP://$($dn)" $ad = @{ Name = $m.name.ToString(); Email = $m.mail.ToString(); Account = $m.sAMAccountName.ToString() } $ur['ADUsers'] += $ad } } else { # Write out a regular user if it's not an AD group $ur = @{ Name = $user.name; Email = $user.email; Account = $user.loginname; SCAdmin = $user.issiteadmin } } $uo['Users'] += $ur } $webHash.Add('UniqueOwners',$uo) } # Recurse! if($web.Webs.count -gt 0) { $webHash.Add('Webs',@()) foreach($w in $web.Webs) { $webHash['Webs'] += GetSubWebInfo($w) } } # Cleanup time... $web.dispose() return $webHash } function GetSCInfo($site) { # Run a recalc() prior since it obviously doesn't happen when it needs to $site.RecalculateStorageUsed() $used = [Math]::Round($site.usage.storage/1024/1024,2) $warn = $site.quota.storagewarninglevel/1024/1024 $max = $site.quota.storagemaximumlevel/1024/1024 # Prep the data row and populate it $scr = @{ URL = $site.url; StorageUsed = $used; StorageWarn = $warn; StorageMax = $max } # Pre-load available web templates...this helps generate display names for each # web's template ID $webTemps = $site.GetWebTemplates(1033) # SMI has been deemed an "expensive" way to get proper storage information, but # iterating through each web, folder, list item, attachment is much, much slower # and usually rounds out to being just as (if not more so) expensive. Setting the # upper limit to 1M rows returned is probably aiming way too high, but better # safe than sorry $smiLists = $site.StorageManagementInformation('List','Decreasing','Size',1000000) $smiDLibs = $site.StorageManagementInformation('DocumentLibrary','Decreasing','Size',1000000) $sws = GetSubWebInfo($site.rootWeb) $scr.Add('RootWeb',$sws) return $scr } function GetCDBData($cdb) { # How lame is this: since MS.SP.Admin.SPContentDatabase wasn't written correctly, we have to call its functions # in a very stupid manner, first by retrieving the methods, then calling .Invoke or .GetValue $getName = [microsoft.sharepoint.administration.spcontentdatabase].getmethod("get_Name"); $cdbName = $getName.Invoke($cdb,"instance,public",$null,$null,$null); $getSize = [microsoft.sharepoint.administration.spcontentdatabase].getmethod("get_DiskSizeRequired"); $cdbSize = $getSize.Invoke($cdb,"instance,public",$null,$null,$null)/1024/1024; $getSrvr = [microsoft.sharepoint.administration.spcontentdatabase].getproperty("ServiceInstance"); $cdbSrvr = $getSrvr.GetValue($cdb,$null).NormalizedDataSource # Prep the data row and populate it $cr = @{ Name = $cdbName; Sites = @(); SizeOnDisk = $cdbSize } # Identify SQL aliases $csAlias = (CheckSQLAlias($cdbSrvr)).split(',')[1] if(!$csAlias) { $cr.Add('Server',$cdbSrvr) $cr.Add('Alias','No') } else { $cr.Add('Server',$csAlias) $cr.Add('Alias',$cdbSrvr) } return $cr } function WriteXML($data) { $x = $data | ConvertTo-Xml -NoTypeInformation $x.Save('.\raw.xml') $tr = New-Object system.Xml.XmlTextReader('.\raw.xml') $tw = New-Object system.Xml.XmlTextWriter('.\out.xml',$null) $tw.WriteStartDocument() $tw.WriteProcessingInstruction('xml-stylesheet','type="text/xsl" href="out.xsl"') # Our document will resemble something like this: ############ # <Objects> # <Object> # <!-- Scenario 1: regular key/value --> # <Property Name="Key">[Key]</Property> # <Property Name="Value">[Value]</Property> # <!-- Scenario 2: blank value --> # <Property Name="Key">[Key]</Property> # <Property Name="Value" /> # <!-- Scenario 3: scalar array value --> # <Property Name="Key">[Key]</Property> # <Property Name="Value"> # <Property>[Value 1]</Property> # <Property>[Value 2]</Property> # ... # </Property> # <!-- Scenario 4: nested hashtable --> # <Property Name="Key">[Key]</Property> # <Property Name="Value"> # <Property> # <Property Name="Key">[Key]</Property> # <Property Name="Value">[Value]</Property> # ... # </Property> # </Property> # </Object> # </Objects> ############ # In the root scenario, <Objects/> is the collection of web applications, and each <Object/> is # a separate web application. Because we're importing from a hashtable, sibling Keys and Values # correspond to a variable, so the goal is to read them sequentially and output something like # <[KeyName]>[Value]</[KeyName]>. However, since this is a very deeply nested hashtable (plus # scalar arrays), it's not exactly that simple, hence the four extra scenarios. ############ while($tr.Read()) { switch($tr.NodeType) { Element { switch($tr.Name) { Objects { $tw.WriteStartElement('WebApps'); break } Object { $tw.WriteStartElement('WebApp'); break } Property { # Poll for attributes weeds out scenario 3/scalar array if($tr.HasAttributes) { # Keys are easy to deal with if($tr.GetAttribute('Name') -eq 'Key') { [void]$tr.Read() # Skip to the value $tw.WriteStartElement($tr.Value) # Start a new element based on the value [void]$tr.Read() # Skip the closing element } else { # Either <Property Name="Value"> or <Property> # Handle scenario 2 with a self-closing tag check, otherwise the next read will skip it if($tr.IsEmptyElement) { $tw.WriteEndElement() } [void]$tr.Read() # Skip the opening # Handle scenario 1, which is regular text if($tr.HasValue) { $tw.WriteValue($tr.Value) } # Handle scenarios 3+4, start a new <Item> if current node isn't text or an EndElement elseif($tr.NodeType -ne 'EndElement') { $tw.WriteStartElement('Item') } # Lack of a regular "else" here also handles scenarios 3+4 by letting a leftover EndElement be # caught by the outside switch() } # Handle scenario 3 by creating a plain <Item> node } else { $tw.WriteStartElement('Item') } } } break; } # Handle scenario 1 (regular text value) Text { $tw.WriteValue($tr.Value); break } # Handle scenario 2 (blank value) EndElement { $tw.WriteEndElement(); break } } } $tr.Close() $tw.Flush() $tw.Close() } #ENDREGION #REGION Main Program [datetime]::Now Write-Progress -id 1 -a "Starting..." -st "Initializing libraries and variables..." -pe 0 # Init scalar array for info storage $waData = @() # Load all SharePoint stuff...libs, content service, non-admin web apps [void][reflection.assembly]::loadwithpartialname("Microsoft.SharePoint") $cSvc = [microsoft.sharepoint.administration.spwebservice]::ContentService $was = $csvc.WebApplications | where { $_.IsAdministrationWebApplication -eq $false } # Prep for first progress indicator $wc = 100/$was.count; $cw = 0 # Start web application loop foreach ($wa in $was) { $wn = $wa.name $waHash = @{ Name = $wn; AltURLs = @(); CDBs = @() } # Update progress and prep for second progress indicator Write-Progress -Id 1 -a "Processing web applications..." -st "Currently on $($wn)" -pe ($cw * $wc) $sc = 100/$wa.sites.count; $cs = 0 # That stupid trick again $getSites = [microsoft.sharepoint.administration.spcontentdatabase].getproperty("Sites"); # Start content database loop foreach($cdb in $wa.ContentDatabases) { $cdbHash = GetCDBData($cdb) $cdbSites = $getSites.GetValue($cdb,$null) foreach ($site in $cdbSites) { Write-Progress -Id 2 -a "Processing site collections..." -st "Getting data about $($site.URL)" -pe ($cs * $sc) $scHash = GetSCInfo($site) $cdbHash['Sites'] += $scHash # Cleanup and iterate site collection count $site.dispose() $cs++ } $waHash['CDBs'] += $cdbHash } # Add in alternate URLs foreach($au in $wa.AlternateUrls) { $waHash['altURLs'] += [string]::Format("{0} ({1})",$au.Uri,$au.UrlZone) } # Add the hashtable row to our big set of data $waData += $waHash # Iterate web application count $cw++ } WriteXML($waData) [datetime]::Now #ENDREGION
PowerShellCorpus/GithubGist/tkinz27_8a0b49f3c8b0ea4575c6_raw_0553a03b6d6ee2cb45ebb3a86b6dcf3b4333ecca_file.ps1
tkinz27_8a0b49f3c8b0ea4575c6_raw_0553a03b6d6ee2cb45ebb3a86b6dcf3b4333ecca_file.ps1
#!powershell # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # WANT_JSON # POWERSHELL_COMMON $params = Parse-Args $args; function Set-Permissions { Param ( [string]$path, [string]$mode = "0644", [string]$user = "sgadmin", [string]$group ) $changed = $false $permissions = [convert]::ToInt32($mode, 8) $permBits = @() $permBits += ( $permissions -band 0x07 ) $permBits += ( ( $permissions -shr 3 ) -band 0x07 ) $permBits += ( ( $permissions -shr 6 ) -band 0x07 ) $perms = @() foreach ( $permBit in $permBits ) { $perm = @() if ($permBit -band 0x04) { $perm += "Read" } if ($permBit -band 0x02) { $perm += "Write" } if ($permBit -band 0x01) { $perm += "Execute" } $perms += , $perm } Write-Verbose "Setting the Permissions to $( $perms -join ', ' )" # Setting up the ACL object $rights = [System.Security.AccessControl.FileSystemRights]$perms $inherit = [System.Security.AccessControl.InheritanceFlags]::None $propogate = [System.Security.AccessControl.PropogationFlags]::None $objType = [System.Security.AccessControl.AccessControlType]::Allow $objUser = New-Object System.Security.Principal.NTAccount( $user ) $objACE = New-Object System.Security.AccessControl.FileSystemAccessRule ` ($objUser, $rights, $inherit, $propogate, $objType ) $origAcl = Get-Acl -path $path $origACL.RemoveAccessRuleAll($objACE) Set-Acl $path $objAcl -ErrorVariable $work $work #foreach ( $access in $origAcl.access ) #{ # foreach ( $idRef in $access.IdentityReference.Value ) # { # $defaults = @( "NT Authority\System", "BUILTIN\sgadmin" ) # if ( $defaults -notcontains $idRef ) # { # if ( $idRef -eq $user ) # { # $origAcl.RemoveAccessRule( $access ) | Out-Null # } # } #} ## Applying the removal of the old #Set-Acl -path $path -aclObject $origAcl } # path $path = Get-Attr $params "path" $FALSE; If ($path -eq $FALSE) { $path = Get-Attr $params "dest" $FALSE; If ($path -eq $FALSE) { $path = Get-Attr $params "name" $FALSE; If ($path -eq $FALSE) { Fail-Json (New-Object psobject) "missing required argument: path"; } } } # state - file, link, directory, hard, touch, absent $state = Get-Attr $params "state" "file"; $src = Get-Attr $params "src"; # recurse - yes, no $recurse = Get-Attr $params "recurse" "no"; # force - yes, no $force = Get-Attr $params "force" "no"; # group $group = Get-Attr $params "group"; # acl $acl = Get-Attr $params "acl"; # owner $owner = Get-Attr $params "owner"; # mode $mode = Get-Attr $params "mode"; # result $result = New-Object psobject @{ changed = $FALSE mode = $mode owner = $owner group = $group acl = $acl }; If ( $state -eq "touch" ) { If(Test-Path $path) { (Get-ChildItem $path).LastWriteTime = Get-Date } Else { echo $null > $file } $result.changed = $TRUE; } If (Test-Path $path) { If ( $state -eq "absent" ) { Remove-Item $path -Force; $result.changed = $TRUE; } Else { # Translate perms to windows $info = Get-Item $path; # Only files have the .Directory attribute. If ( $state -eq "directory" -and $info.Directory ) { Fail-Json (New-Object psobject) "path is not a directory"; } #else #{ # $result.acl = Set-Permissions $path $mode $env:computername + "\" + $user #} # Only files have the .Directory attribute. If ( $state -eq "file" -and -not $info.Directory ) { Fail-Json (New-Object psobject) "path is not a file"; } #else #{ # $result.acl = Set-Permissions $path $mode $env:computername + "\" + $user #} } } Else { If ( $state -eq "directory" ) { New-Item -ItemType directory -Path $path } If ( $state -eq "file" ) { Fail-Json (New-Object psobject) "path will not be created"; } } Exit-Json $result;
PowerShellCorpus/GithubGist/proquibas_4634427_raw_147daf48beeb3defa2df875bd4d90435c243af58_AD_power.ps1
proquibas_4634427_raw_147daf48beeb3defa2df875bd4d90435c243af58_AD_power.ps1
############################################################################# # PowerShell para extraer información de Active Directory. # # Se crea directorio C:\FSO y los outputs se guardan en outcommand.txt # # Informacion que extrae: # # >Numero total de usuarios # # >Numero total de maquinas # # >Numero total de servidores # # >Numero total de administradores del dominio # # >Lista de GPO's activas en el Dominio # ############################################################################# import-module ActiveDirectory #Se importa el modulo de Active Directory #Se comprueba si existe carpeta temporal donde guardar el output. De lo contrario, se crea. if (!(Test-Path -path C:\FSO)) { Write-host "------ Creando directorio temporal en C:\FSO ------" New-Item -ItemType directory -Path C:\FSO } else { Write-Host "------ El dicrectorio C:\FSO ya Existe ------" Write-Host "------ Comprobando contenido" if ((Test-Path c:\FSO\outcommand.txt) -eq $true) { Remove-Item c:\FSO\*.txt Write-Host ">>>>> Fichero temporal eliminado" } } write-host "" "************ Escribiendo informacion de usuatios" >> c:\FSO\outcommand.txt $total_users = Get-ADUser -Filter * -SearchBase "DC=dominio,DC=com" | measure | ForEach-Object {$_.Count} #numero total de usuarios $total_computers = Get-ADComputer -Filter * -SearchBase "DC=dominio,DC=com" | measure | ForEach-Object {$_.Count} #numero total de maquinas $total_servers = Get-ADComputer -Filter {operatingsystem -like "*server*"} | measure | ForEach-Object {$_.Count} #numero total de servidores $total_admin = Get-ADGroupMember -Identity "Admins. del dominio" | measure | ForEach-Object {$_.Count} #numero total de administradores del dominio "Usuarios totales en AD : " + $total_users >> c:\FSO\outcommand.txt "Computers totales en AD : " + $total_computers >> c:\FSO\outcommand.txt "Servers totales en AD : " + $total_servers >> c:\FSO\outcommand.txt "Admins. del Dominio en AD : " + $total_admin >> c:\FSO\outcommand.txt " " >> c:\FSO\outcommand.txt " " >> c:\FSO\outcommand.txt #'Lista de GPOs $domain = "dominio" #Dominio del que extraer las políticas "Listando politicas de " + $domain >> c:\FSO\outcommand.txt $gpm=New-Object -ComObject gpmgmt.gpm $constants = $gpm.GetConstants() $gpmDomain = $gpm.GetDomain($domain,$null,$constants.useanydc) $gpmSearchCriteria = $gpm.CreateSearchCriteria() $gpo=$gpmdomain.SearchGPOs($gpmSearchCriteria) if($verbose) { write-host $gpo } ELSE { foreach($ogpo in $gpo) { $hash += @{ $ogpo.ID = $ogpo.DisplayName } >> c:\FSO\outcommand.txt } format-table -inputobject $hash -autosize >> c:\FSO\outcommand.txt } exit write-host ">>>>>> Finalizado"
PowerShellCorpus/GithubGist/sneal_7808621_raw_971e5b9263dd4b59ebe2b2a15a51841eca1faecb_gistfile1.ps1
sneal_7808621_raw_971e5b9263dd4b59ebe2b2a15a51841eca1faecb_gistfile1.ps1
$is_64bit = [IntPtr]::size -eq 8 # setup openssh $ssh_download_url = "http://www.mls-software.com/files/setupssh-6.3p1-1.exe" if ($is_64bit) { Write-Host "64 bit OS found" $ssh_download_url = "http://www.mls-software.com/files/setupssh-6.3p1-1(x64).exe" } If (!(Test-Path "C:\Program Files\OpenSSH\bin\ssh.exe")) { Write-Host "Downloading $ssh_download_url" (New-Object System.Net.WebClient).DownloadFile($ssh_download_url, "C:\Windows\Temp\openssh.exe") C:\Windows\temp\openssh.exe /S /port=22 /privsep=1 /password=D@rj33l1ng } # Let the installer finish before modifying its files #Write-Host "Waiting 5s for OpenSSH install to finish" #Start-Sleep -s 5 # ensure vagrant can log in Write-Host "Setting vagrant user file permissions" New-Item -ItemType Directory -Force -Path "C:\Users\vagrant\.ssh" C:\Windows\System32\icacls.exe "C:\Users\vagrant" /grant "vagrant:(OI)(CI)F" C:\Windows\System32\icacls.exe "C:\Program Files\OpenSSH\bin" /grant "vagrant:(OI)RX" C:\Windows\System32\icacls.exe "C:\Program Files\OpenSSH\usr\sbin" /grant "vagrant:(OI)RX" Write-Host "Setting SSH home directories" (Get-Content "C:\Program Files\OpenSSH\etc\passwd") | Foreach-Object { $_ -replace '/home/(\w+)', '/cygdrive/c/Users/$1' } | Set-Content 'C:\Program Files\OpenSSH\etc\passwd' # fix opensshd to not be strict Write-Host "Setting OpenSSH to be non-strict" $sshd_config = Get-Content "C:\Program Files\OpenSSH\etc\sshd_config" $sshd_config = $sshd_config -replace 'StrictModes yes', 'StrictModes no' $sshd_config = $sshd_config -replace '#PubkeyAuthentication yes', 'PubkeyAuthentication yes' $sshd_config = $sshd_config -replace '#PermitUserEnvironment no', 'PermitUserEnvironment yes' Set-Content "C:\Program Files\OpenSSH\etc\sshd_config" $sshd_config # use c:\Windows\Temp as /tmp location Write-Host "Setting temp directory location" Remove-Item -Recurse -Force -ErrorAction SilentlyContinue "C:\Program Files\OpenSSH\tmp" C:\Program` Files\OpenSSH\bin\junction.exe /accepteula "C:\Program Files\OpenSSH\tmp" "C:\Windows\Temp" C:\Windows\System32\icacls.exe "C:\Windows\Temp" /grant "vagrant:(OI)(CI)F" # add 64 bit environment variables missing from SSH Write-Host "Setting SSH environment" $sshenv = "TEMP=C:\Windows\Temp" if ($is_64bit) { $env_vars = "ProgramFiles(x86)=C:\Program Files (x86)", ` "ProgramW6432=C:\Program Files", ` "CommonProgramFiles(x86)=C:\program files (x86)\Common Files", ` "CommonProgramW6432=C:\program files\Common Files" $sshenv = $sshenv + "`r`n" + ($env_vars -join "`r`n") } Set-Content C:\Users\vagrant\.ssh\environment $sshenv # record the path for use by provisioners Write-Host "Recording PATH for provisioners" $env:PATH > c:\windows\temp\PATH # configure firewall Write-Host "Configuring firewall" netsh advfirewall firewall add rule name="SSHD" dir=in action=allow service=OpenSSHd enable=yes netsh advfirewall firewall add rule name="SSHD" dir=in action=allow program="C:\Program Files\OpenSSH\usr\sbin\sshd.exe" enable=yes netsh advfirewall firewall add rule name="ssh" dir=in action=allow protocol=TCP localport=22
PowerShellCorpus/GithubGist/Elindalyne_1790669_raw_0a874461c6791fb17663a0ef84adbe0eb23812d8_Bootstrap-EC2-Windows-CloudInit.ps1
Elindalyne_1790669_raw_0a874461c6791fb17663a0ef84adbe0eb23812d8_Bootstrap-EC2-Windows-CloudInit.ps1
# Windows AMIs don't have WinRM enabled by default -- this script will enable WinRM # AND install the CloudInit.NET service, 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 R2 Core x64 and Windows 2008 SP2 x86 AMIs provided # by Amazon # # To run the script, open up a PowerShell prompt as admin # PS> Set-ExecutionPolicy Unrestricted # PS> icm $executioncontext.InvokeCommand.NewScriptBlock((New-Object Net.WebClient).DownloadString('https://raw.github.com/gist/1672426/Bootstrap-EC2-Windows-CloudInit.ps1')) # Alternatively pass the new admin password and encryption password in the argument list (in that order) # PS> icm $executioncontext.InvokeCommand.NewScriptBlock((New-Object Net.WebClient).DownloadString('https://raw.github.com/gist/1672426/Bootstrap-EC2-Windows-CloudInit.ps1')) -ArgumentList "adminPassword cloudIntEncryptionPassword" # The script will prompt for a a new admin password and CloudInit password to use for encryption param( [Parameter(Mandatory=$true)] [string] $AdminPassword, [Parameter(Mandatory=$true)] [string] $CloudInitEncryptionPassword ) 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))) } while (($CloudInitEncryptionPassword -eq $null) -or ($CloudInitEncryptionPassword -eq '')) { $CloudInitEncryptionPassword= [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host "Enter a non-null / non-empty password to use for encrypting CloudInit.NET scripts" -AsSecureString))) } Import-Module BitsTransfer $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]" cd $Env:USERPROFILE #change admin password net user Administrator $AdminPassword Add-Content $log -value "Changed Administrator password" #.net 4 if ((Test-Path "${Env:windir}\Microsoft.NET\Framework\v4.0.30319") -eq $false) { if($IsCore) { $netUrl = 'http://download.microsoft.com/download/3/6/1/361DAE4E-E5B9-4824-B47F-6421A6C59227/dotNetFx40_Full_x86_x64_SC.exe' } else { $netUrl = 'http://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe' } Start-BitsTransfer $netUrl dotNetFx40_Full_x86_x64.exe Start-Process -FilePath "dotNetFx40_Full_x86_x64.exe" -ArgumentList '/norestart /q /ChainingPackage ADMINDEPLOYMENT' -Wait -NoNewWindow del dotNetFx40_Full_x86_x64.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" } #winrm if ($Is32Bit) { #this really only applies to oses older than 2008 SP2 or 2008 R2 or Win7 #this uri is Windows 2008 x86 - powershell 2.0 and winrm 2.0 #Start-BitsTransfer 'http://www.microsoft.com/downloads/info.aspx?na=41&srcfamilyid=863e7d01-fb1b-4d3e-b07d-766a0a2def0b&srcdisplaylang=en&u=http%3a%2f%2fdownload.microsoft.com%2fdownload%2fF%2f9%2fE%2fF9EF6ACB-2BA8-4845-9C10-85FC4A69B207%2fWindows6.0-KB968930-x86.msu' Windows6.0-KB968930-x86.msu #Start-Process -FilePath "wusa.exe" -ArgumentList 'Windows6.0-KB968930-x86.msu /norestart /quiet' -Wait #Add-Content $log -value "" } #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' } Start-BitsTransfer $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 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' } Start-BitsTransfer $vcredist 'vcredist.exe' Start-Process -FilePath 'vcredist.exe' -ArgumentList '/norestart /q' -Wait del vcredist.exe Add-Content $log -value "Installed VC++ Redistributable from $vcredist and updated path" #curl $curlUri = if ($Is32Bit) { 'http://www.gknw.net/mirror/curl/win32/curl-7.23.1-ssl-sspi-zlib-static-bin-w32.zip' } ` else { 'http://curl.haxx.se/download/curl-7.23.1-win64-ssl-sspi.zip' } Start-BitsTransfer $curlUri curl.zip &7z e curl.zip `-o`"c:\program files\curl`" 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" #cloudinit.net curl http://cloudinitnet.codeplex.com/releases/80468/download/335000 `-L `-d `'`' `-o cloudinit.zip &7z e cloudinit.zip `-o`"c:\program files\CloudInit.NET`" del cloudinit.zip Add-Content $log -value 'Downloaded / extracted CloudInit.NET' $configFile = 'c:\program files\cloudinit.net\install-service.ps1' (Get-Content $configFile) | % { $_ -replace "3e3e2d3848336b7d3b547b2b55",$CloudInitEncryptionPassword } | Set-Content $configFile cd 'c:\program files\cloudinit.net' . .\install.ps1 Start-Service CloudInit Add-Content $log -value "Updated config file with CloudInit encryption password and ran installation scrpit" #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 { $tempDir = Join-Path $env:TEMP "chocInstall" if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)} $file = Join-Path $tempDir "chocolatey.zip" (new-object System.Net.WebClient).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' [Environment]::SetEnvironmentVariable('ChocolateyInstall', 'c:\nuget', [System.EnvironmentVariableTarget]::User) if ($($env:Path).ToLower().Contains('c:\nuget\bin') -eq $false) { $env:Path = [Environment]::GetEnvironmentVariable('Path', [System.EnvironmentVariableTarget]::Machine); } Import-Module -Name 'c:\nuget\chocolateyInstall\helpers\chocolateyinstaller.psm1' & C:\NuGet\chocolateyInstall\chocolatey.ps1 update Add-Content $log -value 'Updated chocolatey to the latest version' } Add-Content $log -value "Installed Chocolatey" #this script will be fired off after the reboot #http://www.codeproject.com/Articles/223002/Reboot-and-Resume-PowerShell-Script @' $log = 'c:\Bootstrap.txt' $systemPath = [Environment]::GetFolderPath([Environment+SpecialFolder]::System) Remove-ItemProperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run -name 'Restart-And-Resume' &winrm quickconfig `-q Add-Content $log -value "Ran quickconfig for winrm" #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 15 seconds for CloudInit Service to start / fail Start-Sleep -m 15000 #clear event log and any cloudinit logs wevtutil el | % {Write-Host "Clearing $_"; wevtutil cl "$_"} del 'c:\cloudinit.log' -ErrorAction SilentlyContinue del 'c:\afterRebootScript.ps1' -ErrorAction SilentlyContinue '@ | Set-Content 'c:\afterRebootScript.ps1' Set-ItemProperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run -name 'Restart-And-Resume' ` -value "$(Join-Path $env:windir 'system32\WindowsPowerShell\v1.0\powershell.exe') c:\afterRebootScript.ps1" Write-Host "Press any key to reboot and finish image configuration" [void]$host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') Restart-Computer
PowerShellCorpus/GithubGist/fstanley_5621593_raw_4dbebc12eec4db7c3e3bb15118ebccd41bfca87b_nb_makefileBuilder.ps1
fstanley_5621593_raw_4dbebc12eec4db7c3e3bb15118ebccd41bfca87b_nb_makefileBuilder.ps1
# Author: Forrest Stanley <fstanley@netburner.com> # # This script generates a makefile in the current folder. It automatically adds # required cpp files and html files/folder. # # Usage nb_makefileBuilder # -Platform [PLATFORM] - optional. Adds Platform = PLATFORM to makefile # # param( [Parameter( Mandatory = $false, Position = 0)] [string]$Platform ) $dateYear = Get-Date -Format yyyy $copyrightText = @" # Copyright 1998-$dateYear NetBurner, Inc. ALL RIGHTS RESERVED # Permission is hereby granted to purchasers of NetBurner Hardware # to use or modify this computer program for any use as long as the # resultant program is only executed on NetBurner provided hardware. # # No other rights to use this program or it's derivitives in part or # in whole are granted. # # It may be possible to license this or other NetBurner software for # use on non NetBurner Hardware. Please contact Licensing@Netburner.com # for more information. # # NetBurner makes no representation or warranties with respect to the # performance of this computer program, and specifically disclaims any # responsibility for any damages, special or consequential, connected # with the use of this program. # # NetBurner, Inc # http://www.netburner.com "@ # Adding Copyright Text $makefile = $copyrightText # Setting the Name of your makefile to be the directory name you are in $path = (Get-Location).Path $myIndex = $path.LastIndexOf("\") + 1 $AppName = $path.Substring($myIndex) $makefile += "NAME = $AppName`r`n" if ($Platform -ne "") { $makefile += "PLATFORM = $Platform`r`n" } $makefile += "`r`n" # Adding c++ source files dir *.cpp -recurse | ForEach-Object -begin { $makefile += "CXXSRCS = \`r`n" } ` -process { ` if (($_).Name -ne "htmldata.cpp") { ` $makefile += "`t" + ($_).Name + " \`r`n" ` } ` } ` -end { $makefile += "`r`n" } # Adding C Source files dir *.c -recurse | ForEach-Object -begin { $makefile += "CSRCS = \`r`n" } ` -process { $makefile += "`t" + ($_).Name + " \`r`n" } ` -end { $makefile += "`r`n" } # Adding htmldata.cpp to the build list if an html directory exists if (Test-Path html) { $makefile += @" CXXSRCS += htmldata.cpp CREATEDTARGS = htmldata.cpp "@ } # Adding includes to the nburn make system $makefile += "include `$(NBROOTMINGW)/make/main.mak`r`n`r`n" # Add special rule to build html, if we find an html folder if (Test-Path html) { $makefile += @" htmldata.cpp : `$(wildcard html/*.*) comphtml html -ohtmldata.cpp "@ } $makefile += "`r`n`r`n" # Output the generated makefile to the local directory as makefile $makefile | Out-File -Encoding ascii -FilePath makefile
PowerShellCorpus/GithubGist/rysstad_9972336_raw_a28faf686c84f510d27f0061c1597dfff2c91ee8_Generate-RandomPassword.ps1
rysstad_9972336_raw_a28faf686c84f510d27f0061c1597dfff2c91ee8_Generate-RandomPassword.ps1
################################################################################ # PowershellGenerateRandomPassword # # Description: Generate random password consisting of only upper and lower case letters and numbers. # Adding non-letter characters would increase the password complexity, but would add # potential problems related to SQL server, ODBC etc. # # Author name: Tor Arne Rysstad # Created date: 2013.10.29 # Version: 0.02 # # Based on code snipped from: # http://blogs.technet.com/b/heyscriptingguy/archive/2013/06/03/generating-a-new-password-with-windows-powershell.aspx # ---- All hail to the Scripting Guy!!!!!! --- # ################################################################################ Function Generate-Password { <# .SYNOPSIS Generate random password. .DESCRIPTION Generate random password consisting of only upper and lower case letters and numbers. Number of characters is set using the length parameter. .EXAMPLE Generate-Password .EXAMPLE Generate-Password -length 10 .PARAMETER length The length of the password. The default 19 characters should work well with most MS systems. #> [CmdletBinding()] Param( [int]$Length=19 ) Write-Verbose "Running function Generate-Password" $alphabet=$NULL; # Upper case letters A-Z For ($a=65;$a –le 90;$a++) { $alphabet+=,[char][byte]$a } # Lower case letters a-z For ($a=97;$a –le 122;$a++) { $alphabet+=,[char][byte]$a } # Numbers 0-9 For ($a=48;$a –le 57;$a++) { $alphabet+=,[char][byte]$a } For ($loop=1; $loop –le $length; $loop++) { $TempPassword+=($alphabet | Get-Random) } Write-Verbose "Function Generate-Password completed" return $TempPassword } # end of Function Generate-Password
PowerShellCorpus/GithubGist/ziembor_6911450_raw_1f7caa4aaaa5f541de97cacc0bd596931d51f8b4_Remove-DirtyCharacters.ps1
ziembor_6911450_raw_1f7caa4aaaa5f541de97cacc0bd596931d51f8b4_Remove-DirtyCharacters.ps1
$SystemWebAssembly = [System.Reflection.Assembly]::LoadWithPartialName("System.Web") $SystemGlobalizationAssembly = [System.Reflection.Assembly]::LoadWithPartialName("System.Globalization") $SystemTextAssembly = [System.Reflection.Assembly]::LoadWithPartialName("System.Text") function Convert-TitleToSlug([String] $Title) { $CleanTitle = Remove-IllegalCharacters $Title $HyphenatedTitle = Replace-SpacesWithHyphen $CleanTitle $StringWithLessDiacritics = Remove-DiacriticsFromLatinCharacters $HyphenatedTitle $StringWithEvenLessDiacritics = Remove-DiacriticsViaCodepageConversion $StringWithLessDiacritics $URLEncodedString = Encode-URL $StringWithEvenLessDiacritics $ResultString = Remove-IllegalCharacters $URLEncodedString return $ResultString } function Remove-IllegalCharacters([String] $DirtyString) { if ([String]::IsNullOrEmpty($DirtyString)) { return $DirtyString } Write-Debug $DirtyString $CleanerString = $DirtyString -replace '[^\w -]', [String]::Empty Write-Debug $CleanerString return $CleanerString } function Replace-SpacesWithHyphen([string] $CleanString) { if ([String]::IsNullOrEmpty($CleanString)) { return $CleanString } Write-Debug $CleanString $HyphenatedString = $CleanString -replace '( )+', '-' Write-Debug $HyphenatedString return $HyphenatedString } function Remove-DiacriticsFromLatinCharacters([string] $StringToConvert) { if ([String]::IsNullOrEmpty($StringToConvert)) { return $StringToConvert } Write-Debug $StringToConvert [String] $Normalized = $StringToConvert.Normalize([System.Text.NormalizationForm]::FormD) [System.Text.StringBuilder] $SB = New-Object -TypeName "System.Text.StringBuilder" for ($i = 0; $i -lt $Normalized.Length; $i++) { [Char] $C = $Normalized[$i]; if ([System.Globalization.CharUnicodeInfo]::GetUnicodeCategory($C) -ne [System.Globalization.UnicodeCategory]::NonSpacingMark) { [void] $SB.Append($C) } } $StringWithoutDiacritics = $SB.ToString().Normalize([System.Text.NormalizationForm]::FormC) Write-Debug $StringWithoutDiacritics return $StringWithoutDiacritics } function Remove-DiacriticsViaCodepageConversion([string] $StringToConvert) { if ([String]::IsNullOrEmpty($StringToConvert)) { return $StringToConvert } Write-Debug $StringToConvert $NonUnicodeEncoding = [System.Text.Encoding]::GetEncoding(850) $UnicodeEncoding = [System.Text.Encoding]::Unicode [Byte[]] $UnicodeBytes = $UnicodeEncoding.GetBytes($StringToConvert); [Byte[]] $NonUnicodeBytes = [System.Text.Encoding]::Convert($UnicodeEncoding, $NonUnicodeEncoding , $UnicodeBytes); [Char[]] $NonUnicodeChars = New-Object -TypeName "Char[]" -ArgumentList $($NonUnicodeEncoding.GetCharCount($NonUnicodeBytes, 0, $NonUnicodeBytes.Length)) [void] $NonUnicodeEncoding.GetChars($NonUnicodeBytes, 0, $NonUnicodeBytes.Length, $NonUnicodeChars, 0); [String] $NonUnicodeString = New-Object String(,$NonUnicodeChars) #Tricky, Tricky, Tricky Write-Debug $NonUnicodeString return $NonUnicodeString } function Encode-URL([string] $StringToEncode) { Write-Debug $StringToEncode $EncodedUrl = [System.Web.HttpUtility]::UrlEncode($StringToEncode) Write-Debug $EncodedUrl return $EncodedUrl }
PowerShellCorpus/GithubGist/jeffhandley_6312875_raw_6164b4221602ad421a06e55e20a174fc24e969b5_Get-RandomPassword.ps1
jeffhandley_6312875_raw_6164b4221602ad421a06e55e20a174fc24e969b5_Get-RandomPassword.ps1
<# .SYNOPSIS Returns a random, timestamped, password #> # Base64-encode the Guid to add some additional characters [DateTime]::Now.ToString("MMMddyy") + "!" + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([Guid]::NewGuid().ToString()))
PowerShellCorpus/GithubGist/y0ug_ceb453ef63de5c681c7a_raw_f3882286565b5e4007fc6d0d7ff8e6aaf3349c61_disable_service.ps1
y0ug_ceb453ef63de5c681c7a_raw_f3882286565b5e4007fc6d0d7ff8e6aaf3349c61_disable_service.ps1
$filename = "service_disabled.txt" foreach ($line in get-content $filename) { $line = $line.trim() if($line.StartsWith("#")){ continue } $elems = $line.split("#") $srv = $elems[0].trim() $desc = $elems[1].trim() write-host "Disabled:" $srv "|" $desc set-service $srv -startuptype disabled }
PowerShellCorpus/GithubGist/jasongaylord_5672298_raw_851b2f4cdbefd127bc44349381309948b7d41ee2_Get-ADComputerCDRomInfo.ps1
jasongaylord_5672298_raw_851b2f4cdbefd127bc44349381309948b7d41ee2_Get-ADComputerCDRomInfo.ps1
Function Get-ADComputerCDRomInfo { # Search Active Directory for computers ([adsisearcher]"objectcategory=computer").findall() | ForEach-Object { # Set computer name $c = ([adsi]$_.path).Name; # Function variables $deviceId = "" $volumeName = "" $err = "" try { # Grab WMI object $w = Get-WmiObject -ComputerName $c -Class Win32_LogicalDisk -Filter "DriveType = 2 or DriveType = 5" -errorvariable MyErr -erroraction Stop; # If more than one item is returned, loop through items if ($w.Count -gt 0) { $w | ForEach-Object { # Populate the properties $deviceId = $_.DeviceID $volumeName = $_.VolumeName # If the drive letter length is 0, populate the default error if ($deviceId.Length -eq 0) { $err = "No drive found." } # Build the object and write the output $obj = new-object psobject $obj | Add-Member noteproperty Computer ($c) $obj | Add-Member noteproperty DriveLetter ($deviceId) $obj | Add-Member noteproperty VolumeName ($volumeName) $obj | Add-Member noteproperty Error ($err) Write-Output $obj } } else { # Populate the properties $deviceId = $w.DeviceID $volumeName = $w.VolumeName # If the drive letter length is 0, populate the default error if ($deviceId.Length -eq 0) { $err = "No drive found." } # Build the object and write the output $obj = new-object psobject $obj | Add-Member noteproperty Computer ($c) $obj | Add-Member noteproperty DriveLetter ($deviceId) $obj | Add-Member noteproperty VolumeName ($volumeName) $obj | Add-Member noteproperty Error ($err) Write-Output $obj } } Catch [system.exception] { # Let's make sure we're populating the correct error if ($MyErr.Count -gt 0) { $err = $MyErr } else { $err = $error[0].tostring() } # Build the object and write the output $obj = new-object psobject $obj | Add-Member noteproperty Computer ($c) $obj | Add-Member noteproperty DriveLetter ($deviceId) $obj | Add-Member noteproperty VolumeName ($volumeName) $obj | Add-Member noteproperty Error ($err) Write-Output $obj } } } # Execute this function Get-ADComputerCDRomInfo
PowerShellCorpus/GithubGist/ao-zkn_ab4570b0ce00b48c33a7_raw_0fa3b2d9cbe67d37e35057205ce1a41582190d90_Rotate-FileSize.ps1
ao-zkn_ab4570b0ce00b48c33a7_raw_0fa3b2d9cbe67d37e35057205ce1a41582190d90_Rotate-FileSize.ps1
# ------------------------------------------------------------------ # ファイルサイズでファイルのローテーションを行う # 関数名:Rotate-FileSize # 引数 :FilePath ファイルパス # :RollingFileSize 最大ファイルサイズ(デフォルト:10MB) # :MaxBackupIndex 最大バックアップログファイル数(デフォルト:10) # 戻り値:なし # ------------------------------------------------------------------ function Rotate-FileSize([String]$FilePath, [Int]$RollingFileSize = 10MB, [Int]$MaxBackupIndex = 10){ # ファイルが存在する場合 if(Test-Path -LiteralPath $FilePath -PathType Leaf){ # ファイルサイズ $filesize = $(Get-ItemProperty $FilePath).Length # ローテート対象 if($filesize -gt $RollingFileSize){ $sizeRollingName = (Split-Path $FilePath -Leaf) + "." $sizeRollingPath = Join-Path -Path (Split-Path $FilePath -Parent) -ChildPath $sizeRollingName for($i = $MaxBackupIndex - 1;$i -ge 1;$i--){ if(Test-Path -LiteralPath ($sizeRollingPath + $i) -PathType Leaf){ Move-Item -LiteralPath ($sizeRollingPath + $i) -Destination ($sizeRollingPath + ($i + 1)) -Force } } Move-Item -LiteralPath $FilePath -Destination ($sizeRollingPath + 1) -Force } } }
PowerShellCorpus/GithubGist/jeffpatton1971_8187557_raw_a02df64e9c3176393e0b92d1aaa703b458bc9515_SetupDSCClient.ps1
jeffpatton1971_8187557_raw_a02df64e9c3176393e0b92d1aaa703b458bc9515_SetupDSCClient.ps1
Configuration SetupDSCClient { param ( [string]$NodeId, [string]$PullServer ) LocalConfigurationManager { AllowModuleOverwrite = 'True' ConfigurationID = $NodeId ConfigurationModeFrequencyMins = 30 RefreshFrequencyMins = 15 ConfigurationMode = 'ApplyAndAutoCorrect' RebootNodeIfNeeded = 'True' RefreshMode = 'PULL' DownloadManagerName = 'WebDownloadManager' DownloadManagerCustomData = (@{ServerUrl = "http://$($PullServer)/psdscpullserver.svc";AllowUnsecureConnection = 'True'}) } }
PowerShellCorpus/GithubGist/devlead_9638825a3380fa473bca_raw_477e5aa8af7d669d855241ff2d2adadabf4c4849_gistfile1.ps1
devlead_9638825a3380fa473bca_raw_477e5aa8af7d669d855241ff2d2adadabf4c4849_gistfile1.ps1
gci -Directory -Recurse .git -Hidden|%{pushd;cd (Split-Path -Parent $_);(git remote -v)-split "`n"|%{$r=$_ -split "`t| ";iex "git remote set-url $(if($r[2]-eq"(push)"){"--push "})$($r[0]) $($r[1]-replace ("John","Doe"))"} ;popd}
PowerShellCorpus/GithubGist/andreimic_7804746_raw_d894e94952f959a1d696e824a9c13c5c7f6019a1_gistfile1.ps1
andreimic_7804746_raw_d894e94952f959a1d696e824a9c13c5c7f6019a1_gistfile1.ps1
# References # http://www.thesysadminhimself.com/2013/09/sharepoint-start-workflow-all-items-powershell.html # http://social.technet.microsoft.com/Forums/sharepoint/en-US/dffdceab-f2fe-4886-8e2a-ea26cf08c78a/how-to-start-a-speific-workflow-programatically-in-sharepoint-2010-via-powershell $web = Get-SPWeb -Identity "https://intranet.contoso.com" $manager = $web.Site.WorkFlowManager # Name of the list $list = $web.Lists["Shared Documents"] # Name of the Workflow $assoc = $list.WorkflowAssociations.GetAssociationByName("On Item Created","en-US") $data = $assoc.AssociationData $items = $list.Items foreach($item in $items) { $wf = $manager.StartWorkFlow($item,$assoc,$data,$true) } $manager.Dispose() $web.Dispose()
PowerShellCorpus/GithubGist/uniquelau_5592800_raw_4f7db2ca2e542fafa1de5686978cdec43e186e5b_createWebsite.ps1
uniquelau_5592800_raw_4f7db2ca2e542fafa1de5686978cdec43e186e5b_createWebsite.ps1
<# .SYNOPSIS CreateWebsite - Automatic website creation. .DESCRIPTION Allow to create a website and its ApplicationPool. Some tuning is included .PARAMETER SiteName Defines the display name (in IIS Manager) of the website Mandatory parameter. .PARAMETER Port Defines the listening port for the website Default is "80". .PARAMETER Environment Defines the website environment. This will be added as suffix in the website display name Possible values are "LIVE", "STAGING", "UAT", "QUAL" or "DEV" Default is "LIVE". .PARAMETER Identity Defines the identity type to be used for the ApplicationPool Possible values are "0" (LocalSystem), "1" (LocalService), "2" (NetworkService), "3" (SpecificUser) or "4" (ApplicationPoolIdentity) Default is "4" (ApplicationPoolIdentity). .PARAMETER Runtime Defines the Managed Runtime to be used for the ApplicationPool Possible values are "1.1", "2.0" or "4.0" Default is "4.0". .PARAMETER Pipeline Defines the Managed Pipeline Mode to be used for the ApplicationPool Possible values are "Classic" = 1 "Integrated" = 0 Default is "Integrated". .PARAMETER Computer Computer name, default %Computer% .PARAMETER InetFolder Default location that contains each website (normally c:\inetpub, d:\inetpubs, or d:\webs) .PARAMETER Domain Default top-level domain used to build default hostname. .PARAMETER Hostname Defines the URL the website reponds to. Default 'http://$SiteName-$Enviroment.$Computer.$Domain' .PARAMETER EnvironmentHostName Default 'http://$SiteName.$Environment.$Domain' .PARAMETER VDirName Name for the Virtual Directory (e.g. Media) .PARAMETER FileShare Location of your File Share .PARAMETER VDirPath Default $SiteName-$Environment\$VDirName\ .NOTES File Name : CreateWebsite.ps1 Remixed by : Laurence Gillian lau@voodoobytes.co.uk Orginal production by : Fabrice ZERROUKI - fabricezerrouki@hotmail.com .EXAMPLE PS D:\>CreateWebsite.ps1 -SiteName TESTSITE Creates a website named 'testsite-LIVE', listening on the TCP80 port (default value), responding to 'http://$SiteName-$Enviroment.$Computer.$Domain' (default value). The associated ApplicationPool 'testsite' running with the identity 'ApplicationPoolIdentity' (default value), v4.0 .NET Framework managed runtime (default value) and 'Integrated' managed pipeline mode (default value). .EXAMPLE PS D:\>CreateWebsite.ps1 -SiteName TESTSITE -Port 8080 -Environment PREPROD -Runtime 2.0 -Pipeline Classic Creates a website named 'testsite-PREPROD', listening on the TCP8080 port. The associated ApplicationPool 'testsite' running with the identity 'ApplicationPoolIdentity' (default value), v2.0 .NET Framework managed runtime and 'Classic' managed pipeline mode. By default the site is binded to http://$SiteName-$Environment.$Computer.$Domain http://$SiteName.$Environment.$Domain .EXAMPLE PS D:\>CreateWebsite.ps1 -SiteName TESTSITE -VDirName Media Creates a website named TESTSITE-LIVE, with a virtual directory for Media, that points at $FileShare\$VDirPath e.g. 192.168.1.1\TESTSITE-LIVE\Media #> Param( [Parameter(Mandatory=$true, HelpMessage="You must provide a display name for the website.")] $SiteName, $Port="80", [ValidateSet("LIVE", "STAGING", "UAT", "QUAL", "DEV")] $Environment="LIVE", [ValidateSet("0", "1", "2", "3", "4")] $Identity="4", [ValidateSet("v1.1", "v2.0", "v4.0")] $Runtime="v4.0", [ValidateSet("1", "0")] $Pipeline="0", $Computer=$env:COMPUTERNAME, $InetFolder="c:\inetpubs", $Domain="voodoobytes.net", [ValidatePattern("([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?")] $HostName="$SiteName-$Environment" + ".$Computer" + ".$Domain", $EnvironmentHostName="$SiteName.$Environment.$Domain", $VDirName="", $FileShare="\\192.168.1.1\", $VDirPath="$SiteName-$Environment\$VDirName\" ) switch ($Identity) { 0 {$FullIdentity="LocalSystem"} 1 {$FullIdentity="LocalService"} 2 {$FullIdentity="NetworkService"} 3 {$FullIdentity="SpecificUser"} 4 {$FullIdentity="ApplicationPoolIdentity"} } Function Ask-YesOrNo { param([string]$title="Confirmation needed.",[string]$message="Parameters that will be used by the script are listed above.`nIf you want to modify one or more parameter, please restart the script and specify the wanted parameters.`nAny not defined parameter uses its default value.`r`nDo you want to continue with the above parameters?`n") $choiceYes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Answer Yes." $choiceNo = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Answer No." $options = [System.Management.Automation.Host.ChoiceDescription[]]($choiceYes, $choiceNo) $nresult = $host.ui.PromptForChoice($title, $message, $options, 1) switch ($nresult) { 0 {"OK, we can continue..."} 1 {"Bye bye!" ; exit} } } Write-Host "`n**********************************************************" -ForegroundColor Yellow Write-Host "*`t`tAutomatic Website Creation" -ForegroundColor Yellow Write-Host "*" -ForegroundColor Yellow Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Parameters" Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Website Name (-SiteName):`t`t" -nonewline; Write-Host "$SiteName" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Website Port (-Port):`t`t`t" -nonewline; Write-Host "$Port" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Website Environment (-Environment):`t" -nonewline; Write-Host "$Environment" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " AppPool Identity (-Identity):`t`t" -nonewline; Write-Host "$FullIdentity ($Identity)" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Managed Runtime (-Runtime):`t`t" -nonewline; Write-Host "$Runtime" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Managed Pipeline Mode (-Pipeline):`t" -nonewline; Write-Host "$Pipeline" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Computer Name (-Computer):`t`t" -nonewline; Write-Host "$Computer" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Inetpub Folder (-InetFolder):`t`t" -nonewline; Write-Host "$InetFolder" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Top Level Domain (-Domain):`t`t" -nonewline; Write-Host "$Domain" -ForegroundColor DarkGreen Write-Host "*" -ForegroundCOlor Yellow Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Website Hostname (-HostName):`t`t" -nonewline; Write-Host "$HostName" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Environment (-EnvironmentHostName):`t" -nonewline; Write-Host "$EnvironmentHostName" -ForegroundColor DarkGreen Write-Host "*" -ForegroundCOlor Yellow if ($VDirName) { Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Virtual Directory Name (-VDirName):`t" -nonewline; Write-Host "$VDirName" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " File Share (-FileShare):`t`t" -nonewline; Write-Host "$FileShare" -ForegroundColor DarkGreen Write-Host "*" -ForegroundColor Yellow -nonewline; Write-Host " Virtual Directory Path (-VDirPath):`t" -nonewline; Write-Host "$VDirPath" -ForegroundColor DarkGreen } Write-Host "*" -ForegroundColor Yellow Write-Host "**********************************************************" -ForegroundColor Yellow Ask-YesOrNo if ($nresult -eq "$false") {exit} if ($Identity -eq "3") { $AppPoolUser=Read-Host "`nPlease provide username for the ApplicationPool identity" $AppPoolPwd=Read-Host "Please provide the password for '$AppPoolUser' user" -AsSecureString } function Read-Choice { Param( [System.String]$Message, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.String[]]$Choices, [System.Int32]$DefaultChoice=1, [System.String]$Title=[string]::Empty ) [System.Management.Automation.Host.ChoiceDescription[]]$Poss=$Choices | ForEach-Object { New-Object System.Management.Automation.Host.ChoiceDescription "&$($_)", "Sets $_ as an answer." } $Host.UI.PromptForChoice($Title, $Message, $Poss, $DefaultChoice) } function Select-IPAddress { [cmdletbinding()] Param( [System.String]$ComputerName='localhost' ) $IPs=Get-WmiObject -ComputerName $ComputerName -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled='True'" | ForEach-Object { $_.IPAddress } | Where-Object { $_ -match "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" } if($IPs -is [array]){ Write-Host "`nServer $ComputerName uses these IP addresses:" $IPs | ForEach-Object {$Id=0} {Write-Host "${Id}: $_" -ForegroundColor Yellow; $Id++} $IPs[(Read-Choice -Message "`nChoose an IP Address" -Choices (0..($Id-1)) -DefaultChoice 0)] } else{$IPs} } $ChosenIP=Select-IPAddress Write-Host "`nThe selected IP address is: $ChosenIP`n" -ForegroundColor DarkGreen # Combine SiteName and Enviroment $SiteNameEnvironment = "$SiteName-$Environment" # Create the website directory Write-Host "Creating application directory" -ForegroundColor Yellow $ProjectPath = "$InetFolder" + "\" + "$SiteNameEnvironment" $SitePath = "$ProjectPath" + "\wwwroot\" if (!(Test-Path $SitePath)) { New-Item -ItemType Directory -Path $SitePath } # Creates the website logfiles directory Write-Host "Creating application logfiles directory" -ForegroundColor Yellow $SiteLogsPath = "$ProjectPath" + "\logs\" if (!(Test-Path $SiteLogsPath)) { New-Item -ItemType Directory -Path $SiteLogsPath } Import-Module "WebAdministration" -ErrorAction Stop # Creates the ApplicationPool Write-Host "Creating website application pool" -ForegroundColor Yellow New-WebAppPool –Name $SiteNameEnvironment -Force Set-ItemProperty ("IIS:\AppPools\" + $SiteNameEnvironment) -Name processModel.identityType -Value $Identity if ($Identity -eq "3") { Set-ItemProperty ("IIS:\AppPools\" + $SiteNameEnvironment) -Name processModel.username -Value $AppPoolUser Set-ItemProperty ("IIS:\AppPools\" + $SiteNameEnvironment) -Name processModel.password -Value $AppPoolPwd } Set-ItemProperty ("IIS:\AppPools\" + $SiteNameEnvironment) -Name "managedRuntimeVersion" -Value $Runtime Set-ItemProperty ("IIS:\AppPools\" + $SiteNameEnvironment) -Name "managedPipelineMode" -Value $Pipeline # Creates the website Write-Host "Creating website" -ForegroundColor Yellow New-Website –Name $SiteNameEnvironment -Port $Port –HostHeader $HostName -IPAddress $ChosenIP -PhysicalPath $SitePath -ApplicationPool $SiteNameEnvironment -Force Set-ItemProperty ("IIS:\Sites\" + $SiteNameEnvironment) -Name logfile.directory -Value $SiteLogsPath # Add additional bindings Write-Host "Adding environment binding" -ForegroundColor Yellow New-WebBinding -Name $SiteNameEnvironment -Port $Port -IPAddress $ChosenIP -HostHeader $EnvironmentHostName -Force # Create Virtual Directory that points at a FileShare/SAN/NAS, etc # Must point to existing path, so FileShare + VDirPath if ($VDirName -and $FileShare) { # If Directory doesn't exist then create it if (!(Test-Path $FileShare\$VDirPath)) { New-Item -ItemType Directory -Path $FileShare\$VDirPath } Write-Host "Creating a virtual directory" -ForegroundColor Yellow New-WebVirtualDirectory -Site $SiteNameEnvironment -Name $VDirName -PhysicalPath $FileShare\$VDirPath } Start-WebAppPool -Name $SiteNameEnvironment Start-WebSite $SiteNameEnvironment Write-Host "Excellent!!!" -ForegroundColor DarkGreen Write-Host "Website $SiteNameEnvironment created!" -ForegroundColor DarkGreen
PowerShellCorpus/GithubGist/urasandesu_4f99747caea265a579ec_raw_39a300f4459f665e812cd1ca2b2e0093db40baf2_Invoke-PilotStubber.ps1
urasandesu_4f99747caea265a579ec_raw_39a300f4459f665e812cd1ca2b2e0093db40baf2_Invoke-PilotStubber.ps1
[CmdletBinding()] param ( [string[]] $ReferenceFrom, [string] $Assembly, [string] $TargetFrameworkVersion, [string] $KeyFile, [string] $OutputPath, [string] $Settings, [switch] $WhatIf ) # ----------------------------------------------------------------------------------------------- # # Utilities # # ----------------------------------------------------------------------------------------------- $ToRootNamespace = { param ($AssemblyInfo) $AssemblyInfo.GetName().Name + '.Prig' } $ToSignAssembly = { param ($KeyFile) if ([string]::IsNullOrEmpty($KeyFile)) { $false } else { $true } } $ToProcessorArchitectureConstant = { param ($AssemblyInfo) switch ($AssemblyInfo.GetName().ProcessorArchitecture) { 'X86' { "_M_IX86" } 'Amd64' { "_M_AMD64" } 'MSIL' { "_M_MSIL" } Default { "_M_MSIL" } } } $ToTargetFrameworkVersionConstant = { param ($TargetFrameworkVersion) switch ($TargetFrameworkVersion) { 'v3.5' { "_NET_3_5" } 'v4.0' { "_NET_4" } 'v4.5' { "_NET_4_5" } 'v4.5.1' { "_NET_4_5_1" } Default { "_NET_4" } } } $ToDefineConstants = { param ($AssemblyInfo, $TargetFrameworkVersion) $result = (& $ToProcessorArchitectureConstant $AssemblyInfo), (& $ToTargetFrameworkVersionConstant $TargetFrameworkVersion) $result -join ';' } $ToPlatformTarget = { param ($AssemblyInfo) switch ($AssemblyInfo.GetName().ProcessorArchitecture) { 'X86' { "x86" } 'Amd64' { "x64" } 'MSIL' { "AnyCPU" } Default { "AnyCPU" } } } $ToProcessorArchitectureString = { param ($AssemblyInfo) switch ($AssemblyInfo.GetName().ProcessorArchitecture) { 'X86' { "x86" } 'Amd64' { "AMD64" } 'MSIL' { "MSIL" } Default { "MSIL" } } } $ToAssemblyName = { param ($AssemblyInfo) '{0}.{1}.v{2}.{3}.Prig' -f $AssemblyInfo.GetName().Name, $AssemblyInfo.ImageRuntimeVersion, $AssemblyInfo.GetName().Version.ToString(), (& $ToProcessorArchitectureString $AssemblyInfo) } $ToReferenceInclude = { param ($refAsmInfos) foreach ($refAsmInfo in $refAsmInfos) { @" <Reference Include="$($refAsmInfo.GetName().Name)"> <HintPath>$($refAsmInfo.Location)</HintPath> </Reference> "@ } } $GenerateCsproj = { param ($AssemblyInfo, $ReferencedAssemblyInfos, $KeyFile, $TargetFrameworkVersion, $OutputPath) $rootNamespace = & $ToRootNamespace $AssemblyInfo $signAsm = & $ToSignAssembly $KeyFile $defineConsts = & $ToDefineConstants $AssemblyInfo $TargetFrameworkVersion $platform = & $ToPlatformTarget $AssemblyInfo $asmName = & $ToAssemblyName $AssemblyInfo $refInc = & $ToReferenceInclude $ReferencedAssemblyInfos $csprojTemplate = [xml]@" <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>$rootNamespace</RootNamespace> <FileAlignment>512</FileAlignment> <SignAssembly>$signAsm</SignAssembly> <AssemblyOriginatorKeyFile>$KeyFile</AssemblyOriginatorKeyFile> <OutputPath>$OutputPath</OutputPath> <DefineConstants>$defineConsts</DefineConstants> <PlatformTarget>$platform</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <TargetFrameworkVersion>$TargetFrameworkVersion</TargetFrameworkVersion> <AssemblyName>$asmName</AssemblyName> </PropertyGroup> <ItemGroup>$refInc</ItemGroup> <ItemGroup> <Compile Include="**/*.cs" /> </ItemGroup> <Import Project="`$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> </Project> "@ New-Object psobject | Add-Member NoteProperty 'Path' "$rootNamespace.csproj" -PassThru | Add-Member NoteProperty 'XmlDocument' $csprojTemplate -PassThru } $ToFullNameFromType = { param ($Type) $defName = $Type.FullName if ($Type.IsGenericType -and !$Type.IsGenericTypeDefinition) { $defName = $Type.Namespace + "." + $Type.Name } elseif ($Type.ContainsGenericParameters) { $defName = $Type.Name } if ($Type.IsGenericType) { $defName = $defName -replace '`\d+', '' $genericArgNames = @() foreach ($genericArg in $Type.GetGenericArguments()) { $genericArgNames += (& $ToFullNameFromType $genericArg) } $defName = ($defName + "<" + ($genericArgNames -join ', ') + ">") } $defName } $ToClassNameFromType = { param ($Type) $defName = $Type.Name if ($Type.IsGenericType) { $defName = $defName -replace '`\d+', '' $genericArgNames = @() foreach ($genericArg in $Type.GetGenericArguments()) { $genericArgNames += (& $ToFullNameFromType $genericArg) } $defName = ($defName + "<" + ($genericArgNames -join ', ') + ">") } $defName } $ToClassNameFromStub = { param ($Stub) $defName = $Stub.Alias if ($Stub.Target.IsGenericMethod) { $defName = $defName -replace '`\d+', '' $genericArgNames = @() foreach ($genericArg in $Stub.Target.GetGenericArguments()) { $genericArgNames += (& $ToFullNameFromType $genericArg) } $defName = ($defName + "<" + ($genericArgNames -join ', ') + ">") } $defName } $GenerateTokensCs = { param ($AssemblyInfo, $Section, $TargetFrameworkVersion) $content = @" #if $(& $ToTargetFrameworkVersionConstant $TargetFrameworkVersion) && $(& $ToProcessorArchitectureConstant $AssemblyInfo) //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Assembly : $($AssemblyInfo.GetName().Name) // Runtime Version : $($AssemblyInfo.ImageRuntimeVersion) // Assembly Version : $($AssemblyInfo.GetName().Version.ToString()) // Processor Architecture : $(& $ToProcessorArchitectureString $AssemblyInfo) // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Urasandesu.Prig.Framework; "@ + $(foreach ($stub in $Section.Stubs) { @" [assembly: Indirectable($($stub.Target.DeclaringType.Namespace).Prig.P$($stub.Target.DeclaringType.Name).TokenOf$($stub.Name))] "@}) + @" "@ + $(foreach ($namespaceGrouped in $Section.GroupedStubs) { @" namespace $($namespaceGrouped.Key).Prig { "@ + $(foreach ($declTypeGrouped in $namespaceGrouped) { @" public partial class P$(& $ToClassNameFromType $declTypeGrouped.Key) { "@ + $(foreach ($stub in $declTypeGrouped) { @" internal const int TokenOf$($stub.Name) = 0x$($stub.Target.MetadataToken.ToString('X8')); "@}) + @" } "@}) + @" } "@}) + @" #endif "@ New-Object psobject | Add-Member NoteProperty 'Path' 'AutoGen\Tokens.g.cs' -PassThru | Add-Member NoteProperty 'Content' $content -PassThru } $GenerateStubsCs = { param ($AssemblyInfo, $Section, $TargetFrameworkVersion) $results = New-Object System.Collections.ArrayList foreach ($namespaceGrouped in $Section.GroupedStubs) { $dir = $namespaceGrouped.Key -replace '\.', '\' foreach ($declTypeGrouped in $namespaceGrouped) { $content = @" using Urasandesu.Prig.Framework; namespace $($namespaceGrouped.Key).Prig { public partial class P$(& $ToClassNameFromType $declTypeGrouped.Key) { "@ + $(foreach ($stub in $declTypeGrouped) { @" public static class $(& $ToClassNameFromStub $stub) { public static $(& $ToClassNameFromType $stub.IndirectionDelegate) Body { set { var info = new IndirectionInfo(); info.AssemblyName = "$($AssemblyInfo.FullName)"; info.Token = TokenOf$($stub.Name); var holder = LooseCrossDomainAccessor.GetOrRegister<IndirectionHolder<$(& $ToClassNameFromType $stub.IndirectionDelegate)>>(); holder.AddOrUpdate(info, value); } } } "@}) + @" } } "@ $result = New-Object psobject | Add-Member NoteProperty 'Path' "$dir\$($declTypeGrouped.Key.Name).cs" -PassThru | Add-Member NoteProperty 'Content' $content -PassThru [Void]$results.Add($result) } } ,$results } # ----------------------------------------------------------------------------------------------- # # Main # # ----------------------------------------------------------------------------------------------- Write-Verbose ('ReferenceFrom : {0}' -f $ReferenceFrom) Write-Verbose ('Assembly : {0}' -f $Assembly) Write-Verbose ('Target Framework Version : {0}' -f $TargetFrameworkVersion) Write-Verbose ('Key File : {0}' -f $KeyFile) Write-Verbose ('Output Path : {0}' -f $OutputPath) Write-Verbose ('Settings : {0}' -f $Settings) Write-Verbose 'Load Settings ...' [Void][System.Reflection.Assembly]::LoadWithPartialName('System.Configuration') $asmInfo = [System.Reflection.Assembly]::Load($Assembly) $refAsmInfos = New-Object 'System.Collections.Generic.List[System.Reflection.Assembly]' foreach ($refFrom in $ReferenceFrom) { $refAsmInfos.Add([System.Reflection.Assembly]::LoadFrom($refFrom)) } $onAsmInfoResolve = [System.ResolveEventHandler] { param($Sender, $E) foreach($curAsmInfo in [System.AppDomain]::CurrentDomain.GetAssemblies()) { if ($curAsmInfo.FullName -match $E.Name) { return $curAsmInfo } } return $null } [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAsmInfoResolve) $fileMap = New-Object System.Configuration.ExeConfigurationFileMap $fileMap.ExeConfigFilename = $Settings $config = [System.Configuration.ConfigurationManager]::OpenMappedExeConfiguration($fileMap, [System.Configuration.ConfigurationUserLevel]::None) $section = $config.GetSection("prig") Write-Verbose 'Generate Tokens.g.cs ...' $tokensCsInfo = & $GenerateTokensCs $asmInfo $section $TargetFrameworkVersion $tokensCsDir = [System.IO.Path]::GetDirectoryName($tokensCsInfo.Path) if (![string]::IsNullOrEmpty($tokensCsDir) -and ![IO.Directory]::Exists($tokensCsDir)) { New-Item $tokensCsDir -ItemType Directory -WhatIf:$WhatIf -ErrorAction Stop | Out-Null } $tokensCsInfo.Content | Out-File $tokensCsInfo.Path -Encoding utf8 -WhatIf:$WhatIf -ErrorAction Stop | Out-Null Write-Verbose 'Generate stubs *.cs ...' $stubsCsInfos = & $GenerateStubsCs $asmInfo $section $TargetFrameworkVersion foreach ($stubsCsInfo in $stubsCsInfos) { $stubsCsDir = [System.IO.Path]::GetDirectoryName($stubsCsInfo.Path) if (![string]::IsNullOrEmpty($stubsCsDir) -and ![IO.Directory]::Exists($stubsCsDir)) { New-Item $stubsCsDir -ItemType Directory -WhatIf:$WhatIf -ErrorAction Stop | Out-Null } $stubsCsInfo.Content | Out-File $stubsCsInfo.Path -Encoding utf8 -WhatIf:$WhatIf -ErrorAction Stop | Out-Null } Write-Verbose 'Generate *.csproj ...' $csprojInfo = & $GenerateCsproj $asmInfo $refAsmInfos $KeyFile $TargetFrameworkVersion $OutputPath $csprojDir = [System.IO.Path]::GetDirectoryName($csprojInfo.Path) if (![string]::IsNullOrEmpty($csprojDir) -and ![IO.Directory]::Exists($csprojDir)) { New-Item $csprojDir -ItemType Directory -WhatIf:$WhatIf -ErrorAction Stop | Out-Null } $csprojInfo.XmlDocument.Save($csprojInfo.Path) Write-Verbose 'Build all *.cs files ...' & msbuild $csprojInfo.Path /t:rebuild
PowerShellCorpus/GithubGist/MyITGuy_9472976_raw_05d6b53ea769c709991de2c4cd30a0637a7aa2a3_smpAutomationEmailCheck.ps1
MyITGuy_9472976_raw_05d6b53ea769c709991de2c4cd30a0637a7aa2a3_smpAutomationEmailCheck.ps1
[CmdletBinding(SupportsShouldProcess=$True)] param ( #SMTP server name [string]$smtpServer = "smtp", [string]$From, #[string]$ReplyTo = "", [string]$To, [string]$Cc, [string]$Subject = "Automation Policies Email Verification", [switch]$Export ) Import-Module SQLPS Import-Module ActiveDirectory function sendMail { Write-Verbose "Sending email" #Creating a Mail object Write-Verbose "Creating Net.Mail.MailMessage object" $MailMessage = New-Object Net.Mail.MailMessage #Creating SMTP server object Write-Verbose "Creating Net.Mail.SmtpClient object using: $($smtpServer)" $SmtpClient = New-Object Net.Mail.SmtpClient($smtpServer) $SmtpClient.UseDefaultCredentials = $true #$Credential = Get-Credential Write-Verbose "Using credentials: $($Credential.UserName)" #$SmtpClient.Credentials = $Credential #Email structure Write-Verbose "From: $($From)" $MailMessage.From = $From # Write-Verbose "ReplyTo: $($ReplyTo)" # $MailMessage.ReplyTo = $ReplyTo Write-Verbose "To: $($To)" $MailMessage.To.Add($To) Write-Verbose "Cc: $($Cc)" $MailMessage.Cc.Add($Cc) Write-Verbose "Subject: $($Subject)" $MailMessage.Subject = $Subject Write-Verbose "Body: $($Body)" $MailMessage.Body = "$HTML" $MailMessage.IsBodyHTML = $true #Sending email try { $SmtpClient.Send($MailMessage) } catch { Write-Verbose $_ return } } if ($PSBoundParameters['Verbose']) { Write-Verbose "Verbose logging enabled" } $CurrentLocation = Get-Location $AutomationPolicies = Invoke-Sqlcmd -ServerInstance "SMP" -Database "Symantec_CMDB" -InputFile "AeX_Show_Automation_Policy_Email_Recipients.sql" Set-Location $CurrentLocation $Validators = New-Object -TypeName PSObject $Validators = @() foreach ($AutomationPolicy In $AutomationPolicies) { $Name = $AutomationPolicy.'Automation Policy' $EmailAddresses = @() if ($AutomationPolicy.TO_EMAIL -ne $null -and $AutomationPolicy.TO_EMAIL -ne '') {$EmailAddresses += ($AutomationPolicy.TO_EMAIL -split ',' | Where {($EmailAddresses -notcontains $_)})} if ($AutomationPolicy.CC_EMAIL -ne $null -and $AutomationPolicy.CC_EMAIL -ne '') {$EmailAddresses += ($AutomationPolicy.CC_EMAIL -split ',' | Where {($EmailAddresses -notcontains $_)})} $EmailAddressesCount = ($EmailAddresses | Measure).Count $DiscoveredCount = 0 $ValidSMTPAddresses = @() $InvalidSMTPAddresses = @() foreach ($EmailAddress In $EmailAddresses) { $EmailAddress = $EmailAddress.Trim() if ($EmailAddress.IndexOf('<') -ge 0) { # "Test Account" <test@something.local> $SMTPAddress = $EmailAddress.Substring($EmailAddress.IndexOf('<') + 1, (($EmailAddress.IndexOf('>')) - ($EmailAddress.IndexOf('<') + 1))) Write-Verbose "Using $($SMTPAddress) instead of $($EmailAddress)" } else { $SMTPAddress = $EmailAddress } $SMTPAddress = $SMTPAddress -replace ("'", "''") Try { $ThisCount = (Get-ADObject -Filter "proxyAddresses -eq 'SMTP:$($SMTPAddress)'" | Measure).Count } Catch { $_ $ThisCount = 0 } if ($ThisCount -le 0) { $InvalidSMTPAddresses += $EmailAddress } else { $ValidSMTPAddresses += $EmailAddress $DiscoveredCount += 1 } } $Validator = New-Object -TypeName PSObject -Property @{ Name = $Name ValidCount = $DiscoveredCount InvalidCount = ($EmailAddressesCount - $DiscoveredCount) ValidSMTP = $ValidSMTPAddresses -join ',' InValidSMTP = $InvalidSMTPAddresses -join ',' } $Validators += $Validator } # use a calculated field and set the Ascending attribute to False $HTML = $Validators | Sort -Property @{Expression = {$_.InvalidCount}; Descending = $true},@{Expression = {$_.ValidCount}; Ascending = $true} | Select Name,InvalidCount,InvalidSMTP,ValidCount,ValidSMTP | ConvertTo-Html -Title "Report" -Head "<style>body {font-family: verdana; font-size: 8pt;}</style>" if ($Export) { $Validators | Sort -Property @{Expression = {$_.InvalidCount}; Descending = $true},@{Expression = {$_.ValidCount}; Ascending = $true} | Select Name,InvalidCount,InvalidSMTP,ValidCount,ValidSMTP | Export-Csv -NoTypeInformation "export.csv" } else { $InvalidCount = ($Validators | Where {$_.InvalidCount -ne 0} | Measure).Count if ($InvalidCount -gt 0) {sendMail} }
PowerShellCorpus/GithubGist/janikvonrotz_6247871_raw_3aa26fe8d437566e113e69cf1af6bce628ba9642_New-ADUsers.ps1
janikvonrotz_6247871_raw_3aa26fe8d437566e113e69cf1af6bce628ba9642_New-ADUsers.ps1
<# $Metadata = @{ Title = "Create new ActiveDirectory users" Filename = "New-ADUsers.ps1" Description = "" Tags = "powershell, activedirectory, user" Project = "" Author = "Janik von Rotz" AuthorContact = "http://janikvonrotz.ch" CreateDate = "2013-08-16" LastEditDate = "2013-08-21" Url = "https://gist.github.com/janikvonrotz/6247871" Version = "1.1.0" License = @' This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Switzerland License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ch/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. '@ } #> Import-Module Quest.ActiveRoles.ArsPowerShellSnapIn $ADUsers = Import-CSV "ADUsers.csv" -Delimiter ";" $ADUsers | foreach{ if(!(Get-QADUser $_.Name)){ Write-Host "Creating user" $_.Name # create a new user New-QADUser -Name $_.Name ` -DisplayName $_.DisplayName ` -FirstName $_.givenName ` -LastName $_.LastName ` -Company $_.company ` -PostalCode $_.postalCode ` -PostOfficeBox $_.postOfficeBox ` -StreetAddress $_.streetAddress ` -WebPage $_.wWWHomePage ` -City $_.l ` -Department $_.department ` -Manager $_.manager ` -Title $_.title ` -Email $_.mail ` -UserPrincipalName $_.UserPrincipalName ` -ParentContainer $_.OU ` -samAccountName $_.samAccountName ` -UserPassword $_.Password ` -ObjectAttributes @{ extensionAttribute1= $_.extensionAttribute1; extensionAttribute2 = $_.extensionAttribute2; extensionAttribute3 = $_.extensionAttribute3; co = $_.co; c = $_.c } | Set-QADUser -PasswordNeverExpires $true | Out-Null # update group memberships $ADMemberOfs = $_.MemberOf -split "," foreach( $ADMemberOf in $ADMemberOfs){ Write-Host "Add User $($_.Name) to the group $ADMemberOf" Add-QADMemberOf $_.Name -Group $ADMemberOf | Out-Null } }else{ Write-Host $_.Name "already exist" } }
PowerShellCorpus/GithubGist/ndelitski_3ce58ffe400882a6338f_raw_7899509b09ca1905726ed06d677c12f4ae2c36e9_vagrant-windows.ps1
ndelitski_3ce58ffe400882a6338f_raw_7899509b09ca1905726ed06d677c12f4ae2c36e9_vagrant-windows.ps1
# Powershell Script to prepare the windows install to be used with vagrant-windows Set-ExecutionPolicy -executionpolicy remotesigned -force # Step 1: Disable UAC New-ItemProperty -Path HKLM:Software\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -PropertyType DWord -Value 0 -Force | Out-Null Write-Host "User Access Control (UAC) has been disabled." -ForegroundColor Green # Step 2: Disable IE ESC Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}" -Name "IsInstalled" -Value 0 | Out-Null Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}" -Name "IsInstalled" -Value 0 | Out-Null Stop-Process -Name Explorer | Out-Null Write-Host "IE Enhanced Security Configuration (ESC) has been disabled." -ForegroundColor Green # Step 3: Disable the shutdown tracker # Reference: http://www.askvg.com/how-to-disable-remove-annoying-shutdown-event-tracker-in-windows-server-2003-2008/ If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability")) { New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" } New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" -Name "ShutdownReasonOn" -PropertyType DWord -Value 0 -Force -ErrorAction continue New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" -Name "ShutdownReasonUI" -PropertyType DWord -Value 0 -Force -ErrorAction continue Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" -Name "ShutdownReasonOn" -Value 0 Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" -Name "ShutdownReasonUI" -Value 0 Write-Host "Shutdown Tracker has been disabled." -ForegroundColor Green # Step 4: Disable Automatic Updates # Reference: http://www.benmorris.me/2012/05/1st-test-blog-post.html $AutoUpdate = (New-Object -com "Microsoft.Update.AutoUpdate").Settings $AutoUpdate.NotificationLevel = 1 $AutoUpdate.Save() Write-Host "Windows Update has been disabled." -ForegroundColor Green # Step 5: Disable Complex Passwords # Reference: http://vlasenko.org/2011/04/27/removing-password-complexity-requirements-from-windows-server-2008-core/ $seccfg = [IO.Path]::GetTempFileName() secedit /export /cfg $seccfg (Get-Content $seccfg) | Foreach-Object {$_ -replace "PasswordComplexity\s*=\s*1", "PasswordComplexity=0"} | Set-Content $seccfg secedit /configure /db $env:windir\security\new.sdb /cfg $seccfg /areas SECURITYPOLICY del $seccfg Write-Host "Complex Passwords have been disabled." -ForegroundColor Green # Step 6: Enable Remote Desktop # Reference: http://social.technet.microsoft.com/Forums/windowsserver/en-US/323d6bab-e3a9-4d9d-8fa8-dc4277be1729/enable-remote-desktop-connections-with-powershell (Get-WmiObject Win32_TerminalServiceSetting -Namespace root\cimv2\TerminalServices).SetAllowTsConnections(1,1) (Get-WmiObject -Class "Win32_TSGeneralSetting" -Namespace root\cimv2\TerminalServices -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0) # Step 7: Enable WinRM Control winrm quickconfig -q winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="512"}' winrm set winrm/config '@{MaxTimeoutms="1800000"}' winrm set winrm/config/service '@{AllowUnencrypted="true"}' winrm set winrm/config/service/auth '@{Basic="true"}' Write-Host "WinRM has been configured and enabled." -ForegroundColor Green # Step 8: Disable Windows Firewall &netsh "advfirewall" "set" "allprofiles" "state" "off" Write-Host "Windows Firewall has been disabled." -ForegroundColor Green
PowerShellCorpus/GithubGist/roberto-reale_4d6a2d32f3b25225decc_raw_d355d0a70b2ae3f91c176a4be529d53575f7c1ea_days_to_christmas.ps1
roberto-reale_4d6a2d32f3b25225decc_raw_d355d0a70b2ae3f91c176a4be529d53575f7c1ea_days_to_christmas.ps1
# # How many days until Christmas? # function DaysToXmas() { $now = Get-Date $Xmas = Get-Date -Day 25 -Month 12 if ($now -gt $Xmas) { $Xmas = Get-Date -Day 25 -Month 12 -Year ($now.Year + 1) } $diff = $Xmas.Subtract($now).Days if ($diff -eq 0) { Write-Host "Happy Christmas!" } return $diff }
PowerShellCorpus/GithubGist/andrewrjones_1600609_raw_98e386d00c752bf54ca37ff03c035b3d0038162a_Microsoft.PowerShell_profile.ps1
andrewrjones_1600609_raw_98e386d00c752bf54ca37ff03c035b3d0038162a_Microsoft.PowerShell_profile.ps1
# Import PowerShell Community Extensions # Available from http://pscx.codeplex.com/ $pscx = Get-Module -List Pscx if($m){Import-Module Pscx} Set-Alias open Invoke-Item Set-Alias vi gvim # because I forget... function prompt { # set the window title to the path $host.ui.RawUI.WindowTitle = $(get-location) # change the colour of the prompt Write-Host ("PS" + ">") -nonewline -foregroundcolor Gray # return a String return " " }
PowerShellCorpus/GithubGist/PaulDMurphy_08aec7fe6b9b2ec20159_raw_963cc6c983ff3063e98795c9d6aaf315ce07808f_updates.ps1
PaulDMurphy_08aec7fe6b9b2ec20159_raw_963cc6c983ff3063e98795c9d6aaf315ce07808f_updates.ps1
# Boxstarter options $Boxstarter.RebootOk =$true # Allow reboots? $Boxstarter.AutoLogin =$true # Save my password securely and auto-login after a reboot $Boxstarter.NoPassword =$false # Is this a machine with no login password? # Set the execution policy Update-ExecutionPolicy Unrestricted # Configure Windows Set-CornerNavigationOptions -DisableUpperRightCornerShowCharms -DisableUpperLeftCornerSwitchApps -EnableUsePowerShellOnWinX Set-ExplorerOptions -hideHidenFilesFoldersDrives -showFileExtensions #Set-StartScreenOptions -EnableBootToDesktop -DisableDesktopBackgroundOnStart -DisableSearchEverywhereInAppsView Set-TaskbarOptions -Dock Top -Size Small -Lock Enable-RemoteDesktop winrm qc -force # Always check for patches Install-WindowsUpdate -AcceptEula if (Test-PendingReboot) { Invoke-Reboot }
PowerShellCorpus/GithubGist/jonschoning_1149285_raw_0fca3c000df90fca570cc5b3181079f5fbd59003_Format-Columns.ps1
jonschoning_1149285_raw_0fca3c000df90fca570cc5b3181079f5fbd59003_Format-Columns.ps1
function Format-Columns { ################################################################ #.Synopsis # Formats incoming data to columns. #.Description # It works similarly as Format-Wide but it works vertically. Format-Wide outputs # the data row by row, but Format-Columns outputs them column by column. #.Parameter Property # Name of property to get from the object. # It may be # -- string - name of property. # -- scriptblock # -- hashtable with keys 'Expression' (value is string=property name or scriptblock) # and 'FormatString' (used in -f operator) #.Parameter Column # Count of columns #.Parameter Autosize # Determines if count of columns is computed automatically. #.Parameter MaxColumn # Maximal count of columns if Autosize is specified #.Parameter InputObject # Data to display #.Example # PS> 1..150 | Format-Columns -Autosize #.Example # PS> Format-Columns -Col 3 -Input 1..130 #.Example # PS> Get-Process | Format-Columns -prop @{Expression='Handles'; FormatString='{0:00000}'} -auto #.Example # PS> Get-Process | Format-Columns -prop {$_.Handles} -auto #.Notes # Name: Get-Columns # Author: stej, http://twitter.com/stejcz # Lastedit: 2010-01-18 # Version 0.3 - 2010-01-18 # - fixed for Posh ISE # Version 0.2 - 2010-01-14 # - added MaxColumn # - fixed bug - displaying collection of 1 item was incorrect # Version 0.1 - 2010-01-06 ################################################################ param( [Parameter(Mandatory=$false,Position=0)][Object]$Property, [Parameter()][switch]$Autosize, [Parameter(Mandatory=$false)][int]$Column, [Parameter(Mandatory=$false)][int]$MaxColumn, [Parameter(Mandatory=$true,ValueFromPipeline=$true)][PsObject[]]$InputObject ) begin { $values = @() } process { $values += $InputObject } end { function ProcessValues { $ret = $values $p = $Property if ($p -is [Hashtable]) { $exp = $p.Expression if ($exp) { if ($exp -is [string]) { $ret = $ret | % { $_.($exp) } } elseif ($exp -is [scriptblock]) { $ret = $ret | % { & $exp $_} } else { throw 'Invalid Expression value' } } if ($p.FormatString) { if ($p.FormatString -is [string]) { $ret = $ret | % { $p.FormatString -f $_ } } else { throw 'Invalid format string' } } } elseif ($p -is [scriptblock]) { $ret = $ret | % { & $p $_} } elseif ($p -is [string]) { $ret = $ret | % { $_.$p } } elseif ($p -ne $null) { throw 'Invalid -property type' } # in case there were some numbers, objects, etc., convert them to string $ret | % { $_.ToString() } } function Base($i) { [Math]::Floor($i) } function Max($i1, $i2) { [Math]::Max($i1, $i2) } if (!$Column) { $Autosize = $true } $values = ProcessValues $valuesCount = @($values).Count if ($valuesCount -eq 1) { $values | Out-Host return } # from some reason the console host doesn't use the last column and writes to new line $consoleWidth = ` if (gi variable:psise -ea silentlycontinue) { $Host.UI.RawUI.BufferSize.Width } else { $Host.UI.RawUI.maxWindowSize.Width -1; } $spaceWidthBetweenCols = 2 # get length of the longest string $values | % -Begin { [int]$maxLength = -1 } -Process { $maxLength = Max $maxLength $_.Length } # get count of columns if not provided if ($Autosize) { $Column = Max (Base ($consoleWidth/($maxLength+$spaceWidthBetweenCols))) 1 $remainingSpace = $consoleWidth - $Column*($maxLength+$spaceWidthBetweenCols); if ($remainingSpace -ge $maxLength) { $Column++ } if ($MaxColumn -and $MaxColumn -lt $Column) { Write-Debug "Columns corrected to $MaxColumn (original: $Column)" $Column = $MaxColumn } } $countOfRows = [Math]::Ceiling($valuesCount / $Column) $maxPossibleLength = Base ($consoleWidth / $Column) # cut too long values, considers count of columns and space between them $values = $values | % { if ($_.length -gt $maxPossibleLength) { $_.Remove($maxPossibleLength-2) + '..' } else { $_ } } #add empty values so that the values fill rectangle (2 dim array) without space if ($Column -gt 1) { $values += (@('') * ($countOfRows*$Column - $valuesCount)) } # in case there is only one item, make it array $values = @($values) <# now we have values like this: 1, 2, 3, 4, 5, 6, 7, '' and we want to display them like this: 1 3 5 7 2 4 6 '' #> $formatString = (1..$Column | %{"{$($_-1),-$maxPossibleLength}"}) -join '' 1..$countOfRows | % { $r = $_-1 $line = @(1..$Column | % { $values[$r + ($_-1)*$countOfRows]} ) $formatString -f $line | Out-Host } } }
PowerShellCorpus/GithubGist/victorvogelpoel_6636754_raw_4db7c63089cc50022761d90a99f265ec325a8af5_compare-directory.ps1
victorvogelpoel_6636754_raw_4db7c63089cc50022761d90a99f265ec325a8af5_compare-directory.ps1
# Compare-Directory.ps1 # Compare files in one or more directories and return file difference results # Victor Vogelpoel <victor.vogelpoel@macaw.nl> # Sept 2013 # # 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. # Compare-Directory -ReferenceDirectory "C:\Compare-Directory\FrontEnd1-Site" -DifferenceDirectory "C:\Compare-Directory\FrontEnd2-Site" function Compare-Directory { [CmdletBinding()] param ( [Parameter(Mandatory=$true, position=0, ValueFromPipelineByPropertyName=$true, HelpMessage="The reference directory to compare one or more difference directories to.")] [System.IO.DirectoryInfo]$ReferenceDirectory, [Parameter(Mandatory=$true, position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="One or more directories to compare to the reference directory.")] [System.IO.DirectoryInfo[]]$DifferenceDirectory, [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Recurse the directories")] [switch]$Recurse, [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Files to exclude from the comparison")] [String[]]$ExcludeFile, [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Directories to exclude from the comparison")] [String[]]$ExcludeDirectory, [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Displays only the characteristics of compared objects that are equal.")] [switch]$ExcludeDifferent, [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Displays characteristics of files that are equal. By default, only characteristics that differ between the reference and difference files are displayed.")] [switch]$IncludeEqual, [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Passes the objects that differed to the pipeline.")] [switch]$PassThru ) begin { function Get-MD5 { [CmdletBinding(SupportsShouldProcess=$false)] param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="file(s) to create hash for")] [Alias("File", "Path", "PSPath", "String")] [ValidateNotNull()] $InputObject ) begin { $cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider] $hashAlgorithm = new-object $cryptoServiceProvider } process { $hashByteArray = "" $item = Get-Item $InputObject -ErrorAction SilentlyContinue if ($item -is [System.IO.DirectoryInfo]) { throw "Cannot create hash for directory" } if ($item) { $InputObject = $item } if ($InputObject -is [System.IO.FileInfo]) { $stream = $null; $hashByteArray = $null try { $stream = $InputObject.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); } finally { if ($stream -ne $null) { $stream.Close(); } } } else { $utf8 = new-object -TypeName "System.Text.UTF8Encoding" $hashByteArray = $hashAlgorithm.ComputeHash($utf8.GetBytes($InputObject.ToString())); } Write-Output ([BitConverter]::ToString($hashByteArray)).Replace("-","") } } function Get-Files { [CmdletBinding(SupportsShouldProcess=$false)] param ( [string]$DirectoryPath, [String[]]$ExcludeFile, [String[]]$ExcludeDirectory, [switch]$Recurse ) $relativeBasenameIndex = $DirectoryPath.ToString().Length # Get the files from the first deploypath # and ADD the MD5 hash for the file as a property # and ADD a filepath relative to the deploypath as a property Get-ChildItem -Path $DirectoryPath -Exclude $ExcludeFile -Recurse:$Recurse | foreach { $hash = "" if (!$_.PSIsContainer) { $hash = Get-MD5 $_ } # Added two new properties to the DirectoryInfo/FileInfo objects $item = $_ | Add-Member -Name "MD5Hash" -MemberType NoteProperty -Value $hash -PassThru | Add-Member -Name "RelativeBaseName" -MemberType NoteProperty -Value ($_.FullName.Substring($relativeBasenameIndex)) -PassThru # Test for directories and files that need to be excluded because of ExcludeDirectory if ($item.PSIsContainer) { $item.RelativeBaseName += "\" } if ($ExcludeDirectory | where { $item.RelativeBaseName -like "\$_\*" }) { Write-Verbose "Ignore item `"$($item.Fullname)`"" } else { Write-Verbose "Adding `"$($item.Fullname)`" to result set" Write-Output $item } } } $referenceDirectoryFiles = Get-Files -DirectoryPath $referenceDirectory -ExcludeFile $ExcludeFile -ExcludeDirectory $ExcludeDirectory -Recurse:$Recurse } process { if ($DifferenceDirectory -and $referenceDirectoryFiles) { foreach($nextPath in $DifferenceDirectory) { $nextDifferenceFiles = Get-Files -DirectoryPath $nextpath -ExcludeFile $ExcludeFile -ExcludeDirectory $ExcludeDirectory -Recurse:$Recurse ################################################### # Compare the contents of the two file/directory arrays and return the results $results = @(Compare-Object -ReferenceObject $referenceDirectoryFiles -DifferenceObject $nextDifferenceFiles -ExcludeDifferent:$ExcludeDifferent -IncludeEqual:$IncludeEqual -PassThru:$PassThru -Property RelativeBaseName, MD5Hash) if (!$PassThru) { foreach ($result in $results) { $path = $ReferenceDirectory $pathFiles = $referenceDirectoryFiles if ($result.SideIndicator -eq "=>") { $path = $nextPath $pathFiles = $nextDifferenceFiles } # Find the original item in the files array $itemPath = (Join-Path $path $result.RelativeBaseName).ToString().TrimEnd('\') $item = $pathFiles | where { $_.fullName -eq $itemPath } $result | Add-Member -Name "Item" -MemberType NoteProperty -Value $item } } Write-Output $results } } } <# .SYNOPSIS Compares a reference directory with one or more difference directories. .DESCRIPTION Compare-Directory compares a reference directory with one ore more difference directories. Files and directories are compared both on filename and contents using a MD5hash. Internally, Compare-Object is used to compare the directories. The behavior and results of Compare-Directory is similar to Compare-Object. .PARAMETER ReferenceDirectory The reference directory to compare one or more difference directories to. .PARAMETER DifferenceDirectory One or more directories to compare to the reference directory. .PARAMETER Recurse Include subdirectories in the comparison. .PARAMETER ExcludeFile File names to exclude from the comparison. .PARAMETER ExcludeDirectory Directory names to exclude from the comparison. Directory names are relative to the Reference of Difference Directory path .PARAMETER ExcludeDifferent Displays only the characteristics of compared files that are equal. .PARAMETER IncludeEqual Displays characteristics of files that are equal. By default, only characteristics that differ between the reference and difference files are displayed. .PARAMETER PassThru Passes the objects that differed to the pipeline. By default, this cmdlet does not generate any output. .EXAMPLE Compare-Directory -reference "D:\TEMP\CompareTest\path1" -difference "D:\TEMP\CompareTest\path2" -ExcludeFile "web.config" -recurse Compares directories "D:\TEMP\CompareTest\path1" and "D:\TEMP\CompareTest\path2" recursively, excluding "web.config" Only differences are shown. Results: RelativeBaseName MD5Hash SideIndicator Item ---------------- ------- ------------- ---- bin\site.dll 87A1E6006C2655252042F16CBD7FB41B => D:\TEMP\CompareTest\path2\bin\site.dll index.html 02BB8A33E1094E547CA41B9E171A267B => D:\TEMP\CompareTest\path2\index.html index.html 20EE266D1B23BCA649FEC8385E5DA09D <= D:\TEMP\CompareTest\path1\index.html web_2.config 5E6B13B107ED7A921AEBF17F4F8FE7AF <= D:\TEMP\CompareTest\path1\web_2.config bin\site.dll 87A1E6006C2655252042F16CBD7FB41B => D:\TEMP\CompareTest\path2\bin\site.dll index.html 02BB8A33E1094E547CA41B9E171A267B => D:\TEMP\CompareTest\path2\index.html index.html 20EE266D1B23BCA649FEC8385E5DA09D <= D:\TEMP\CompareTest\path1\index.html web_2.config 5E6B13B107ED7A921AEBF17F4F8FE7AF <= D:\TEMP\CompareTest\path1\web_2.config .EXAMPLE Compare-Directory -reference "D:\TEMP\CompareTest\path1" -difference "D:\TEMP\CompareTest\path2" -ExcludeFile "web.config" -recurse -IncludeEqual Compares directories "D:\TEMP\CompareTest\path1" and "D:\TEMP\CompareTest\path2" recursively, excluding "web.config". Results include the items that are equal: RelativeBaseName MD5Hash SideIndicator Item ---------------- ------- ------------- ---- bin == D:\TEMP\CompareTest\path1\bin bin\site2.dll 98B68D681A8D40FA943D90588E94D1A9 == D:\TEMP\CompareTest\path1\bin\site2.dll bin\site3.dll 9408C4B29F82260CBBA528342CBAA80F == D:\TEMP\CompareTest\path1\bin\site3.dll bin\site4.dll 0616E1FBE12D468F611F07768D70C2EE == D:\TEMP\CompareTest\path1\bin\site4.dll ... bin\site8.dll 87A1E6006C2655252042F16CBD7FB41B => D:\TEMP\CompareTest\path2\bin\site8.dll index.html 02BB8A33E1094E547CA41B9E171A267B => D:\TEMP\CompareTest\path2\index.html index.html 20EE266D1B23BCA649FEC8385E5DA09D <= D:\TEMP\CompareTest\path1\index.html web_2.config 5E6B13B107ED7A921AEBF17F4F8FE7AF <= D:\TEMP\CompareTest\path1\web_2.config .EXAMPLE Compare-Directory -reference "D:\TEMP\CompareTest\path1" -difference "D:\TEMP\CompareTest\path2" -ExcludeFile "web.config" -recurse -ExcludeDifference Compares directories "D:\TEMP\CompareTest\path1" and "D:\TEMP\CompareTest\path2" recursively, excluding "web.config". Results only include the files that are equal; different files are excluded from the results. .EXAMPLE Compare-Directory -reference "D:\TEMP\CompareTest\path1" -difference "D:\TEMP\CompareTest\path2" -ExcludeFile "web.config" -recurse -Passthru Compares directories "D:\TEMP\CompareTest\path1" and "D:\TEMP\CompareTest\path2" recursively, excluding "web.config" and returns NO comparison results, but the different files themselves! FullName -------- D:\TEMP\CompareTest\path2\bin\site3.dll D:\TEMP\CompareTest\path2\index.html D:\TEMP\CompareTest\path1\index.html D:\TEMP\CompareTest\path1\web_2.config .LINK Compare-Object #> }
PowerShellCorpus/GithubGist/NotMyself_1944957_raw_ae9898129bc470a4d66f8a0113e892063d84f6a6_clean-merged-branches.ps1
NotMyself_1944957_raw_ae9898129bc470a4d66f8a0113e892063d84f6a6_clean-merged-branches.ps1
$dontcare = git fetch origin --prune $branches = git branch -a --merged | ?{$_ -match "remotes\/origin"} | ?{$_ -notmatch "\/master"} | %{$_.Replace("remotes/origin/", "").Trim() } if (-not $branches) { echo "No merged branches detected" exit 0 } echo $branches $title = "Delete Merged Branches" $message = "Do you want to delete the already-merged remote branches displayed above??" $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", ` "Delete the remote branches listed." $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", ` "Leave the branches alone." $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no) $result = $host.ui.PromptForChoice($title, $message, $options, 1) if ($result -eq 1) { exit 0 } $branches | %{ git push origin ":$_" }
PowerShellCorpus/GithubGist/glassdfir_a12cbad63fad91ff90d5_raw_9145dfa58ebd91d345b7897d1f95735df9179577_snippet.ps1
glassdfir_a12cbad63fad91ff90d5_raw_9145dfa58ebd91d345b7897d1f95735df9179577_snippet.ps1
Param( [Parameter(Mandatory=$False)] [String] $Remote ="", [Parameter(Mandatory=$True)] [String] $query ="", [Parameter(Mandatory=$False)] [Switch] $exact = $false ) $ComputerName="LocalHost" If($Remote -ne ""){$ComputerName = $Remote} If($exact) { $searchstring = 'Event[System[EventID=1] and EventData[Data[@Name="Image"]="' + $query +'"]]' $events = Get-WinEvent -LogName Microsoft-Windows-Sysmon/Operational -ComputerName $ComputerName -FilterXPath $searchstring ForEach($event in $events){ $event.TimeCreated.ToString() + "`t" +$query } } Else { $events = get-winevent -LogName microsoft-windows-sysmon/operational -ComputerName $ComputerName|Where-Object { ( $_.id -eq 1)} ForEach($event in $events){ $image = $event |% {(([xml]$_.toxml()).Event.EventData.Data | ? {$_.name -eq "Image" })."#text"} if($image -match $query){ $event.TimeCreated.ToString() + "`t" + $image.ToString() } } }
PowerShellCorpus/GithubGist/ebibibi_2cf0f4206e94b917e4f1_raw_dc11de790b8b7b93203ac90203802d7d1fd2f3ff_runas.ps1
ebibibi_2cf0f4206e94b917e4f1_raw_dc11de790b8b7b93203ac90203802d7d1fd2f3ff_runas.ps1
Param ( [String]$Path = (Get-Location) ) # Elevate Write-Host "Checking for elevation... " -NoNewline $CurrentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent()) if (($CurrentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) -eq $false) { ArgumentList = "-noprofile -noexit -file `"{0}`" -Path `"$Path`"" If ($ValidateOnly) {$ArgumentList = $ArgumentList + " -ValidateOnly"} If ($SkipValidation) {$ArgumentList = $ArgumentList + " -SkipValidation $SkipValidation"} Write-Host "elevating" Start-Process powershell.exe -Verb RunAs -ArgumentList ($ArgumentList -f ($myinvocation.MyCommand.Definition)) Exit }
PowerShellCorpus/GithubGist/sunnyc7_8617526_raw_dc78e4e52a8d58bfd49b7adac303008f5f0bbbf0_ConvertFrom-IISW3CLog.ps1
sunnyc7_8617526_raw_dc78e4e52a8d58bfd49b7adac303008f5f0bbbf0_ConvertFrom-IISW3CLog.ps1
function ConvertFrom-IISW3CLog { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('PSPath')] [string[]] $Path ) process { foreach ($SinglePath in $Path) { $FieldNames = $null $Properties = @{} Get-Content -Path $SinglePath | ForEach-Object { if ($_ -match '^#') { #metadata if ($_ -match '^#(?<k>[^:]+):\s*(?<v>.*)$') { #key value pair if ($Matches.k -eq 'Fields') { $FieldNames = @(-split $Matches.v) } } } else { $FieldValues = @(-split $_) $Properties.Clear() for ($Index = 0; $Index -lt $FieldValues.Length; $Index++) { $Properties[$FieldNames[$Index]] = $FieldValues[$Index] } [pscustomobject]$Properties } } } } }
PowerShellCorpus/GithubGist/Tylerflick_8459808_raw_a8c51eeaf5cd41989416543740f17ed48764816f_WCF%20Client%20Generator.ps1
Tylerflick_8459808_raw_a8c51eeaf5cd41989416543740f17ed48764816f_WCF%20Client%20Generator.ps1
# CHANGE THESE TO COMPLY WITH YOUR LOCAL MACHINE & SERVICE YOU ARE REFERENCING # $linqPadConfig = 'C:\Program Files (x86)\LINQPad4\linqpad.config' $linqPadExtensions = 'PATH TO LINQPAD PLUGINS FOLDER' $servicePath = 'SERVICE PATH' $generatedCsFile = 'GENERATED SERVICE C# FILE NAME' ################################################################################ # DON'T CHANGE THESE # $env:SVCUTIL = 'C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools' $env:CSC = 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319' $env:Path="$env:SVCUTIL;$env:CSC" ###################### cd $linqPadExtensions if(Test-Path $linqPadConfig) { svcutil.exe /mergeConfig /config:$linqPadConfig $servicePath } else { svcutil.exe /config:$linqPadConfig $servicePath } csc /t:library $generatedCsFile
PowerShellCorpus/GithubGist/janegilring_91f174491e498e170981_raw_e8b2de670931bcfefa384dbca5d9233b58da809b_RoyalTS-PSModule-Examples.ps1
janegilring_91f174491e498e170981_raw_e8b2de670931bcfefa384dbca5d9233b58da809b_RoyalTS-PSModule-Examples.ps1
# Import the module $RTSPSModule = Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'code4ward.net\Royal TS V3\RoyalDocument.PowerShell.dll' Import-Module $RTSPSModule # Explore available cmdlets Get-Command -Module RoyalDocument.PowerShell # Create a new RoyalStore in memory $Store = New-RoyalStore -UserName ($env:USERDOMAIN + '\' + $env:USERNAME) # Create the new document $RoyalDocumentPath = Join-Path -Path $env:USERPROFILE -ChildPath ('Documents\' + $env:USERDOMAIN + '.rtsz') $RoyalDocument = New-RoyalDocument -Name $env:USERDOMAIN -FileName $RoyalDocumentPath -Store $Store # Store the new document on disk and close it Out-RoyalDocument -Document $RoyalDocument Close-RoyalDocument -Document $RoyalDocument # Open the document $RoyalDocument = Open-RoyalDocument -FileName $RoyalDocumentPath -Store $store # Create a new folder for storing our demo server connection object $Folder = New-RoyalObject -folder $RoyalDocument -Type RoyalFolder -Name 'PowerShell Magazine' # Create a new RDS Connection $RDS = New-RoyalObject -Folder $Folder -Type RoyalRDSConnection -Name PSMag-SRV01 -Description "Demo server" # Configure the connection URI (hostname) Set-RoyalObjectValue -Object $RDS -Property URI -Value PSMag-SRV01.demo.local # Store the updated document on disk and close it Out-RoyalDocument -Document $RoyalDocument Close-RoyalDocument -Document $RoyalDocument # Open the application to verify the changes $RTSApp = Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'code4ward.net\Royal TS V3\RTS3App.exe' Start-Process -FilePath $RTSApp # Open the document $RoyalDocument = Open-RoyalDocument -FileName $RoyalDocumentPath -Store $store # Store the Remote Desktop connection we want to modify in a variable $RoyalObject = Get-RoyalObjects -Store $store -Name PSMag-SRV01 # Change the properties we want to modify $RoyalObject.Smartsizing = $true $RoyalObject.CredentialFromParent = $true # Store the updated document on disk and close it Out-RoyalDocument -Document $RoyalDocument Close-RoyalDocument -Document $RoyalDocument # Open the application to verify the changes $RTSApp = Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'code4ward.net\Royal TS V3\RTS3App.exe' Start-Process -FilePath $RTSApp
PowerShellCorpus/GithubGist/ao-zkn_3e97b82a116418197d26_raw_07bc953acc9a6a5cb8c786b3fbcd53e942c1c40f_ConvertTo-UsedFileName.ps1
ao-zkn_3e97b82a116418197d26_raw_07bc953acc9a6a5cb8c786b3fbcd53e942c1c40f_ConvertTo-UsedFileName.ps1
# ------------------------------------------------------------------ # Windowsでファイル名に使用できない禁止文字を全角に変換する # 関数名:ConvertTo-UsedFileName # 引数 :FileName ファイル名 # 戻り値:変換後のファイル名 # ------------------------------------------------------------------ function ConvertTo-UsedFileName([String]$FileName){ # 禁止文字(半角記号) $CannotUsedFileName = "\/:*?`"><|" # 禁止文字(全角記号) $UsedFileName = "¥/:*?`”><|" for ($i = 0; $i -lt $UsedFileName.Length; $i++) { $FileName = $FileName.Replace($CannotUsedFileName[$i], $UsedFileName[$i]) } return $FileName }
PowerShellCorpus/GithubGist/tekmaven_041a205276bf4d26e8f9_raw_22a7a126973245cb972ef4fe780e30e5cc762402_Install-MongoDb-On-AppVeyor.ps1
tekmaven_041a205276bf4d26e8f9_raw_22a7a126973245cb972ef4fe780e30e5cc762402_Install-MongoDb-On-AppVeyor.ps1
#Make sure 7za is installed choco install 7zip.commandline # Create mongodb and data directory md $env:temp\mongo\data # Go to mongodb dir Push-Location $env:temp\mongo # Download zipped mongodb binaries to mongodbdir Invoke-WebRequest https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-2.6.5.zip -OutFile mongodb.zip # Extract mongodb zip cmd /c 7za e mongodb.zip # Install mongodb as a windows service cmd /c $env:temp\mongo\mongod.exe --logpath=$env:temp\mongo\log --dbpath=$env:temp\mongo\data\ --smallfiles --install # Sleep as a hack to fix an issue where the service sometimes does not finish installing quickly enough Start-Sleep -Seconds 5 # Start mongodb service net start mongodb # Return to last location, to run the build Pop-Location Write-Host Write-Host "monogdb installation complete"
PowerShellCorpus/GithubGist/botsmack_5878562_raw_dac5e17eca84e11935a0e9ff1169d50f20a666e3_encode.ps1
botsmack_5878562_raw_dac5e17eca84e11935a0e9ff1169d50f20a666e3_encode.ps1
<# I added the optional decomb PowerShell parameter than activates "--decomb" in Handbrake. I was running into interlace issues encoding an animated TV show - Sealab 2021. I don't think you will need it unless you're enoding similar content. For everything else I leave it off ($false) by default. Improved the funcationality of the script to take either a single MKV file or a folder of MKV files. Usage: encode.ps1 [source file] encode.ps1 [source directory] -decomb:$true #> Param( [Parameter(Mandatory = $true, HelpMessage="Please specify an MKV source file or directory.")] [string]$source, [switch]$decomb ) [string]$handbrake = "C:\Program Files\HandBrake\HandBrakeCLI.exe" [string]$mediainfo = "C:\Program Files\MediaInfo\MediaInfo.exe" $script:handbrake_options = @("--markers", "--large-file", "--encoder", "x264", "--encopts", "vbv-maxrate=25000:vbv-bufsize=31250:ratetol=inf", "--crop", "0:0:0:0", "--strict-anamorphic") if ($decomb) { $script:handbrake_options += "--decomb" } function Encode-File { Param( [Parameter(Mandatory = $true)] [string]$source_file ) [string]$output_file = [io.path]::ChangeExtension($source_file, '.mp4') [int]$width = & $mediainfo --Inform="Video;%Width%" $source_file [int]$height = & $mediainfo --Inform="Video;%Height%" $source_file if (($width -gt 1280) -or ($height -gt 720)) { $max_bitrate = "6500" } elseif (($width -gt 720) -or ($height -gt 576)) { $max_bitrate = "4000" } else { $max_bitrate = "2200" } [int]$min_bitrate = $max_bitrate / 2 [decimal]$bitrate = & $mediainfo --Inform="Video;%BitRate%" $source_file if (! $bitrate) { $bitrate = & $mediainfo --Inform="General;%OverallBitRate%" $source_file $bitrate = $bitrate / 10 * 9 } if ($bitrate) { $bitrate = [math]::floor($bitrate / 5 * 4 / 100000) * 100 if ($bitrate -gt $max_bitrate) { $bitrate = $max_bitrate } elseif ($bitrate -lt $min_bitrate) { $bitrate = $min_bitrate } } else { $bitrate = $min_bitrate } $script:handbrake_options += "--vb", $bitrate [decimal]$frame_rate = & $mediainfo --Inform="Video;%FrameRate_Original%" $source_file if (! $frame_rate) { $frame_rate = & $mediainfo --Inform="Video;%FrameRate%" $source_file } if ($frame_rate -eq 29.970) { $script:handbrake_options += "--rate", 23.976, "--detelecine" } else { $script:handbrake_options += "--rate", 30, "--pfr" } [int]$channels = (& $mediainfo --Inform="Audio;%Channels%" $source_file) -replace "[^0-9].*" if ($channels -gt 2) { $script:handbrake_options += "--aencoder", "faac,copy:ac3" } elseif (((& $mediainfo --Inform="General;%Audio_Format_List%" $source_file) -replace " /.*") -eq "AAC") { $script:handbrake_options += "--aencoder", "copy:aac" } & $handbrake $script:handbrake_options --input $source_file --output $output_file } if (Test-Path $source -PathType Container) { $files = (Get-ChildItem "$source\*" -include *.mkv) if ($files.length -ge 1) { ForEach ($file in $files) { [string]$mp4file = [io.path]::ChangeExtension($file, ".mp4") Write-Host $mp4file if (!(Test-Path $mp4file)) { Write-Host "`n*******************************************************************************" Write-Host "Encoding $file" -foreground green Write-Host "*******************************************************************************`n" Encode-File $file } else { Write-Host "$mp4file already exists" } } } else { Write-Host "`n*******************************************************************************" Write-Host "No files are available to encode" -foreground yellow Write-Host "*******************************************************************************`n" } } else { Encode-File $source }
PowerShellCorpus/GithubGist/mswietlicki_2369bdb303682ca243fc_raw_a1b1b08c6ee239166fdb8ed2a41b4d6a29d33e30_gistfile1.ps1
mswietlicki_2369bdb303682ca243fc_raw_a1b1b08c6ee239166fdb8ed2a41b4d6a29d33e30_gistfile1.ps1
Dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase
PowerShellCorpus/GithubGist/morgansimonsen_8040285_raw_1d8e5bb1337b3e835541be5c8ce53c517ad4a8c4_gistfile1.ps1
morgansimonsen_8040285_raw_1d8e5bb1337b3e835541be5c8ce53c517ad4a8c4_gistfile1.ps1
get-qadobject -SearchRoot <canonical name of domain> ´ -ldapFilter '(&(objectClass=group)(mailnickname=*))' ´ -service <DC FQDN> -SizeLimit 0 | Set-QADObject -ObjectAttributes ´ @{adminDisplayName='';´ altRecipient='';´ authOrig='';´ autoReplyMessage='';´ deletedItemFlags='';´ delivContLength='';´ deliverAndRedirect='';´ displayNamePrintable='';´ dLMemDefault='';´ dLMemRejectPerms='';´ dLMemSubmitPerms='';´ extensionAttribute1='';´ extensionAttribute10='';´ extensionAttribute11='';´ extensionAttribute12='';´ extensionAttribute13='';´ extensionAttribute14='';´ extensionAttribute15='';´ extensionAttribute2='';´ extensionAttribute3='';´ extensionAttribute4='';´ extensionAttribute5='';´ extensionAttribute6='';´ extensionAttribute7='';´ extensionAttribute8='';´ extensionAttribute9='';´ folderPathname='';´ garbageCollPeriod='';´ homeMDB='';´ homeMTA='';´ internetEncoding='';´ legacyExchangeDN='';´ mail=''; mailNickname='';´ mAPIRecipient='';´ mDBOverHardQuotaLimit='';´ mDBOverQuotaLimit='';´ mDBStorageQuota='';´ mDBUseDefaults='';´ msExchADCGlobalNames='';´ msExchControllingZone='';´ msExchExpansionServerName='';´ msExchFBURL='';´ msExchHideFromAddressLists='';´ msExchHomeServerName='';´ msExchMailboxGuid='';´ msExchMailboxSecurityDescriptor='';´ msExchPoliciesExcluded='';´ msExchPoliciesIncluded='';´ msExchRecipLimit='';´ msExchResourceGUID='';´ protocolSettings='';´ proxyAddresses='';´ publicDelegates='';´ securityProtocol='';´ showInAddressBook='';´ submissionContLength='';´ targetAddress='';´ textEncodedORAddress='';´ unauthOrig=''} ´ -service <DC FQDN>
PowerShellCorpus/GithubGist/forsythetony_3ac8f04fe0af913f23b1_raw_a37d22a605ba5605833ade15d015a126327363fe_newConvertVideos.ps1
forsythetony_3ac8f04fe0af913f23b1_raw_a37d22a605ba5605833ade15d015a126327363fe_newConvertVideos.ps1
# # Function Name: getUserData # # Inputs: None # # Output: # -$userData: A dictionary containing the entries... # - "start" -> A dateTime object that marks the start of the date range # - "end" -> A dateTime object that marks the end of the date range # - "folderPath"-> A path (string) object containing the folderPath to the folder containing the subfolder "KinectData" # # Purpose: To gather input from the user to know which videos this script should convert # function getUserData { Do { $rootPath = Read-Host "Enter the path to the folder containing the dated folders containing the video files" # $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 $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) $converterLocation = Read-Host "To use the correct location for ffmpeg please choose your machine...Echo [0] , Test-Machine[1] , Other[2]" $converterLocation = checkConverterLocation $converterLocation $userData = @{ "start" = $startDate; "end" = $endDate; "folderPath" = $folderPath; "ffmpegPath" = $converterLocation; } return $userData } function checkConverterLocation($locationOption) { Switch ($locationOption) { 0 { $location = "C:\Program Files\ffmpeg\bin\ffmpeg.exe" } 1 { $location = "C:\Users\arfv2b\Downloads\ffmpeg\ffmpeg-20140609-git-958168d-win64-static\bin\ffmpeg.exe" } default { $location = Read-Host "Enter the location to use" while((Test-Path $location) -eq $null) { $location = Read-Host "Invalid path entered. Please try that again." } } } return $location } # # Function Name: checkUserIDString # # Inputs: # - $string: A string containing the user ID that is to be validated # # Output: # - $package: A dictionary with the following entries... # - "isValid" -> A boolean value indicating whether the ID entered was a valid ID # - "path" -> A string that contains the original string if it is a valid ID or $null if it is not. # - "message" -> A message describing the output. Error message or success message. # # Purpose: The purpose of this function is to check whether the user inputed ID value is a number of the right lenght or if it is the # string 'All' which would indicate the function would be looking through all ID's # 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 Name: checkDateString # # Inputs: # -$string: A string containing the date that whose format will be checked. # # Output: # -$parseString: A string that shows the format of the date string that was passed into the function. # # Purpose: To determine the format of the date string so that the ParseExact function knows what kind of # date to expect. # 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 Name: updateFilesInRange # # Inputs: # -$range: A dictionary containing the following entries... # - "start" -> A dateTime object that marks the start of the date range # - "end" -> A dateTime object that marks the end of the date range # - "folderPath"-> A path (string) object containing the folderPath to the folder containing the subfolder "KinectData" # Output: None # # Purpose: To convert videos within the specified date range and folder from .avi's to .mp4's # function updateFilesInRange($range) { $pathToFiles = $range.folderPath # $theChild = Get-ChildItem -Path $pathToFiles | Where {$_.PSIsContainer -eq $true -and $_.Name -eq "KinectData"} sortedFileConversion $pathToFiles $range } # # Function Name: extractDateFromFolder # # Inputs: # -$folderName: A string containing the name of the folder # # Output: # -$dateObject: A date object built from the date specified in the string $folderName which was passed into the function. # # Purpose: # To convert the folder name, which is a basic string object, into a date object which can be used for comparisons with # other date objects. # function extractDateFromFolder($folderName) { $dateTokens = $folderName -split "_" if ($dateTokens.Count -ne 3) { return $null } $thirdToken = $dateTokens[2]; if ($thirdToken.length -eq 4) { $formatString = "MM/dd/yyyy" } elseif ($thirdToken.length -eq 2) { $formatString = "MM/dd/yy" } else { return $null } $dateString = ($dateTokens[0] + "/" + $dateTokens[1] + "/" + $dateTokens[2]) $dateObject = [dateTime]::ParseExact($dateString, $formatString , $null) # Write-Host $dateObject return $dateObject } function extractDateFromFolder2($folderName) { $dateTokens = $folderName -split "_" if ($dateTokens.Count -ne 3) { return $null } $thirdToken = $dateTokens[2]; if ($thirdToken.length -eq 4) { $formatString = "MM/dd/yyyy" } elseif ($thirdToken.length -eq 2) { $formatString = "MM/dd/yy" } else { return $null } $dateString = ($dateTokens[0] + "/" + $dateTokens[1] + "/" + $dateTokens[2]) $dateObject = [dateTime]::ParseExact($dateString, $formatString , $null) # Write-Host $dateObject return $dateObject } # # Function Name: extractDate # # Inputs: # -$path: A string containing the name of the file from which a date can be extracted # # Output: # -$dateObject: A dateTime object built from the string that was passed into the function # # Purpose: # To convert the name of a file into a date which can be used for comparisons. # 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) return $dateObject } function sortedFileConversion($path, $range) { $foldersArray = @() Get-ChildItem -Path $path | Where-Object {$_.PSIsContainer -eq $true} | ForEach-Object { $fullPath = $_.FullName $name = $_.Name $date = extractDateFromFolder2 $name $props = @{ Path = $fullPath Name = $name Date = $date } $theObject = New-Object PSObject -Property $props <## Write-Host ("The range start is " + $range.start) Write-Host ("The range end is " + $range.end) Write-Host ("The folder's date is " + $date) Write-Host ("The path is " + $path) ##> if($date -ge $range.start -and $date -le $range.end) { $foldersArray += $theObject } } $foldersArray | Sort-Object {$_.Date} -Descending | ForEach-Object { Get-ChildItem -Path $_.Path -Recurse | Where-Object {$_.PSIsContainer -eq $false -and $_.Extension -eq ".avi"} | ForEach-Object { $existsBool = testIfVideoExists $_ if($existsBool -eq $true) { $existsMessage = ("The file at path " + $_.FullName + " already exists, will not convert this file.") Write-Host $existsMessage } else { startConvertProcessOnVideo $_ $range } } } } function testIfVideoExists($path) { $newName = [io.path]::ChangeExtension($path.FullName, '.mp4') $existsBool = Test-Path $newName return $existsBool } function startConvertProcessOnVideo($path, $range) { $newVideo = [io.path]::ChangeExtension($path.FullName, '.mp4') $ArgumentList = '-i "{0}" -an -b:v 64k -bufsize 64k -vcodec libx264 -pix_fmt yuv420p "{1}"' -f $path.FullName, $newVideo; $convertMessage = ("Converting video with argument list " + $ArgumentList) Write-Host $convertMessage Start-Process -FilePath $range.ffmpegPath -ArgumentList $ArgumentList -Wait -NoNewWindow; $error[0]|format-list -force } # Main program $userData = getUserData Write-Host ("Start Date: " + $userData.start) Write-Host ("End Date: " + $userData.end) Write-Host ("Folder path: " + $userData.folderPath) updateFilesInRange $userData <## $testPath = "C:\Users\arfv2b\Desktop\testingCopies\testing3\KinectData" $testPath2 = "\\echo\mcp\100\KinectData" getFoldersArray $testPath ##>
PowerShellCorpus/GithubGist/sunnyone_7875686_raw_030987783996e86ecf43a67d62733cbc01f111ee_PrintExceptionSecondChance.ps1
sunnyone_7875686_raw_030987783996e86ecf43a67d62733cbc01f111ee_PrintExceptionSecondChance.ps1
param($Command) New-DbgSession -command $Command Invoke-DbgCommand sxe ld clr Send-DbgGo # to clr loaded Load-DbgExtension sos clr # .loadby sos clr Send-DbgGo # to CorExeMain Send-DbgGo # to go! # app crashes Invoke-DbgCommand "!pe" Invoke-DbgCommand "!clrstack" Exit-DbgSession
PowerShellCorpus/GithubGist/andyb5051_0380694726d6ade84809_raw_9f2002d73a93f2d7a4ac19f03b178269ea077c91_Boxstarter-Script.ps1
andyb5051_0380694726d6ade84809_raw_9f2002d73a93f2d7a4ac19f03b178269ea077c91_Boxstarter-Script.ps1
# http://boxstarter.org/package/url? # It's nice to be able to browse NuGet files if necessary cinstm NugetPackageExplorer # If we're doing web development, we need a few browsers cinstm google-chrome-x64 cinstm Firefox # Don't quite know why this is important, but I'll install silverlight and java runtime anyways cinstm Silverlight cinstm javaruntime # Gotta have Fiddler cinstm fiddler4 # Editors and merge tools cinstm notepadplusplus.install cinstm nano cinst sublimetext3 # Without Git, we might as well go home. cinstm poshgit cinstm git-credential-winstore -Version 1.2.0.0 # Life sux without Visual Studio and the awesome extensions cinstm visualstudio2013expressweb # Get rid of upper case menu in Visual Studio Set-ItemProperty -Path HKCU:\Software\Microsoft\VisualStudio\11.0\General -Name SuppressUppercaseConversion -Type DWord -Value 1 # Run Visual Studio Update if((Get-Item "$($Boxstarter.programFiles86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe").VersionInfo.ProductVersion -lt "11.0.60115.1") { if(Test-PendingReboot){Invoke-Reboot} Install-ChocolateyPackage 'vs update 2 ctp2' 'exe' '/passive /norestart' 'http://download.microsoft.com/download/8/9/3/89372D24-6707-4587-A7F0-10A29EECA317/vsupdate_KB2707250.exe' } # Fix SSH-Agent error by adding the bin directory to the `Path` environment variable $env:PSModulePath = $env:PSModulePath + ";C:\Program Files (x86)\Git\bin" # Markdown is how documentation becomes awesomenes # Unfortunately I'm installing this at the end because it doesn't seem to work unattended... it requires the user to press "ok" cinstm MarkdownPad2 -installargs "/exelang 1033" # VPN Client # cinstm ShrewSoftVpn # Sql Server cinst SqlServer2012Express #optional packages cinstm chocolateygui cinstm paint.net cinstm nodejs.install cinstm virtualbox cinstm putty cinstm git.install cinstm wireshark cinstm vagrant cinstm puppet cinstm linqpad4 cinstm java.jdk cinstm php cinstm google-chrome-x64 cinstm virtualbox.extensionpack cinstm adblockpluschrom
PowerShellCorpus/GithubGist/crancker_5040394_raw_a98c5e046b65f2e175fea1a286bb83db5c414360_IPScanner.ps1
crancker_5040394_raw_a98c5e046b65f2e175fea1a286bb83db5c414360_IPScanner.ps1
if (test-path ./output.txt){ remove-item ./output.txt } $start = read-host "Start IP" $finish = read-host "End IP" $ip1 = ([System.Net.IPAddress]$start).GetAddressBytes() [Array]::Reverse($ip1) $ip1 = ([System.Net.IPAddress]($ip1 -join '.')).Address $ip2 = ([System.Net.IPAddress]$finish).GetAddressBytes() [Array]::Reverse($ip2) $ip2 = ([System.Net.IPAddress]($ip2 -join '.')).Address for ($x=$ip1; $x -le $ip2; $x++) { $ip_ = ([System.Net.IPAddress]$x).GetAddressBytes() [Array]::Reverse($ip_) $iprange = $ip_ -join '.' foreach ($ip in $iprange){ $ip if (Test-Connection -comp $ip -count 1 -quiet){ $result = [System.Net.Dns]::GetHostEntry($ip) $hostname = [String]$result.HostName $output = "$ip $hostname Reachable" >> ./output.txt Write-host "$ip $hostname Reachable" } else{ } } } notepad ./output.txt
PowerShellCorpus/GithubGist/MattHoneycutt_97342b8f79e1cc378d14_raw_4e30d78dfd65b6952eb1853e91cd6eb4fb60c8b4_gistfile1.ps1
MattHoneycutt_97342b8f79e1cc378d14_raw_4e30d78dfd65b6952eb1853e91cd6eb4fb60c8b4_gistfile1.ps1
$StandardGitIgnoreFile = Resolve-Path ".\std.gitignore" function Git-InitStandard() { git init . Copy-Item $StandardGitIgnoreFile ".\.gitignore" Write-Host "Added standard gitignore file." } <# This assumes you have a file next to your Powershell profile (where this function is defined) named std.gitignore. Here's what's in mine: #ignore thumbnails created by windows Thumbs.db #Ignore files build by Visual Studio *.obj *.exe *.pdb *.user *.aps *.pch *.vspscc *_i.c *_p.c *.ncb *.suo *.tlb *.tlh *.bak *.cache *.ilk *.log [Bb]in [Dd]ebug*/ *.lib *.sbr obj/ [Rr]elease*/ _ReSharper*/ [Tt]est[Rr]esult* packages/**/ #>
PowerShellCorpus/GithubGist/sweeneyrobb_6504243_raw_d55369692832a9cf50f6ae31bf2d2103d55d2a89_Select-FileDialog.ps1
sweeneyrobb_6504243_raw_d55369692832a9cf50f6ae31bf2d2103d55d2a89_Select-FileDialog.ps1
function Select-FileDialog { param([string]$Title, [string]$Directory, [string]$Filter="All Files (*.*)|*.*" ) [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null $objForm = New-Object System.Windows.Forms.OpenFileDialog $objForm.InitialDirectory = $Directory $objForm.Filter = $Filter $objForm.Title = $Title $Show = $objForm.ShowDialog() if ($Show -eq "OK") { Return $objForm.FileName } else { Write-Error "Operation cancelled by user." } }
PowerShellCorpus/GithubGist/tetsuh_8729123_raw_bdc6b61e6d5b90526d4e78d335c3c7c621846cc9_svnlog2loc.ps1
tetsuh_8729123_raw_bdc6b61e6d5b90526d4e78d335c3c7c621846cc9_svnlog2loc.ps1
###################################################################################### # # svnlog2loc.ps1 # svnのログを解析し、開発種別を表す特定キーワード別の開発規模(行数)を取得する。 # # USAGE: # svnlog2loc.ps1 <リポジトリパス> <開始レビジョン> <終了レビジョン> <出力ファイル> # 例) # svnlog2loc.ps1 file:///usr/local/svn/a25Project 2000 HEAD a25_SVN_LOC.csv # # History: # 2012.11.26 初版 Iwasaki written by perl # 2013.07.16 PowerShellへ移植 # 2014.01.31 公開用整理 # ###################################################################################### Param( [Parameter(Mandatory=$true,HelpMessage="リポジトリパスを入力してください")][string]$repospath, [Parameter(Mandatory=$true,HelpMessage="開始レビジョンを入力してください")][string]$startrev, [Parameter(Mandatory=$true,HelpMessage="終了レビジョンを入力してください")][string]$endrev, [Parameter(Mandatory=$true,HelpMessage="出力ファイル名を入力してください")][string]$outfile = "outfile.txt" ) ###################################################################################### # 指定リビジョンの差分情報から追加行数を数えて返す関数 ###################################################################################### function countloc($rev) { $total_LOC = 0; # 差分情報をパースする為の正規表現パターン [regex]$filename_regex = "^Index: (.*)$" [regex]$suffix_regex = "(\.cpp$)|(\.c$)|(\.hpp$)|(\.h$)|(\.rc$)|(\.rc2$)" [regex]$incr_regex = "^\+" # 追加行のパターン [regex]$whiteline_regex = "^\+\s*$" # 追加行だけど空行のパターン # テンポラリファイルハンドル、ファイル名取得 $tempfile = [IO.Path]::GetTempFileName() # 指定リビジョンの差分情報をテンポラリファイルに書き出す # `svn diff -c $r $repospath > $fname`; Start-Process -FilePath svn -ArgumentList "diff -c${rev} ${repospath}" -RedirectStandardOutput $tempfile -NoNewWindow -Wait #-------------------------------------------------------------------------- # 書き出した差分情報を取り込みながらパースして行数カウントを行っていく # # foreach でも良いが元の Perl スクリプトが $_ 前提コードだったので雰囲気を合わせるために ForEach-Object を使う # Get-Content $tempfile -Encoding UTF8 -ErrorAction Stop | ForEach-Object { # Index から始まるファイル名の行を引っかけて行数カウントするかどうかのフラグをセットする if ($_ -cmatch $filename_regex) { # ファイル名の拡張子をチェックする # PowerShell では \1 は $Matches[1] を使う if ($Matches[1] -match $suffix_regex) { $stat_flag = $TRUE; } else { $stat_flag = $FALSE; } } # セットした行数カウントフラグに基づいて "+" 行をカウントする # ただし、空行はカウントから除外する if ($stat_flag -eq $TRUE) { if (($_ -match $incr_regex) -and ($_ -notmatch $whiteline_regex)) { $total_LOC++ } } } # for debug #echo "countloc : rev = $rev, LOC = $total_LOC" # テンポラリファイルの削除 Remove-Item $tempfile return $total_LOC } ###################################################################################### # main ###################################################################################### # ログ中に書いたキーワードの正規表現 # ここでは S0012103-ISS という開発種別コードを表すキーワードパターンをセットしている [regex]$MET_regex = "[SE]\d\d\d\d\d\d-[A-Z][A-Z]*" # テンポラリファイルハンドル、ファイル名取得 $tempfile = [IO.Path]::GetTempFileName() # 指定リビジョンのコミットログをテンポラリファイルに書き出す #`svn log -r $startrev:$endrev $repospath > $fname_log`; Start-Process -FilePath svn -ArgumentList "log --xml -r${startrev}:${endrev} ${repospath}" -RedirectStandardOutput $tempfile -NoNewWindow -Wait # 書き出したコミットログを XML として取り込む [xml]$svndoc = Get-Content $tempfile -Encoding UTF8 -ErrorAction Stop # テンポラリファイルの削除 Remove-Item $tempfile #-------------------------------------------------------------------------- # コミットログを辿りながらログ情報の修正とLOCエントリの追加を行う # # 元のスクリプトでは新規に連想配列を生成していたが、 # 本スクリプトでは取り込んだ svn log の XML 構造を流用して LOC エントリを追加する方式とした # foreach($commit in $svndoc.log.logentry) { # コミット日付をフォーマットして .date に再代入する $commit.date = ([datetime]$commit.date).ToString("yyyy/MM/dd HH:mm:ss") # METコードパターンを抽出して .msg に再代入する $commit.msg = [string]($MET_regex.Matches($commit.msg) | ForEach-Object {$_.Value}) # LOCエレメントを追加 [void]$commit.AppendChild($svndoc.CreateElement("LOC")) # LOCを計算して代入する $commit.loc = [string](countloc $commit.revision) } # 出来上がった svndoc を CSV ファイルに出力する echo $svndoc.log.logentry | Export-Csv $outfile -Force -Encoding UTF8 -NoTypeInformation exit
PowerShellCorpus/GithubGist/trondhindenes_faeb6c1212f4a3e2457c_raw_83d29d528be052a607a8b45fc571f4de731c3f79_publish-SMAv2.ps1
trondhindenes_faeb6c1212f4a3e2457c_raw_83d29d528be052a607a8b45fc571f4de731c3f79_publish-SMAv2.ps1
Function Process-RunbookFolder { Param ( $Path, [switch]$recurse ) $allwfs = get-childitem -Path $Path -Recurse:$recurse $Global:referencelist = New-Object System.Collections.ArrayList [System.Collections.ArrayList]$Global:ToProcessList = $allwfs | select -ExpandProperty Fullname $Global:DoneProcessList = New-Object System.Collections.ArrayList foreach ($wf in $ToProcessList) { #Validate-RunbookFile -path $wf.FullName -erroraction Stop Get-RunbookReference -path $wf Process-RunbookFile -path $wf -basepath $Path -recurse:$recurse } #get-variable processlist -Scope global | Remove-Variable } Function Get-RunbookReference { Param ($path) $ThisWf = get-content $path -Raw $ThisWfSB = [scriptblock]::Create($ThisWf) #$ThisWfAST = $ThisWfSB.Ast $TokenizedWF = [System.Management.Automation.PSParser]::Tokenize($ThisWfSB,[ref]$null) $referencedCommands = $TokenizedWF | where {$_.Type -eq "Command"} | select -ExpandProperty "Content" $myobj = "" |Select Fullname, ReferencedRunbooks $myobj.Fullname =$path $myobj.ReferencedRunbooks = $referencedCommands $Global:referencelist += $myobj; $myobj = $null } Function Process-RunbookFile { Param ($path, $basepath, [switch]$recurse) $path = get-item $path if ($DoneProcessList -contains ($path.FullName)) { Write-Verbose "SKIPPING: Already processed runbook $($path.BaseName)" return } Write-Verbose "PARSING: Runbook $($path.BaseName)" #Parse to find wfs this one depends on, and process $ThisWf = get-content $path -Raw $ThisWfSB = [scriptblock]::Create($ThisWf) #$ThisWfAST = $ThisWfSB.Ast $TokenizedWF = [System.Management.Automation.PSParser]::Tokenize($ThisWfSB,[ref]$null) $referencedCommands = $TokenizedWF | where {$_.TYpe -eq "Command"} foreach ($referencedCommand in $referencedCommands) { $runbookpath = get-childitem -Path $basepath -Recurse:$recurse |where {$_.BaseName -eq $referencedCommand.Content} if ($runbookpath) { Write-Verbose "REFERENCE: $($path.BaseName)--> $($referencedCommand.content)" Process-RunbookFile -path $runbookpath.FullName } } #WHen all referenced runbooks are imported, import this one Write-Verbose "PUBLISH: Publishing runbook $($path.BaseName)" $Global:DoneProcessList += $path.FullName } Process-RunbookFolder -Path "D:\trond.hindenes\Desktop\wftest"
PowerShellCorpus/GithubGist/yan-shuai_d60f3fbec3d17656a7a4_raw_9c70ed2421774aee3c6695a53acf1c2202c5b9e5_basics.ps1
yan-shuai_d60f3fbec3d17656a7a4_raw_9c70ed2421774aee3c6695a53acf1c2202c5b9e5_basics.ps1
Clear-Host Set-Variable -Name var -Value 100 # $var = 100 $var Get-Variable var Clear-Variable -Name var $var Remove-Variable -Name var Get-Variable var "I just want to say 'Hello World', OK? " "Plural`bsight" "Plural`nsight" # new line "Plural`t`nsight" $heretext = @" some some some ablankline above "@ $items = (Get-ChildItem).Count $loc = Get-Location "There are $`items items in the folder `@loc" [string]::Format("There are {0} items", $items) "There are {0} items." -f $items "There are {0} items in the location {1}." -f $items, $loc "{0:0.00}" -f 0.1234 # 0.12 # Wildcards "Pluralsight" -like "Plural" "Pluralsight" -like "?luralsight" # true "Pluralsight" -like "Plural*[s-v]" # ends with a char between s and v # Regular expressions "888-368-1240" -match "[1-9]{3}-[0-9]{3}-[0-9]{4}" # Arrays $array = "arcane", "code" $array[0] $array[1] $array $array.GetType() # object[] $array = "robert", "cain" # update $array[0] = "Plural" $array[1] = "sight" $array = @("plural", "sight") # formal array creation syntax $array = @() # empty array $array = 1..5 # 1 2 3 4 5 $numbers = 1, 42, 256 $numbers -contains 42 # true $numbers -notcontains 99 # true # Hash Table #hash = @{"key" = "value"; "Pluralsight" = "pluralsight.com"; "Arcane code" = "arcanecode.com"} $hash $hash["Pluralsight"] # pluralsight.com $hash."Pluralsight" # pluralsight.com $mykey = "Pluralsight" $hash.$mykey # pluralsight.com $hash.$($mykey) # evaluating as an expression $hash.$("Plural" + "sight") # pluralsight.com $hash $hash["Top Gear"] = "topgear.com" # add value $hash.Remove("Arcane Code") # Remove $hash.Contains("Top Gear") $hash.Contains("Arcane Code") $hash.ContainsValue("pluralsight.com") $hash.ContainsValue("arcanecode.com") $hash.Keys $hash.Values # Automatic Variables $true $false $NULL $pwd $Home $host $PID $PSVersionTable $_ #current object Get-ChildItem | Where-Object {$_.Name -like "*.ps1"} # Branching $var = 2 if ($var -eq 1) { Clear-Host "If branch" } else { Clear-Host "else branch" } $var = 42 switch ($var) { 41 {"Forty one"; break} 42 {"Forty two"; break} default {"default"} } switch(1,2,3) { 1 {"one"} 2 {"two"} 3 {"three"} default {"zero"} } # one two three switch -casesensitive ("Pluralsight") { "" } switch -Wildcard ("Pluralsight") { } # Looping # while $i = 1 while($i -le 5) { "`$i =$i" $i = $i + 1 } # do ... while $i = 1 do { "`$i = $i" $i++ } while($i -le 5) # do ... until $i = 1 do { $i++ } until ($i -gt 5) # for for ($f = 0; $f -le 5; $f++) { "`$f = $f" } # Iterating over a collection $array = 11,12,14,15,13 for($i = 0; $i -lt $array.Length; $i++) { $array[$i] } foreach ($item in $array) { "`$item = $item" } foreach ($file in Get-ChildItem) { $file.Name if ($file.Name -like "") { contine # break } } # Script Blocks $cool = {Clear-Host; "Powershell and bowties are cool."} $cool # doesn't run it & $cool # to run it $ { Clear-Host; "xxx" } $value = { 41 + 1 } 1 + &$value Write-Host "Pluralsight" $value = { return 42; Write-Host "Pluralsight is cool" } &$value # 42 # args collection $args[0] $args[1] $qa = { param ($question, $answer) Write-Host "here is your question: $question The answer is $answer" } &$qa "What else is cool?" "Bowties" &$qa -question "What else is cool?" -answer "Bowties" &$qa -answer "Bowties" -question "What else is cool?" $qa = { param ($question, $answer = Default value") Write-Host "here is your question: $question The answer is $answer" } $math = { param ([int] $x, [int] $y) return $x * $y } &$math 3 11 # Pipeline enabling a block $onlyCoolFiles = { process { if ($_.Name -like "*.ps1") { return $_.Name } } } # Programming Powershell # functions function Get-Fullname($filename, $lastname) { Write-Host($filename + " " + $lastname) } Get-Fullname "Arcane" "Code" function Set-FVar([ref] $myparam) { $myparam.Value = 33 } $fvar = 42 "fvar before: $fvar" Set-FVar([ref] $fvar) "fvar after: $fvar" # Error handling function divver($enum, $denom) { Write-Host "Divver begin" $result = $enum / $denom Write-Host "Result: $result" Write-Host "Divver done." trap { Write-Host "Oh NO! An error has occured!!!" Write-Host $_.ErrorID Write-Host $_.Exception.Message break # or contine } } divver 10 0 function divver($enum, $denom) { trap [System.DivideByZeroExeption] { Write-Host "Hey, chowderhead, you can't divide by zero" contine } trap { Write-Host "Oh NO! An error has occured!!!" Write-Host $_.ErrorID Write-Host $_.Exception.Message break # or contine } } # Working with files Set-Location "C:\PS\01 - Intro" Get-ChildItem "?.txt" Get-Content "a.txt" $a = Get-Content "a.txt" $a.GetType() $separator = [System.Environment]::NewLine $all = [string]::Join($separator, $a) $all Get-Process | Export-Csv "Processes.csv" $header = "__NounName", "Name", "Handles", "VM" $processes = Import-Csv "Processes.csv" -Header $header # XML files $courseTemplate = @" <courses version="1.0"> <course> <name></name> <level></level> </course> </courses> "@ $courseTemplate | Out-File "C:\PS\01 - Intro\PluralsightCourses.xml" # $courseXml = New-Object xml $courseXml.Load("C:\PS\01 - Intro\Pluralsight.xml")
PowerShellCorpus/GithubGist/totomz_4d033fa1b991504a4e31_raw_b1627b2efaacc45f629691e8a5fb9b04a6819b98_gistfile1.ps1
totomz_4d033fa1b991504a4e31_raw_b1627b2efaacc45f629691e8a5fb9b04a6819b98_gistfile1.ps1
$gscript = "test-script/startup.ps1";Invoke-Expression $(Invoke-RestMethod -Uri $("https://storage-download.googleapis.com/"+$gscript+"?access_token=" + $($(Invoke-RestMethod -Uri "http://metadata/computeMetadata/v1/instance/service-accounts/default/token" -Headers @{"Metadata-Flavor"="Google"}).access_token)));
PowerShellCorpus/GithubGist/lantrix_97bc8f3d494681652ba8_raw_80faea164a66706f944fdd58dfbbf67f7d5b6846_newinstance.ps1
lantrix_97bc8f3d494681652ba8_raw_80faea164a66706f944fdd58dfbbf67f7d5b6846_newinstance.ps1
#setup variables $ami = "ami-e95c31d3" #public Windows server 2012 R2 $subnet = "subnet-e1a4f488" #VPC Subnet for instance $group = "sg-e5f3e889" #whatever security group $folder = 'C:\Users\me\OneDrive' $allVolumesAvailable = $False $readyCount = 0 $maxRetries = 20 $sleepBetweenChecks = 10 $Retries = 0 #Create instance try { $instance = New-EC2Instance -ImageId $ami -KeyName MyKey -InstanceType t2.small -SubnetId $subnet } catch { throw "Need to have instance created before continuing" } write-host "New Instance: $($instance.Instances.InstanceId)" write-host "New Instance: $($instance.Instances.PrivateIpAddress)" #Wait for Instance to be running while ((Get-EC2InstanceStatus -InstanceIds $instance.Instances.InstanceId).InstanceState.Name.Value -ne "running") { write-host "Waiting for instance to be running" sleep $sleepBetweenChecks } #Create Volums $newVolumes = @() $vol1 = New-EC2Volume -VolumeType standard -Size 1 -AvailabilityZone ap-southeast-2a $newVolumes += $vol1 $vol2 = New-EC2Volume -VolumeType standard -Size 1 -AvailabilityZone ap-southeast-2a $newVolumes += $vol2 $vol3 = New-EC2Volume -VolumeType standard -Size 1 -AvailabilityZone ap-southeast-2a $newVolumes += $vol3 #Wait for Volumes to be available before attaching #If they have only just been created we will have to wait for them to be completed ('available'). $totalVolumes = $newVolumes.Count while(($readyCount -lt $totalVolumes) -and ($Retries -lt $maxRetries)){ Write-Host "Determining if new volumes are ready to be attached" foreach($newVolume in $newVolumes){ Write-Host "Volume $($newVolume.VolumeId) $($newVolume.Size)GB state: $($newVolume.State.Value)" if($newVolume.State.Value -eq 'available'){ $readyCount++ } else { $NewVolumes = Get-EC2Volume -VolumeIds $NewVolumes.VolumeId $readyCount = 0 Write-Host "$(Get-Date) Volumes are not yet available. Sleeping for $sleepBetweenChecks second(s). Check $Retries of $maxRetries" } } Start-Sleep $sleepBetweenChecks $Retries++ } if($Retries -eq $maxRetries){ Throw "Volumes are in an unexpected state. Cannot continue!" } Write-Host "All volumes are now available." #Create Tags $newtags = @() $t = New-Object Amazon.EC2.Model.Tag $t.Key = 'Owner' $t.Value = 'Lantrix' $newtags += $t $t = New-Object Amazon.EC2.Model.Tag $t.Key = 'Name' $t.Value = 'DiskTest' $newtags += $t #Tag all resources New-EC2Tag -Resources @( $instance.Instances.InstanceId, $vol1.VolumeId, $vol2.VolumeId, $vol3.VolumeId ) -Tags $newtags #Attach Volumes to instance Add-EC2Volume -InstanceId $instance.Instances.InstanceId -VolumeId $vol1.VolumeId -Device 'xvdd' Add-EC2Volume -InstanceId $instance.Instances.InstanceId -VolumeId $vol2.VolumeId -Device 'xvde' Add-EC2Volume -InstanceId $instance.Instances.InstanceId -VolumeId $vol3.VolumeId -Device 'xvdf' #Wait for password data $password = $null while ($password -eq $null) { try { $password = Get-EC2PasswordData -InstanceId $instance.Instances.InstanceId -PemFile $folder\MyKey.pem -Decrypt } catch { "$(Get-Date) Waiting for PasswordData to be available" Sleep -Seconds 10 } }
PowerShellCorpus/GithubGist/gpolitis_4349530_raw_53007582e0cf18891335d720263aaa398f2e71bc_Microsoft.PowerShell_profile.ps1
gpolitis_4349530_raw_53007582e0cf18891335d720263aaa398f2e71bc_Microsoft.PowerShell_profile.ps1
function emacs { &"C:\Program Files (x86)\emacs-24.2\bin\emacs.exe" "-nw" $args } function Get-BitsFile { Get-BitsTransfer | % { $_.FileList | % { New-Object PSObject -Property @{ Progress = ($_.BytesTransferred / $_.BytesTotal) LocalName = $_.LocalName } } } }
PowerShellCorpus/GithubGist/skoon_1679717_raw_14bcfbfe3800f77ae6233bdfd75c403426ec23ac_githg.ps1
skoon_1679717_raw_14bcfbfe3800f77ae6233bdfd75c403426ec23ac_githg.ps1
if (test-path function:\prompt) { $oldPrompt = ls function: | ? {$_.Name -eq "prompt"} remove-item -force function:\prompt } function prompt { function getGitStatus { $branch = git branch 2>&1 if($branch.Exception -eq $null) { $status = "git" $branch | foreach { if ($_ -match "^\*(.*)"){ $status += $matches[1] } } $untracked = 0 $updates = 0 $deletes = 0 $addsIndex = 0 $deletesIndex =0 $updatesIndex = 0 git status --porcelain | foreach { if($_ -match "^([\w?]|\s)([\w?])?\s*") { switch ($matches[1]) { "A" {$addsIndex++ } "M" {$updatesIndex++ } "D" {$deletesIndex++ } "?" {$untracked++ } } switch ($matches[2]) { "A" {$adds++ } "M" {$updates++ } "D" {$deletes++ } } } } $status += " a:" +$addsIndex if($adds -gt 0) { $status += "($adds)" } $status += " m:" +$updatesIndex if($updates -gt 0) { $status += "($updates)" } $status += " d:" +$deletesIndex if($deletes -gt 0) { $status += "($deletes)" } $status += " ?:$untracked" return $status } else { return $false } } function getHgStatus { $summary = hg summary 2>&1 if($summary.Exception -eq $null) { $regex = "(?si)(parent:(?<parent>.*?)(\n|\r)+.*?)(branch:(?<branch>.*)\s)(commit:(?<commit>.*)\s)(update:(?<update>.*))"; $summary = [System.String]::Join([System.Environment]::NewLine,$summary) $res = $summary -match $regex $status = "hg {0} c:{1}" -f $matches["branch"].Trim(), $matches["commit"].Trim() return $status } else { return $false } } $status = getGitStatus if(-not $status) { $status = getHgStatus } $host.ui.rawui.WindowTitle = (get-location).Path if($status) { write-host ($status) -NoNewLine -ForegroundColor Green write-host (">") -NoNewLine -ForegroundColor Green } else { & $oldPrompt } return " " }
PowerShellCorpus/GithubGist/ibara1454_a8cf0d3aa013c7f775d8_raw_47de30c76a38f625cbad660b8c4d2b7e8da20138_dump.ps1
ibara1454_a8cf0d3aa013c7f775d8_raw_47de30c76a38f625cbad660b8c4d2b7e8da20138_dump.ps1
# Initializing $root_path = 'I:\' # scanning for what path $output = '.\Desktop\list.txt' # output path $pattern = '' # pattern match. ex: '*abc*' $include_ext = '' # extension name. ex: '*.rar' or '*.txt *.exe' $query = join-path $root_path $pattern get-childitem $query -recurse -include $include_ext ` | where-object {-not $_.PSIsContainer} ` | foreach-object {$_.Name + "`t" + $_.DirectoryName} ` | out-file $output
PowerShellCorpus/GithubGist/MattDavies_dfc66ade9c8e481ce854_raw_cad0f58ed8fd4399cecc6198ffa446d4fc9a715d_Publish-WebApplicationVM.ps1
MattDavies_dfc66ade9c8e481ce854_raw_cad0f58ed8fd4399cecc6198ffa446d4fc9a715d_Publish-WebApplicationVM.ps1
#Requires -Version 3.0 <# .SYNOPSIS Creates and deploys a Microsoft Azure Virtual Machine for a Visual Studio web project. For more detailed documentation go to: http://go.microsoft.com/fwlink/?LinkID=394472 .EXAMPLE PS C:\> .\Publish-WebApplicationVM.ps1 ` -Configuration .\Configurations\WebApplication1-VM-dev.json ` -WebDeployPackage ..\WebApplication1\WebApplication1.zip ` -VMPassword @{Name = "admin"; Password = "password"} ` -AllowUntrusted ` -Verbose #> [CmdletBinding(HelpUri = 'http://go.microsoft.com/fwlink/?LinkID=391696')] param ( [Parameter(Mandatory = $true)] [ValidateScript({Test-Path $_ -PathType Leaf})] [String] $Configuration, [Parameter(Mandatory = $false)] [String] $SubscriptionName, [Parameter(Mandatory = $false)] [ValidateScript({Test-Path $_ -PathType Leaf})] [String] $WebDeployPackage, [Parameter(Mandatory = $false)] [Switch] $AllowUntrusted, [Parameter(Mandatory = $false)] [ValidateScript( { $_.Contains('Name') -and $_.Contains('Password') } )] [Hashtable] $VMPassword, [Parameter(Mandatory = $false)] [ValidateScript({ !($_ | Where-Object { !$_.Contains('Name') -or !$_.Contains('Password')}) })] [Hashtable[]] $DatabaseServerPassword, [Parameter(Mandatory = $false)] [Switch] $SendHostMessagesToOutput = $false ) function New-WebDeployPackage { #Write a function to build and package your web application #To build your web application, use MsBuild.exe. For help, see MSBuild Command-Line Reference at: http://go.microsoft.com/fwlink/?LinkId=391339 } function Test-WebApplication { #Edit this function to run unit tests on your web application #Write a function to run unit tests on your web application, use VSTest.Console.exe. For help, see VSTest.Console Command-Line Reference at http://go.microsoft.com/fwlink/?LinkId=391340 } function New-AzureWebApplicationVMEnvironment { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [Object] $Configuration, [Parameter (Mandatory = $false)] [AllowNull()] [Hashtable] $VMPassword, [Parameter (Mandatory = $false)] [AllowNull()] [Hashtable[]] $DatabaseServerPassword ) $VMInfo = New-AzureVMEnvironment ` -CloudServiceConfiguration $Config.cloudService ` -VMPassword $VMPassword # Create the SQL databases. The connection string is used for deployment. $connectionString = New-Object -TypeName Hashtable if ($Config.Contains('databases')) { @($Config.databases) | Where-Object {$_.connectionStringName -ne ''} | Add-AzureSQLDatabases -DatabaseServerPassword $DatabaseServerPassword | ForEach-Object { $connectionString.Add($_.Name, $_.ConnectionString) } } return @{ConnectionString = $connectionString; VMInfo = $VMInfo} } function Publish-AzureWebApplicationToVM { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [Object] $Config, [Parameter(Mandatory = $false)] [AllowNull()] [Hashtable] $ConnectionString, [Parameter(Mandatory = $true)] [ValidateScript({Test-Path $_ -PathType Leaf})] [String] $WebDeployPackage, [Parameter(Mandatory = $false)] [AllowNull()] [Hashtable] $VMInfo ) $waitingTime = $VMWebDeployWaitTime $result = $null $attempts = 0 $allAttempts = 60 do { $result = Publish-WebPackageToVM ` -VMDnsName $VMInfo.VMUrl ` -IisWebApplicationName $Config.webDeployParameters.IisWebApplicationName ` -WebDeployPackage $WebDeployPackage ` -UserName $VMInfo.UserName ` -UserPassword $VMInfo.Password ` -AllowUntrusted:$AllowUntrusted ` -ConnectionString $ConnectionString if ($result) { Write-VerboseWithTime ($scriptName + ' Publishing to VM succeeded.') } elseif ($VMInfo.IsNewCreatedVM -and !$Config.cloudService.virtualMachine.enableWebDeployExtension) { Write-VerboseWithTime ($scriptName + ' You need to set "enableWebDeployExtension" to $true.') } elseif (!$VMInfo.IsNewCreatedVM) { Write-VerboseWithTime ($scriptName + ' Exising VM does not support Web Deploy.') } else { Write-VerboseWithTime ('{0}: Publishing to VM failed. Attempt {1} of {2}.' -f $scriptName, ($attempts + 1), $allAttempts) Write-VerboseWithTime ('{0}: Publishing to VM will start after {1} seconds.' -f $scriptName, $waitingTime) Start-Sleep -Seconds $waitingTime } $attempts++ #Try to publish again only for newly created virtual machine that has Web Deploy installed. } While( !$result -and $VMInfo.IsNewCreatedVM -and $attempts -lt $allAttempts -and $Config.cloudService.virtualMachine.enableWebDeployExtension) if (!$result) { Write-Warning ' Publishing to the virtual machine failed. This can be caused by an untrusted or invalid certificate. You can specify -AllowUntrusted to accept untrusted certificates.' throw ($scriptName + ' Publishing to VM failed.') } } # Script main routine Set-StrictMode -Version 3 Remove-Module AzureVMPublishModule -ErrorAction SilentlyContinue $scriptDirectory = Split-Path -Parent $PSCmdlet.MyInvocation.MyCommand.Definition Import-Module ($scriptDirectory + '\AzureVMPublishModule.psm1') -Scope Local -Verbose:$false New-Variable -Name VMWebDeployWaitTime -Value 30 -Option Constant -Scope Script New-Variable -Name AzureWebAppPublishOutput -Value @() -Scope Global -Force New-Variable -Name SendHostMessagesToOutput -Value $SendHostMessagesToOutput -Scope Global -Force try { $originalErrorActionPreference = $Global:ErrorActionPreference $originalVerbosePreference = $Global:VerbosePreference if ($PSBoundParameters['Verbose']) { $Global:VerbosePreference = 'Continue' } $scriptName = $MyInvocation.MyCommand.Name + ':' Write-VerboseWithTime ($scriptName + ' Start') $Global:ErrorActionPreference = 'Stop' Write-VerboseWithTime ('{0} $ErrorActionPreference is set to {1}' -f $scriptName, $ErrorActionPreference) Write-Debug ('{0}: $PSCmdlet.ParameterSetName = {1}' -f $scriptName, $PSCmdlet.ParameterSetName) # Verify that you have the Azure module, Version 0.7.4 or later. $validAzureModule = Test-AzureModule if (-not ($validAzureModule)) { throw 'Unable to load Azure PowerShell. To install the latest version, go to http://go.microsoft.com/fwlink/?LinkID=320552 .If you have already installed Azure PowerShell, you may need to restart your computer or manually import the module.' } # Save the current subscription. It will be restored to Current status later in the script Backup-Subscription -UserSpecifiedSubscription $SubscriptionName if ($SubscriptionName) { # If you provided a subscription name, verify that the subscription exists in your account. if (!(Get-AzureSubscription -SubscriptionName $SubscriptionName)) { throw ("{0}: Cannot find the subscription name $SubscriptionName" -f $scriptName) } # Set the specified subscription to current. Select-AzureSubscription -SubscriptionName $SubscriptionName | Out-Null Write-VerboseWithTime ('{0}: Subscription is set to {1}' -f $scriptName, $SubscriptionName) } $Config = Read-ConfigFile $Configuration -HasWebDeployPackage:([Bool]$WebDeployPackage) #Build and package your web application New-WebDeployPackage #Run unit test on your web application Test-WebApplication #Create Azure environment described in the JSON configuration file $newEnvironmentResult = New-AzureWebApplicationVMEnvironment -Configuration $Config -DatabaseServerPassword $DatabaseServerPassword -VMPassword $VMPassword #Deploy Web Application package if $WebDeployPackage is specified by the user if($WebDeployPackage) { Publish-AzureWebApplicationToVM ` -Config $Config ` -ConnectionString $newEnvironmentResult.ConnectionString ` -WebDeployPackage $WebDeployPackage ` -VMInfo $newEnvironmentResult.VMInfo } } finally { $Global:ErrorActionPreference = $originalErrorActionPreference $Global:VerbosePreference = $originalVerbosePreference # Restore the original current subscription to Current status if($validAzureModule) { Restore-Subscription } Write-Output $Global:AzureWebAppPublishOutput $Global:AzureWebAppPublishOutput = @() }
PowerShellCorpus/GithubGist/serbrech_8003858_raw_5527525f12a0e46c456a0de7951fddf11b144f61_MsDeploy.ps1
serbrech_8003858_raw_5527525f12a0e46c456a0de7951fddf11b144f61_MsDeploy.ps1
function DeployWebsite($Package, $Server, $IISSite, $App, $Username, $Password) { $MSDeployKey = 'HKLM:\SOFTWARE\Microsoft\IIS Extensions\MSDeploy\3' if(!(Test-Path $MSDeployKey)) { throw "Could not find MSDeploy. Use Web Platform Installer to install the 'Web Deployment Tool' and re-run this command" } $InstallPath = (Get-ItemProperty $MSDeployKey).InstallPath if(!$InstallPath -or !(Test-Path $InstallPath)) { throw "Could not find MSDeploy. Use Web Platform Installer to install the 'Web Deployment Tool' and re-run this command" } $msdeploy = Join-Path $InstallPath "msdeploy.exe" if(!(Test-Path $MSDeploy)) { throw "Could not find MSDeploy. Use Web Platform Installer to install the 'Web Deployment Tool' and re-run this command" } $PublishUrl = "https://$($Server):8172/MSDeploy.axd?site=$($IISSite)" $WebApp = "$IISSite/$App" # DEPLOY! Write-Host "Deploying package to $PublishUrl for $($App)" $arguments = [string[]]@( "-verb:sync", "-source:package='$Package'", "-dest:auto,computerName='$PublishUrl',userName='$UserName',password='$Password',authtype='Basic'", "-setParam:name='IIS Web Application Name',value='$($WebApp)'", "-allowUntrusted") Start-Process $msdeploy -ArgumentList $arguments -NoNewWindow -Wait }
PowerShellCorpus/GithubGist/ghotz_af65a1d178d8119e325e_raw_bf7356edc512bffa31f236ad345042100921eded_Split-ErrorLog.ps1
ghotz_af65a1d178d8119e325e_raw_bf7356edc512bffa31f236ad345042100921eded_Split-ErrorLog.ps1
# just a draft, need massive polishing :) cls; $reader = new-object System.IO.StreamReader("ERRORLOG") $count = 1 $numlines = 0 $fileName = "{0}{1}.{2}" -f ("ERRORLOG_stripped_", $count, "txt") while(($line = $reader.ReadLine()) -ne $null) { if ((++$numlines % 1000) -eq 0) { Write-Output "Processed $numlines lines" } if (!($line -match "Login succeeded*" -or $line -match "Login failed*" -or $line -match "Error: 18456*")) #if (!($line -match "I/O is frozen*" -or $line -match "I/O was resumed*" -or $line -match "Database backed up.*")) { Add-Content -path $fileName -value $line } if((Get-ChildItem -path $fileName).Length -ge 10MB) { ++$count $fileName = "{0}{1}.{2}" -f ("ERRORLOG_stripped_", $count, "txt") } } $reader.Close()
PowerShellCorpus/GithubGist/ao-zkn_47b3f28d1bf1c5e6543d_raw_d3e29a5c7355ba78850aa357e85e9931f33bd5a1_Rename-Folder.ps1
ao-zkn_47b3f28d1bf1c5e6543d_raw_d3e29a5c7355ba78850aa357e85e9931f33bd5a1_Rename-Folder.ps1
# ------------------------------------------------------------------ # フォルダ名をリネームする # 関数名:Rename-Folder # 引数 :FolderPath 名前を変更するフォルダパス # :NewFolderName 新しいフォルダ名前 # 戻り値:なし # ------------------------------------------------------------------ function Rename-Folder([String]$FolderPath, [String]$NewFolderName){ if(Test-Path -LiteralPath $FolderPath -PathType Container){ Rename-Item $FolderPath -newName $NewFolderName Write-Host "フォルダー名を変更しました。置換前[ $FolderPath ] 置換後[ $NewFolderName ]" }else{ Write-Host "フォルダーが存在しません。フォルダー名[ $FolderPath ]" } }
PowerShellCorpus/GithubGist/BrandonBrowning_935043e4f54942fbba34_raw_8c05f45fd1423f3e756a395a39f3bb87bc7fad07_gistfile1.ps1
BrandonBrowning_935043e4f54942fbba34_raw_8c05f45fd1423f3e756a395a39f3bb87bc7fad07_gistfile1.ps1
# pk: pk - Azure Table Storage Log Partition Key Generator # by Brandon Browning # # Usage: pk [time-expression]... # Time expression examples: +5s, -1h15s, 30m # Examples: # pk # Gets current time keys # pk -30s # Gets time keys 30 seconds ago # pk 0s -1h5s # Gets time keys now, and 1 hour 5 seconds ago # Example output: # PS C:\Users\bbrowning> pk 0s -1h +2h15s +1d # 2014-05-30T20:13:13.0665297Z PartitionKey ge '0635370775930665297' PartitionKey ge '1401480793' # 2014-05-30T19:13:13.0665297Z PartitionKey ge '0635370739930665297' PartitionKey ge '1401477193' # 2014-05-30T20:13:28.0665297Z PartitionKey ge '0635370776080665297' PartitionKey ge '1401480808' # 2014-05-31T20:13:13.0665297Z PartitionKey ge '0635371639930665297' PartitionKey ge '1401567193' $start = [DateTime]::UtcNow if ($args.Count -eq 0) { $args = @('+0s') } foreach ($arg in $args) { $now = $start.AddSeconds(0) foreach ($match in [Regex]::Matches($arg, '(?:(\d+)(\w))+')) { if ($arg[0] -eq '-') { $mult = -1 } else { $mult = 1 } if ($match.Groups[2].Value.ToLower() -eq 'd') { $now = $now.AddDays($mult * [int]$match.Groups[1].Value) } elseif ($match.Groups[2].Value.ToLower() -eq 'h') { $now = $now.AddHours($mult * [int]$match.Groups[1].Value) } elseif ($match.Groups[2].Value.ToLower() -eq 'm') { $now = $now.AddMinutes($mult * [int]$match.Groups[1].Value) } elseif ($match.Groups[2].Value.ToLower() -eq 's') { $now = $now.AddSeconds($mult * [int]$match.Groups[1].Value) } } $epoch = New-Object DateTime 1970, 1, 1 $pk = '0' + $now.Ticks.ToString() $unix = [int]($now - $epoch).TotalSeconds "{0} PartitionKey ge '{1}' PartitionKey ge '{2}'" -f ($now.ToString('o'), $pk, $unix) }
PowerShellCorpus/GithubGist/pogin503_d5cf1397db243b26b6cf_raw_4afb234bf5dac93409f711886186af96e61e6095_ps1.ps1
pogin503_d5cf1397db243b26b6cf_raw_4afb234bf5dac93409f711886186af96e61e6095_ps1.ps1
Get-Alias dir # エイリアスを作る Get-Command # コマンドを表示 Import-Alias c:\scripts\alias.txt Write-Host # いわゆるprint文 get-content "パス" Get-Service # 実行中のサービスを表示 # アプリケーション イベントログの最新15個のエントリを表示 Get-EventLog -logName Application -newest 15 # 通常の配列に関してもパイプラインを使用可能。 # 重複を取り除き、ソートをかける @(3,5,10,1,2,1,1,1,2,6,4,4)|Sort-Object|Get-Unique 変数のスコープ # どのスコープからも読み書き可能 $global:a = 1 # 現在のスコープからのみ読み書き可能 $private:a = 1 # 現在のスクリプトからのみ読み書き可能 $script:a = 1 # コマンドを実行する powershell -command {Get-ChildItem C:\} # ' ← シングルクォートは継続行 if elseif else 構文 foreach 構文 foreach ( $name in $names) { } # Abs関数 $a = [math]::abs(-15) # Join $a = "h","e","l","l","o" $b = [string]::join("", $a) # Date $a = get-date -format d => 2006/9/1 # Minute $a =(get-date).minute # DateSerial MyDate1 = DateSerial(2006, 12, 31) # or $a = get-date -y 2006 -mo 12 -day 31 http://winscript.jp/powershell/202 # 変数 $a = 1 $b = 2 $a -eq $b # 論理演算子 -ne != -lt > -gt < -le >= -ge <= -ieq case insensitive -ceq case sensitive
PowerShellCorpus/GithubGist/talatham_5774395_raw_73fb8a83e1281d9b2dfcbcd2c6e798240b94d09e_checkmachineforhotfix.ps1
talatham_5774395_raw_73fb8a83e1281d9b2dfcbcd2c6e798240b94d09e_checkmachineforhotfix.ps1
# Check for a specific patch on remote PCs v1.2 # Tom Latham 04/02/2010 # # Added v1.1: Error messaages # Added v1.2: GUI Inputs # Function to open file dialog box and select a file Function Get-FileName($initialDirectory) { [void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog $OpenFileDialog.initialDirectory = $initialDirectory $OpenFileDialog.filter = "Text Files (*.txt)| *.txt" # Set the file types visible to dialog $OpenFileDialog.ShowDialog() | Out-Null $OpenFileDialog.filename } # Function to prompt user for kb number Function Get-Input { [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $objForm = New-Object System.Windows.Forms.Form $objForm.Text = "Enter KB Number" $objForm.Size = New-Object System.Drawing.Size(300,200) $objForm.StartPosition = "CenterScreen" $objForm.KeyPreview = $True $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") {$x=$objTextBox.Text;$objForm.Close()}}) $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") {$objForm.Close()}}) $OKButton = New-Object System.Windows.Forms.Button $OKButton.Location = New-Object System.Drawing.Size(75,120) $OKButton.Size = New-Object System.Drawing.Size(75,23) $OKButton.Text = "OK" $OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()}) $objForm.Controls.Add($OKButton) $CancelButton = New-Object System.Windows.Forms.Button $CancelButton.Location = New-Object System.Drawing.Size(150,120) $CancelButton.Size = New-Object System.Drawing.Size(75,23) $CancelButton.Text = "Cancel" $CancelButton.Add_Click({$objForm.Close()}) $objForm.Controls.Add($CancelButton) $objLabel = New-Object System.Windows.Forms.Label $objLabel.Location = New-Object System.Drawing.Size(10,20) $objLabel.Size = New-Object System.Drawing.Size(280,20) $objLabel.Text = "Please enter the KB number below (kbxxxxxx):" $objForm.Controls.Add($objLabel) $objTextBox = New-Object System.Windows.Forms.TextBox $objTextBox.Location = New-Object System.Drawing.Size(10,40) $objTextBox.Size = New-Object System.Drawing.Size(260,20) $objForm.Controls.Add($objTextBox) $objForm.Topmost = $True $objForm.Add_Shown({$objForm.Activate()}) [void] $objForm.ShowDialog() $x } # Main Program -------------------------------------- # Do not display errors $erroractionpreference = "SilentlyContinue" # Clear screen clear-host # Store user credentials $cred = get-credential # Supply text file of all PCs to be checked and KB number to search for # Run Open File Dialog $filename = Get-FileName -initialDirectory "c:" # Get path of file to be used in storing results $path = split-path $filename # If kbresults.txt exists, delete it if (test-path $path\kbresults.txt) { remove-item $path\kbresults.txt } # Get kb number $kb = Get-Input # Extract content from filename object $computernames = get-content $filename # For each computer in list foreach ($computer in $computernames) { # Set query string to query ping status $strQuery = "select * from win32_pingstatus where address = '" + $computer + "'" # Get WMI object using query $wmi = gwmi -query $strquery # If machine pings (status = 0) if ($wmi.statuscode -eq 0) { # Get WMI object on computer where hotfixid equals our kb number # Use stored user credentials $checkkb = gwmi win32_QuickFixEngineering -computer $computer -credential $cred | where {$_.hotfixid -eq $kb} | select-object hotfixid, description switch -regex ($Error[ 0 ].Exception) { "The RPC server is unavailable" { write-host -f blue $computer "`t" "RPC Unavailable on $computer" "`r" "$computer `t RPC Unavailable." | out-file $path\kbresults.txt -append continue } "Access denied" { write-host -f blue $computer "`t" "Access Denied" "`r" "$computer `t Access Denied." | out-file $path\kbresults.txt -append continue } "Access is denied" { write-host -f blue $computer "`t" "Access Denied" "`r" "$computer `t Access Denied." | out-file $path\kbresults.txt -append continue } # No error -> record our info! $null { # If kb numbers match if ($checkkb.hotfixid -eq $kb) { # Patch is installed. Test reboot status. # Connect to remote registry hive (HKLM) $regHive = [Microsoft.Win32.RegistryHive]"LocalMachine"; $regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$computer); # Set subkey to 'UpdateExeVolatile', the existence of which show reboot pending status $subKey = $regKey.OpenSubKey("SOFTWARE\Microsoft\Updates\UpdateExeVolatile"); # If subkey is not found if (!$subKey) { # Patch is installed write-host -f green $computer "`t" $checkkb.description "`r" "$computer `t Installed." | out-file $path\kbresults.txt -append } else { # Patch installed. Reboot required. write-host -f green $computer "`t" $checkkb.description "`r" "$computer `t Reboot Required" | out-file $path\kbresults.txt -append } } else { # Patch is not installed. write-host -f red $computer "`t" "Not Found" "`r" "$computer `t Not Installed." | out-file $path\kbresults.txt -append } } } $Error.clear() } else { # Machine doesn't ping. Write to screen and append to results file. write-host $computer "`t" "Cannot ping." "`r" "$computer `t Ping failed." | out-file $path\kbresults.txt -append } }
PowerShellCorpus/GithubGist/fr0gger03_ab5eced3c44f56cf611f_raw_bf757df133bad679a7895702bdc717074e95904a_VMFS-to-LUN-NAA.ps1
fr0gger03_ab5eced3c44f56cf611f_raw_bf757df133bad679a7895702bdc717074e95904a_VMFS-to-LUN-NAA.ps1
# you must connect and authenticate to a vCenter server # use Connect-VIServer to do so # establish Export file name $csvname = Read-Host 'Please provide the file path and name for your CSV export' # Gather information on all datastores in the vCenter and enter a loop get-datastore |foreach-object { # Capture the name of the datastore in a variable $ds=$_.Name # For each datastore, get teh information on the SCSI LUN, # select specific properties and export it all to the CSV file # note - the "gu" command is shorthand for "get-unique" - # this is necessary as datastores will be reported by multiple virtual machines get-scsilun -datastore $ds | Select-Object @{n='NAA';e={$_.canonicalname}}, @{n='Datastore Name';e={$ds}} | gu | Export-CSV "c:\users\rfw614\Desktop\scsilun.csv” -NoTypeInformation –Append }
PowerShellCorpus/GithubGist/tjchaplin_621edccbfddc0d3526b5_raw_a39878becce7f01e68e07326586fb3c8d01d4645_gistfile1.ps1
tjchaplin_621edccbfddc0d3526b5_raw_a39878becce7f01e68e07326586fb3c8d01d4645_gistfile1.ps1
# These are project build parameters in TeamCity # Depending on the branch, we will use different major/minor versions [System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") $ser = New-Object System.Web.Script.Serialization.JavaScriptSerializer $json = Get-Content "package.json" | Out-String $obj = $ser.DeserializeObject($json) $majorVerion = ($obj['version'] -split "\.")[0] $minorVerion = ($obj['version'] -split "\.")[1] $buildCounter = "%teamcity.build.counter%" $buildNumber = "$majorVerion.$minorVerion.$buildCounter" # This gets the name of the current Git branch. $branch = "%teamcity.build.branch%" $buildMetadata = ""; # Sometimes the branch will be a full path, e.g., 'refs/heads/master'. # If so we'll base our logic just on the last part. if ($branch.Contains("/")) { $branch = $branch.substring($branch.lastIndexOf("/")).trim("/") } Write-Host "Branch: $branch" if ($branch -eq "master") { $buildMetadata = "" } elseif ($branch -match "feature_.*") { $branch = $branch.replace("feature_", "") $buildMetadata = "-${branch}" } elseif ($branch -match "feature-.*") { # If the branch starts with "feature-", just use the feature name $branch = $branch.replace("feature-", "") $buildMetadata = "-${branch}" } elseif ($branch -match "fix_.*") { $branch = $branch.replace("fix_", "") $buildMetadata = "-${branch}" } else { $buildMetadata = "-${branch}" } $buildNumber = "$buildNumber$buildMetadata" Write-Host "##teamcity[buildNumber '$buildNumber']"
PowerShellCorpus/GithubGist/rheid_8dd79207a84212773869_raw_f420bdd523b5a6d2eb7ed6682ddd02ffbbfea72e_AddFarmAdmin.ps1
rheid_8dd79207a84212773869_raw_f420bdd523b5a6d2eb7ed6682ddd02ffbbfea72e_AddFarmAdmin.ps1
################################################# # Add a new Farm Administrator ################################################# Add-PSSnapin *SharePoint* -erroraction SilentlyContinue Write-Host $newFarmAdmin = Read-Host -Prompt 'Enter the new Farm Administrator (i.e. DOMAIN\Username): ' Write-Host $webApp = Get-SPWebApplication -IncludeCentralAdministration | where-object {$_.DisplayName -eq "SharePoint Central Administration v4"} $site = $webApp.Sites[0]; $Web = $site.RootWeb; $farmAdministrators = $web.SiteGroups["Farm Administrators"]; try { $farmAdministrators.AddUser($newFarmAdmin, "", $newFarmAdmin, ""); $contentDB = Get-SPContentDatabase -WebApplication $webApp Add-SPShellAdmin -Database $contentDB -Username $newFarmAdmin Write-Host "Completed Succesfully!" } catch { Write-Host 'Error: Failed to add user.' -ForegroundColor Red Write-Host ('Reason: ' + $_) -ForegroundColor Red } $web.Dispose(); $site.Dispose();
PowerShellCorpus/GithubGist/rheid_93fad58069b1a62e786b_raw_e1b04af315fbc45672ab661c308fff6a66e95d39_StateService.ps1
rheid_93fad58069b1a62e786b_raw_e1b04af315fbc45672ab661c308fff6a66e95d39_StateService.ps1
# The State Service is required in order to use the out-of-the-box workflows in # SharePoint Server 2010 (e.g. Approval - SharePoint 2010) or any other features # that leverage InfoPath Forms Services. # # When using the Farm Configuration Wizard to configure the State Service, the # resulting database is named StateService_{GUID}. In order to avoid lengthy # database names containing GUIDs, the State Service is configured using PowerShell. function ConfigureStateService( [string] $stateServiceName = $(Throw "Value cannot be null: stateServiceName"), [string] $stateServiceDatabaseName = $(Throw "Value cannot be null: stateServiceDatabaseName")) { Write-Host "Configuring the State Service..." Write-Debug "stateServiceName: $stateServiceName" Write-Debug "stateServiceDatabaseName: $stateServiceDatabaseName" $serviceApp = Get-SPStateServiceApplication -Identity "$stateServiceName" ` -Debug:$false -EA 0 If ($serviceApp -ne $null) { Write-Host "The State Service has already been configured." return } $database = New-SPStateServiceDatabase -Name $stateServiceDatabaseName ` -Debug:$false $serviceApp = New-SPStateServiceApplication -Name $stateServiceName ` -Database $database -Debug:$false New-SPStateServiceApplicationProxy -ServiceApplication $serviceApp ` -Name $stateServiceName -DefaultProxyGroup -Debug:$false > $null Write-Host -Fore Green "Successfully configured the State Service." } function Main() { $stateServiceName = "State Service" $stateServiceDatabaseName = "HDTP_States" ConfigureStateService $stateServiceName $stateServiceDatabaseName } Main
PowerShellCorpus/GithubGist/andreaslekis_ca65f6471883c43c2c4c_raw_ed5d610721d3a013719ae6197254e8bd21c50550_LpW_Server.ps1
andreaslekis_ca65f6471883c43c2c4c_raw_ed5d610721d3a013719ae6197254e8bd21c50550_LpW_Server.ps1
Disable-MicrosoftUpdate Update-ExecutionPolicy Unrestricted # Vypne rozsirene zabezpeceni IE Disable-InternetExplorerESC cinst notepadplusplus.install cinst 7zip.install cinst putty cinst freecommander #cinst classic-shell choco teamviewer.host # cinst procdump #Prodiskutovat #Add-WindowsFeature NET-framework-core # Nastaveni Windows Set-WindowsExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions Install-WindowsUpdate -accepteula Enable-MicrosoftUpdate
PowerShellCorpus/GithubGist/pstephens_7460763_raw_5767cb84a78059d578aa2df45cc6bd27bddaada5_GetNode.ps1
pstephens_7460763_raw_5767cb84a78059d578aa2df45cc6bd27bddaada5_GetNode.ps1
$nodeUrl = "http://nodejs.org/dist/v0.10.22/x64/node-v0.10.22-x64.msi" $nodeSha = "c3c169304c6371ee7bd119151bcbced61a322394" function DownloadIt($url, $path) { Start-BitsTransfer -Source $url -Destination $path } function TestHash($path, $sha) { $bytes = [System.IO.File]::ReadAllBytes($path) $hasher = [System.Security.Cryptography.SHA1]::Create() $hash = $hasher.ComputeHash($bytes) $hasher.Dispose() $hashAsHex = ($hash.GetEnumerator() | Foreach-Object { "{0:x2}" -f $_ }) -Join "" if($hashAsHex -ne $sha) { throw "Hash for '$path' is incorrect. Was '$hashAsHex' but should be '$sha'." } } function IsElevated() { ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()). IsInRole([Security.Principal.WIndowsBuiltInRole]::Administrator) } function ElevateIfNecessary([ScriptBlock]$script, $workingDirectory) { if(!(IsElevated)) { Write-Host "Elevating..." Start-Process "$PSHome\powershell" ` -Verb runAs ` -Wait ` -ArgumentList "-ExecutionPolicy unrestricted -NoProfile -Command & { Set-Location $workingDirectory; $script }" } else { Push-Location $workingDirectory try { & $script } finally { Pop-Location } } } function FindPath($paths) { foreach($path in $paths) { if(Test-Path $path) { $resolvedPaths = @(Resolve-Path $path) if($resolvedPaths.Length -gt 1) { throw "Too many files match '$path'." } return $resolvedPaths[0] } } throw "Failed to find a match for paths '$($paths -join ", ")'." } function RunNPM($cmdline) { $npmPath = FindPath "$env:ProgramFiles\nodejs\npm.cmd" $p = (Start-Process $npmPath -ArgumentList $cmdline -NoNewWindow -Wait -PassThru) if($p.ExitCode -ne 0) { throw "NPM returned nonzero exit code: $($p.ExitCode)" } } function FixupEnvironment { $pathParts = $env:Path -split ";" $pathParts += [System.Environment]::GetEnvironmentVariable("Path", "Machine") -split ";" $pathParts += [System.Environment]::GetEnvironmentVariable("Path", "User") -split ";" $pathParts = $pathParts | Where { ![string]::IsNullOrWhitespace($_) } | Select-Object -Unique $env:Path = $pathParts -join ";" } try { # Configure directories and paths $thisScript = $MyInvocation.MyCommand.Path $curDir = Split-Path $thisScript $tempDir = Join-Path $curDir NodeTemp $nodeMsi = Join-Path $tempDir "node.msi" if(!(Test-Path $tempDir)) { New-Item $tempDir -ItemType Directory | Out-Null } Get-ChildItem $tempDir -exclude node.msi | Remove-Item if(!(Test-Path $nodeMsi)) { Write-Host "Downloading Node.js..." DownloadIt $nodeUrl $nodeMsi } Write-Host "Verifying Node.js installer hash..." TestHash $nodeMsi $nodeSha ElevateIfNecessary { try { Write-Host 'Uninstalling Node.js (if needed)...' Start-Process msiexec -ArgumentList '/x Node.msi /quiet /l* uninstall.log' -NoNewWindow -Wait Write-Host 'Installing Node.js...' $p = (Start-Process msiexec -ArgumentList '/i Node.msi /quiet /l* install.log' -NoNewWindow -Wait -PassThru) $p.ExitCode | Set-Content MsiExecExitCode.txt } catch { $_ | Set-Content ElevatedError.txt $_ } } $tempDir # Check the results from msiexec $elevatedErrorPath = Join-Path $tempDir ElevatedError.txt if(Test-Path $elevatedErrorPath) { throw "Failed in elevated shell: $(Get-Content $elevatedErrorPath)" } $msiExecExitCode = [int](Get-Content (Join-Path $tempDir MsiExecExitCode.txt)) if($msiExecExitCode -ne 0) { throw "Failed while running msiexec with exit code $msiExecExitCode." } Write-Host "Installing jslint..." RunNPM "install jslint" Write-Host "Fixing up local environment Path..." FixupEnvironment Write-Host "Successfully installed Node.js." } catch { throw $_ }
PowerShellCorpus/GithubGist/vermorel_9804025_raw_014fdb986e1dbcdb33ff34feac3c38a4e1025c00_sample-content.ps1
vermorel_9804025_raw_014fdb986e1dbcdb33ff34feac3c38a4e1025c00_sample-content.ps1
# Sample-Content # By Joannes Vermorel, 2014 # Keep only 1 line out of N of a flat file # Usage: sample-content .\myfile.csv 100 function Sample-Content() { param ( [string]$path = $null, [int]$ratio = 100 ); $path = (get-item $path).FullName; $outpath = $path + ".sample"; $count = -1; # preserve the first line to keep the headers (if any) $r = [IO.File]::OpenText($path) while ($r.Peek() -ge 0) { $line = $r.ReadLine(); $count = $count + 1; if(($count % $ratio) -eq 0) { $line | out-file $outpath -Append; } } $r.Dispose(); }
PowerShellCorpus/GithubGist/jpoehls_2726969_raw_6b01dc04afdbbda64c730b2e4ffdfacb9fa9760f_xpath-example.ps1
jpoehls_2726969_raw_6b01dc04afdbbda64c730b2e4ffdfacb9fa9760f_xpath-example.ps1
function Edit-XmlNodes { param ( [xml] $doc = $(throw "doc is a required parameter"), [string] $xpath = $(throw "xpath is a required parameter"), [string] $value = $(throw "value is a required parameter"), [bool] $condition = $true ) if ($condition -eq $true) { $nodes = $doc.SelectNodes($xpath) foreach ($node in $nodes) { if ($node -ne $null) { if ($node.NodeType -eq "Element") { $node.InnerXml = $value } else { $node.Value = $value } } } } } $xml = [xml](Get-Content "c:\my\file.xml") # <file><foo attribute="bar" attribute2="bar" attribute3="bar" /></file> Edit-XmlNodes $xml -xpath "/file/foo[@attribute='bar']/@attribute" -value "new value" $xml.save("c:\my\file.xml") # <file><foo attribute="new value" attribute2="bar" attribute3="bar" /></file>
PowerShellCorpus/GithubGist/sesstreets_24d0c9da9e9195803e1b_raw_f86f26502c90b70f6bb85f5ee43365d683509987_DesktopWipe.ps1
sesstreets_24d0c9da9e9195803e1b_raw_f86f26502c90b70f6bb85f5ee43365d683509987_DesktopWipe.ps1
DesktopWipe.ps1 # Desktop Wipe version .3 # Moved to powershell # Better program flow # Set the user $strUser="andrewliebowitz.ad" Get-ChildItem -Force "C:\Users\$strUser\desktop" | ForEach-Object {$_} {remove-item $_.fullname -exclude *.lnk,*.ini -recurse}
PowerShellCorpus/GithubGist/altrive_8625656_raw_6acfc5583ca5a39616971523065404fcefef0d0b_ParallelPing.ps1
altrive_8625656_raw_6acfc5583ca5a39616971523065404fcefef0d0b_ParallelPing.ps1
function Main { $ipAddresses = 1..254 | foreach { "192.168.0.$_" } #$ipAddresses | Invoke-ParallelPing | Out-GridView Invoke-ParallelPing -ComputerName $ipAddresses | Out-GridView } function Invoke-ParallelPing { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline)] [string[]] $ComputerName, [int] $TimeoutMilliseconds = 1000, [int] $PingDataSize = 32 ) begin { $ErrorActionPreference = "Stop" $pingOptions = New-Object Net.NetworkInformation.PingOptions(64, $false) $pingData = New-Object byte[]($PingDataSize) $tasks = @() } process { $ComputerName | foreach { $targetName = $_ $ping = New-Object Net.NetworkInformation.Ping $task = $ping.SendPingAsync($targetName, $TimeoutMilliseconds, $pingData, $pingOptions) $tasks += [pscustomobject] @{ ComputerName = $targetName Task = $task PingObject = $ping } } } end { [Threading.Tasks.Task]::WaitAll($tasks.Task) foreach ($task in $tasks) { [Net.NetworkInformation.PingReply] $result = $task.Task.Result [pscustomobject] @{ Id = $task.Task.Id TargetName = $task.ComputerName IsSuccess = $result.Status -eq [Net.NetworkInformation.IPStatus]::Success Status = $result.Status RoundtripTime = $result.RoundtripTime } } foreach ($task in $tasks) { #TODO:Should be disposed in $task.ContinueWith({}) block $task.PingObject.Dispose() $task.Task.Dispose() } } } . Main
PowerShellCorpus/GithubGist/antonioj-mattos_4a5fbab6534e47cfe348_raw_ad321c2da0231b438260ad8a9bf516a1e0be7d6f_Install-MongoDb-On-AppVeyor.ps1
antonioj-mattos_4a5fbab6534e47cfe348_raw_ad321c2da0231b438260ad8a9bf516a1e0be7d6f_Install-MongoDb-On-AppVeyor.ps1
#Make sure 7za is installed choco install 7zip.commandline # Create mongodb and data directory md $env:temp\mongo\data # Go to mongodb dir Push-Location $env:temp\mongo # Download zipped mongodb binaries to mongodbdir Invoke-WebRequest https://fastdl.mongodb.org/win32/mongodb-win32-i386-2.6.7.zip?_ga=1.44958753.446619509.1416081281 -OutFile mongodb.zip # Extract mongodb zip cmd /c 7za e mongodb.zip # Install mongodb as a windows service cmd /c $env:temp\mongo\mongod.exe --logpath=$env:temp\mongo\log --dbpath=$env:temp\mongo\data\ --smallfiles --install # Sleep as a hack to fix an issue where the service sometimes does not finish installing quickly enough Start-Sleep -Seconds 5 # Start mongodb service net start mongodb # Return to last location, to run the build Pop-Location Write-Host Write-Host "monogdb installation complete"
PowerShellCorpus/GithubGist/janegilring_5626326_raw_74107d594f14f768d2d65ea62fc91cae098e9254_2013SGEvent4BeginnerSample.ps1
janegilring_5626326_raw_74107d594f14f768d2d65ea62fc91cae098e9254_2013SGEvent4BeginnerSample.ps1
<# .SYNOPSIS This will export info on 20 randomly selected AD users to an html file located on the desktop of the user running it. It will provide the username, department, title, last logon time, last password change and account enabled / lockout status sorted by user. ***Notes*** It will import the AD module in order to use Get-ADUser. Please change the SearchBase for your own domain / specific ou. .DESCRIPTION This was written for Event 4 of the 2013 Scripting Games (Beginner). .EXAMPLE .\UserAudit.ps1 #> $head = @" <title>Active Directory Audit</title> <style> body { font-family:Georgia, Arial, Helvetica, sans-serif; } table { width:100%; border-collapse:collapse; } td, th { border:1px solid #98bf21; padding:3px 7px 2px 7px; } th { font-size:1.2em; text-align:left; padding-top:5px; padding-bottom:4px; background-color:#A7C942; color:#ffffff; } td { font-size:1.0em; color:#000000; background-color:#EAF2D3; } </style> "@ $pre = "<H2><center>Active Directory Audit</center></H2>" $post = @" <br/> Report Generated: $(Get-Date) by $env:username "@ $path = "$env:userprofile\desktop\UserAudit.html" $properties = "sAMAccountName", "Department", "Title", "lastLogonDate", "PasswordLastSet", "Enabled", "LockedOut" Import-Module ActiveDirectory Get-Random (Get-ADUser -Filter * -SearchBase "dc=tine,dc=no" -Properties $properties) -Count 20 | Select-Object @{name="User Name";expression={$_.sAMAccountName}}, @{name="Department";expression={$_.Department}}, @{name="Title";expression={$_.Title}}, @{name="Last Logon";expression={$_.lastLogonDate}}, @{name="Password Last Changed";expression={$_.PasswordLastSet}}, @{name="Account Enabled";expression={$_.Enabled}}, @{name="Account Locked Out";expression={$_.LockedOut}} | Sort-Object "User Name" | ConvertTo-HTML -head $head -PreContent $pre -PostContent $post | Out-File -FilePath $path -Force
PowerShellCorpus/GithubGist/michelc_a63cbb9f400ad1525288_raw_3189a3d2f266f10744988a6e432a568b0638c37c_Microsoft.PowerShell_profile.ps1
michelc_a63cbb9f400ad1525288_raw_3189a3d2f266f10744988a6e432a568b0638c37c_Microsoft.PowerShell_profile.ps1
# Update with PowerShell: # PS> notepad $profile # Use Git and Posh-Git from GitHub for Windows # Source: http://blog.somewhatabstract.com/2014/09/01/getting-posh-git-in-all-your-powershell-consoles-using-github-for-windows/ # Add paths for Git and Posh-Git from GitHub for Windows # - (git)\cmd => gives access to "git.cmd" # - (git)\bin => gives access to "ssh-agent.exe" . (Resolve-Path "$env:LOCALAPPDATA\GitHub\shell.ps1") # Load Posh-Git example profile . (Resolve-Path "$env:github_posh_git\profile.example.ps1") # Add an empty line before Posh-Git prompt rename-item function:prompt prompt_pg function global:prompt { Write-Host("") prompt_pg } # Set page code to get french accents with Ruby # http://blog.pagesd.info/post/2012/12/18/windows-powershell-ruby-accents chcp 1252
PowerShellCorpus/GithubGist/gravejester_1c9e354ff726d6d78ae2_raw_6ea816b626b6bfa6fd250a42eb9089917b738238_Write-PluralString.ps1
gravejester_1c9e354ff726d6d78ae2_raw_6ea816b626b6bfa6fd250a42eb9089917b738238_Write-PluralString.ps1
function Write-PluralString{ <# .SYNOPSIS Write string with built-in handling of plural-s for variable integer. .DESCRIPTION Write string with built-in handling of plural-s for variable integer. .EXAMPLE Write-PluralString "$($computer): " $num 'file' 'processed' .EXAMPLE Write-Verbose (Write-PluralString "$($computer): " $num 'file' 'processed') .EXAMPLE Write-PluralString '' $num 'file' $processed Omitting the PreString .NOTES Name: Write-PluralString Author: Øyvind Kallstad Created: 18.08.2014 Version: 1.0 #> [CmdletBinding()] param ( # Define a starting string. [Parameter(Position = 0, Mandatory = $false)] [string]$PreString, # Integer that will be used as part of the string, and will decide if the StringPart should include the plural-s or not. [Parameter(Position = 1, Mandatory = $true)] [int]$IntPart, # String that will display with or without 's' based on value of the integer before it [Parameter(Position = 2, Mandatory = $true)] [ValidateNotNullorEmpty()] [string]$StringPart, # Define a string to display at the end. [Parameter(Position = 3, Mandatory = $false)] [string]$PostString ) Write-Output "$(@{$false="$($PreString) "}[[System.String]::IsNullOrWhiteSpace($PreString)])$($IntPart) $(@{$true = $StringPart; $false = "$($StringPart)s"}[$IntPart -eq 1]) $($PostString)" }
PowerShellCorpus/GithubGist/jstangroome_1440889_raw_f398b09019eb3d902d336a8207692f65f716740d_Set-AssemblyInfoVersion.ps1
jstangroome_1440889_raw_f398b09019eb3d902d336a8207692f65f716740d_Set-AssemblyInfoVersion.ps1
$NewVersion = '10.1.2.3' Get-ChildItem -Include assemblyinfo.cs, assemblyinfo.vb -Recurse | ForEach-Object { $_.IsReadOnly = $false (Get-Content -Path $_) -replace '(?<=Assembly(?:File)?Version\(")[^"]*(?="\))', $NewVersion | Set-Content -Path $_ }
PowerShellCorpus/GithubGist/jeffpatton1971_8187784_raw_f5ba8b691979ed3b477c299410e1d795ebe4c6db_AddDSCService.ps1
jeffpatton1971_8187784_raw_f5ba8b691979ed3b477c299410e1d795ebe4c6db_AddDSCService.ps1
Configuration DSCPullServer { param ( [string]$ComputerName ) Node $ComputerName { WindowsFeature DSCService { Name = "DSC-Service" Ensure = "Present" Source = "C:\Windows\SxS" } } }
PowerShellCorpus/GithubGist/vladan-m_1c3e382effa993f00d36_raw_ef2f8063e44b7ca713e92bba939d8ff75b94d447_mac-hidden-files.ps1
vladan-m_1c3e382effa993f00d36_raw_ef2f8063e44b7ca713e92bba939d8ff75b94d447_mac-hidden-files.ps1
# Run Terminal and enter this command. It's for showing hidden files: defaults write com.apple.finder AppleShowAllFiles YES # You must relaunch the Finder by killing it, this is how the changes take effect: killAll Finder # If you want to hide hidden files (those preceded with a .) and go back to the default Mac settings, you can just type the following: defaults write com.apple.finder AppleShowAllFiles NO # Again you will need to kill the Finder so that it can relaunch for changes to take effect: killAll Finder
PowerShellCorpus/GithubGist/AmrEldib_de4e018fe11a98b42a18_raw_3cf900d1d2e9fabb5d88d8271a87021401fb0c85_Get-SqlServiceStatus.ps1
AmrEldib_de4e018fe11a98b42a18_raw_3cf900d1d2e9fabb5d88d8271a87021401fb0c85_Get-SqlServiceStatus.ps1
function Get-SqlServiceStatus ($serviceName) { # Get a reference to the service $sqlService = Get-Service $serviceName # Return the service status return $sqlService.status }
PowerShellCorpus/GithubGist/kujotx_6902269_raw_c1aa9c9cb616c6981e41b33c44d40da0c2628733_Chocolatey-Vs2010-Devbox.ps1
kujotx_6902269_raw_c1aa9c9cb616c6981e41b33c44d40da0c2628733_Chocolatey-Vs2010-Devbox.ps1
choco windowsfeatures MSMQ-Container choco windowsfeatures MSMQ-Server choco install Firefox choco install Google.Chrome choco install webpicommandline choco webpi msdeploy choco webpi iisexpress choco install TeraCopy choco install windbg choco install windowstelnet choco install wireshark choco install winsplit choco install ferventcoder.utilities choco install winmerge choco install lockhunter choco install ack choco install autohotkey choco install camstudio choco install msysgit choco install git.install choco install gitextensions choco install git-credential-winstore choco install git.alias.standup choco install gittfs choco install Devbox-GitFlow choco install TortoiseGit choco install poshgit choco install SourceTree choco install tfpt choco install tfsSidekicks2010 choco install Growl choco install Wix35 choco install papercut choco install warmup choco install ilmerge choco install NuGet.CommandLine choco install Nuget.Core choco install NuGet.Server choco install resharper choco install dotPeek choco install ruby choco install Machine.Specifications.tools.resharper80 choco install Microsoft.Web.Infrastructure choco install mspeclivetemplates
PowerShellCorpus/GithubGist/sheeeng_7235195_raw_35049a2c2c3763fc2aa2f245b0b4cbed570d7d0d_GetDependencyWalker.ps1
sheeeng_7235195_raw_35049a2c2c3763fc2aa2f245b0b4cbed570d7d0d_GetDependencyWalker.ps1
######################################################################## # File : GetDependencyWalker.ps1 # Version : 1.0.0 # Purpose : Downloads the Dependency Walker tool. # Synopsis: http://www.dependencywalker.com/ # Usage : .\GetDependencyWalker.ps1 ("x86","x64","ia64","32","64") # Author: Leonard Lee <sheeeng@gmail.com> ######################################################################## # References: # Manage BITS (Background Intelligent Transfer Service) with Windows PowerShell # http://technet.microsoft.com/en-us/magazine/ff382721.aspx # Using Windows PowerShell to Create BITS Transfer Jobs # http://msdn.microsoft.com/en-us/library/windows/desktop/ee663885(v=vs.85).aspx # Copying Folders by Using the Shell Folder Object # http://technet.microsoft.com/en-us/library/ee176633.aspx ######################################################################## Param( [ValidateSet("x86","x64","ia64","32","64")] [parameter(Mandatory=$true, Position=1)] [alias("Versi")] $Version) if($Version) { Write-Host "You have selected $Version version." } else { Write-Host "Version is empty!" Break } Import-Module BitsTransfer $DebugPreference = "SilentlyContinue" #Continue Write-Debug $DebugPreference Set-Location $HOME $currentDirectory = $HOME if ($Version -eq "x86" -or $Version -eq "32") { $zipFile = "depends22_x86.zip" $targetDirectory = $HOME.ToString() + "\" + "depends22_x86" $downloadLink = "http://www.dependencywalker.com/depends22_x86.zip" } elseif ($Version -eq "x64" -or $Version -eq "64") { $zipFile = "depends22_x64.zip" $targetDirectory = $HOME.ToString() + "\" + "depends22_x64" $downloadLink = "http://www.dependencywalker.com/depends22_x64.zip" } elseif ($Version -eq "ia64") { $zipFile = "depends22_ia64.zip" $targetDirectory = $HOME.ToString() + "\" + "depends22_ia64" $downloadLink = "http://www.dependencywalker.com/depends22_ia64.zip" } else { Break } $sourceZipFile = $currentDirectory + "\" + $zipFile if (Test-Path -path $targetDirectory) { Write-Host "The" $targetDirectory "directory exist." } else { Write-Host "Creating" $targetDirectory "directory since it does not exist." New-Item -ItemType directory -Path $targetDirectory } Start-BitsTransfer -Source $downloadLink function Expand-ZIPFile($file, $destination) { #Write-Host "`$file:" $file #Write-Host "`$destination:" $destination $shell = New-Object -ComObject Shell.Application $zip = $shell.NameSpace($file) foreach($item in $zip.items()) { $shell.Namespace($destination).CopyHere($item, 0x14) } } $processName = "depends" if (Get-Process $processName -ErrorAction SilentlyContinue) { #Write-Host "The" $processName "process exist. Trying to stop..." Stop-Process -processname $processName } else { #Write-Host "The" $processName "process does not exist." } Expand-ZIPFile –File $sourceZipFile $targetDirectory Write-Host "Update completed." #Invoke-Item $targetDirectory
PowerShellCorpus/GithubGist/AaronOnTheHub_459a93f979ee6e9e137a_raw_faad997afaac3a6d86e8f08e82397ad846b50a04_Log.ps1
AaronOnTheHub_459a93f979ee6e9e137a_raw_faad997afaac3a6d86e8f08e82397ad846b50a04_Log.ps1
############################################################################## #.SYNOPSIS # Writes some text, with bonus infoz! # #.DESCRIPTION # Before each line, includes the date and time. Useful for getting coffee and # seeing how long something took. Hah. # #.PARAMETER output # The text to write. Out. Why is called putting? Then it'd be like putting out? # #.EXAMPLE # Log "Yeah." ############################################################################## function Log { param ( [String] $output ) function Time-Stamp { return [System.DateTime]::Now.ToString("yyyy.MM.dd hh:mm:ss"); } Write-Host "$(Time-Stamp): $output"; };
PowerShellCorpus/GithubGist/pkirch_3da0bec11b5ea037185e_raw_1b28fbbdcebaa135d9062a529c6a5f0eac9713e9_Get-SubscriptionEndpoints3.ps1
pkirch_3da0bec11b5ea037185e_raw_1b28fbbdcebaa135d9062a529c6a5f0eac9713e9_Get-SubscriptionEndpoints3.ps1
# Get all Azure VMs in the current subscription. 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 <# Output ServiceName InstanceName Vip Protocol ExternalPort InternalPort DNSName ----------- ------------ --- -------- ------------ ------------ ------- leasetest2 host2 104.40.188.19 PowerShell 5986 5986 http://leasetest2.cloudapp.net/ leasetest2 host2 104.40.188.19 Remote Desktop 56595 3389 http://leasetest2.cloudapp.net/ leasetest4 host4 191.233.81.126 PowerShell 5986 5986 http://leasetest4.cloudapp.net/ leasetest4 host4 191.233.81.126 Remote Desktop 61942 3389 http://leasetest4.cloudapp.net/ leasetest5 host5 137.117.194.91 PowerShell 5986 5986 http://leasetest5.cloudapp.net/ leasetest5 host5 137.117.194.91 Remote Desktop 63809 3389 http://leasetest5.cloudapp.net/ #>
PowerShellCorpus/GithubGist/vScripter_add54f2af5c16c1f1d56_raw_416c44c29ff3a001afc94c4411c5e9d21b6b52b9_Get-NetStat.ps1
vScripter_add54f2af5c16c1f1d56_raw_416c44c29ff3a001afc94c4411c5e9d21b6b52b9_Get-NetStat.ps1
function Get-NetStat { <# .SYNOPSIS This function will get the output of netstat -n and parse the output .DESCRIPTION This function will get the output of netstat -n and parse the output. Credit goes to PowerShell MVP Francois-Xavier Cat, who wrote the orignial function to parse the output of netstat.exe -n. I added the ability to query info from a remote system via Invoke-Command (requires that PowerShell remoting be enabled on the destination system), and then use the same functionality in the original script to parse the output. .PARAMETER ComputerName Name of remote system to query .LINK http://www.lazywinadmin.com/2014/08/powershell-parse-this-netstatexe.html .LINK www.github.com/vN3rd #> [cmdletbinding()] param ( [parameter(Mandatory = $false, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateScript({ Test-Connection -ComputerName $_ -Count 2 -Quiet })] [string]$ComputerName = 'localhost' ) BEGIN { if ($ComputerName -eq 'localhost') { $NetStat = netstat.exe -n } else { $NetStat = Invoke-Command -ComputerName $ComputerName -ScriptBlock { netstat.exe -n } }# end if/else }# end BEGIN PROCESS { # Keep only the line with the data (we remove the first lines) $NetStat = $NetStat[4..$NetStat.count] # Each line need to be splitted and get rid of unnecessary spaces foreach ($line in $NetStat) { # Get rid of the first whitespaces, at the beginning of the line $line = $line -replace '^\s+', '' # Split each property on whitespaces block $line = $line -split '\s+' # Define the properties $properties = @{ Protocole = $line[0] LocalAddressIP = ($line[1] -split ":")[0] LocalAddressPort = ($line[1] -split ":")[1] ForeignAddressIP = ($line[2] -split ":")[0] ForeignAddressPort = ($line[2] -split ":")[1] State = $line[3] } # Output the current line New-Object -TypeName PSObject -Property $properties }# end foreach }# end PROCESS }# end function Get-NetStat
PowerShellCorpus/GithubGist/guitarrapc_3d52bab84734149ffba8_raw_f59f028b875ecb00bad9c6eeaa27188f79b9e78d_ConfigrationWithoutConfiguraionData.ps1
guitarrapc_3d52bab84734149ffba8_raw_f59f028b875ecb00bad9c6eeaa27188f79b9e78d_ConfigrationWithoutConfiguraionData.ps1
# コンフィグレーション (あるべき状態) Configuration Service { param ( [Parameter(Mandatory = 0)] [ValidateNotNullOrEmpty()] [string]$Role = "web" ) $service = $Allnodes.Where{$_.Role -eq $Role}.Service $state = "Running" $startupType = "Automatic" Node $Allnodes.Where{$_.Role -eq $Role}.NodeName { foreach ($x in $service) { Service $x { Name = $x State = $state StartupType = $startupType } } } }
PowerShellCorpus/GithubGist/guitarrapc_43c8fb9f930bbcca3c16_raw_1308f631ef8b90f025936b64b94bc1068dbef225_cDonwloadConfigurationSample.ps1
guitarrapc_43c8fb9f930bbcca3c16_raw_1308f631ef8b90f025936b64b94bc1068dbef225_cDonwloadConfigurationSample.ps1
configuration DownloadGitHubRawContent { Import-DscResource -ModuleName GraniResource cDownload hoge { DestinationPath = "C:\Tools\README.md" Uri = "https://raw.githubusercontent.com/guitarrapc/DSCResources/master/README.md" } } DownloadGitHubRawContent Start-DscConfiguration -Wait -Verbose -Force -Path DownloadGitHubRawContent
PowerShellCorpus/GithubGist/mhornfeck_ca67016a3ce77c429a0a_raw_fab811d7ce1a92fa104b7e3c58a129434aca98e6_gistfile1.ps1
mhornfeck_ca67016a3ce77c429a0a_raw_fab811d7ce1a92fa104b7e3c58a129434aca98e6_gistfile1.ps1
Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -EnableShowProtectedOSFiles -EnableShowFileExtensions Enable-RemoteDesktop cinst Microsoft-Hyper-V-All -source windowsFeatures cinst IIS-WebServerRole -source windowsfeatures # Browsers cinstm GoogleChrome cinstm Firefox # Runtimes cinstm Silverlight cinstm javaruntime # Desktop tools cinst fiddler4 cinst evernote cinst filezilla cinst dropbox cinst virtualclonedrive # Fun stuff cinst spotify # Editors cinstm nano cinst sublimetext2 cinst brackets # Git, merge cinst git-credential-winstore cinst poshgit cinst p4merge # Visual Studio # cinst VisualStudio2013Professional -InstallArguments "/Features:'WebTools Win8SDK' /ProductKey:AB1CD-EF2GH-IJ3KL-MN4OP-QR5ST" # VS related extras cinst NugetPackageExplorer cinst resharper cinst dotpeek cinst dotcover
PowerShellCorpus/GithubGist/chriseyre2000_f8ddea2acbc6df9a28d8_raw_69eaa7de6403ba97560ca4358881ce0114f8f3a7_powershell-web-server.ps1
chriseyre2000_f8ddea2acbc6df9a28d8_raw_69eaa7de6403ba97560ca4358881ce0114f8f3a7_powershell-web-server.ps1
function Load-Packages { param ([string] $directory = 'Packages') $assemblies = Get-ChildItem $directory -Recurse -Filter '*.dll' | Select -Expand FullName foreach ($assembly in $assemblies) { [System.Reflection.Assembly]::LoadFrom($assembly) } } Load-Packages $routes = @{ "/ola" = { return '<html><body>Hello world!</body></html>' } } $url = 'http://localhost:8181/' $listener = New-Object System.Net.HttpListener $listener.Prefixes.Add($url) $listener.Start() Write-Host "Listening at $url..." while ($listener.IsListening) { $context = $listener.GetContext() $requestUrl = $context.Request.Url $response = $context.Response Write-Host '' Write-Host "> $requestUrl" $localPath = $requestUrl.LocalPath $route = $routes.Get_Item($requestUrl.LocalPath) if ($route -eq $null) { $response.StatusCode = 404 } else { $content = & $route $buffer = [System.Text.Encoding]::UTF8.GetBytes($content) $response.ContentLength64 = $buffer.Length $response.OutputStream.Write($buffer, 0, $buffer.Length) } $response.Close() $responseStatus = $response.StatusCode Write-Host "< $responseStatus" }
PowerShellCorpus/GithubGist/FrankDeGroot_144016341fb00e19b969_raw_5aace9a1208c353346ac26deb0f44add98003bad_Parameters.ps1
FrankDeGroot_144016341fb00e19b969_raw_5aace9a1208c353346ac26deb0f44add98003bad_Parameters.ps1
$environment = 'dev' # 'dev', 'test' or 'production' $packagesDir = 'C:\Users\Administrator\Downloads\_PublishedWebsites' $siteDir = 'C:\inetpub\wwwroot' $domain = switch ($environment) { 'dev' { (Get-ChildItem ENV:computername).Value } default { 'OFFICE' } } $sqlServerInstance = '.' $reportServerUrl = 'http://rsbio01/ReportServer_ONTWIKKEL.123' $certPath = 'Cert:\LocalMachine\WebHosting' $certs = @() $dummyCerts = @( @{ friendlyName = 'test'; # Use '0.0.0.0' instead of '*' (for HTTP.SYS). ip = '0.0.0.0'; port = '8000'; host = ''; #'mo.office.rovict.nl'; }, @{ friendlyName = 'test'; # Use '0.0.0.0' instead of '*' (for HTTP.SYS). ip = '0.0.0.0'; port = '8001'; host = ''; #'moauthservice.office.rovict.nl'; }, @{ friendlyName = 'test'; # Use '0.0.0.0' instead of '*' (for HTTP.SYS). ip = '0.0.0.0'; port = '8002'; host = ''; #'moauthclient.office.rovict.nl'; } ) $sites = @( @{ domain = $domain; user = 'MOWebsite_User'; password = '34g1a0t5SQ/GG6+'; appPool = 'MOWebSiteAppPool'; name = 'MO'; scheme = 'http'; #'https'; ip = '*'; port = '8000'; host = ''; #'mo.office.rovict.nl'; dir = $siteDir; package = '01 - Rovict.MO.WebApp'; sqlRoles = ( @{ db = 'MO'; role = 'roleWebApplication' }, @{ db = 'MO_Token'; role = 'roleWebApplication' }, @{ db = 'MO_Logging'; role = 'roleLogger' } ); }, @{ domain = $domain; user = 'MOAuthService_User'; password = '34g1a0t5SQ/GG6+'; appPool = 'MOAuthServiceAppPool'; name = 'MOAuthService'; scheme = 'http'; #'https'; ip = '*'; port = '8001'; host = ''; #'moauthservice.office.rovict.nl'; dir = $siteDir; package = '02 - Rovict.MO.AuthenticationService'; sqlRoles = ( @{ db = 'MO_Token'; role = 'roleAuthenticationService' }, @{ db = 'MO_Logging'; role = 'roleLogger' } ); }) # Add authentication client for dev and test. switch -Regex ($environment) { 'dev|test' { $sites += @{ domain = $domain; user = ''; password = ''; appPool = 'MOAuthClient'; name = 'MOAuthClient'; scheme = 'http'; #'https'; ip = '*'; port = '8002'; host = ''; #'moauthclient.office.rovict.nl'; dir = $siteDir; package = '05 - Rovict.MO.AuthenticationClient'; } } }
PowerShellCorpus/GithubGist/omidkrad_fbb4bfb3b1f5b83c9898_raw_412ad101d527addc84ed474b65c5cc762ea59193_ExecJavaScript.ps1
omidkrad_fbb4bfb3b1f5b83c9898_raw_412ad101d527addc84ed474b65c5cc762ea59193_ExecJavaScript.ps1
# some web page with jQuery in it $url = "http://jquery.com/" Function ResetTimer { $script:startTime = [DateTime]::Now } Function IsTimeout([TimeSpan]$timeout) { return ([DateTime]::Now - $startTime) -ge $timeout } Function WaitForIE { $ie = $script:ie Write-Debug "Waiting..." ResetTimer do { if (IsTimeout ([TimeSpan]::FromSeconds(30))) { Write-Error "IE response timed out."; ExitFailure } Start-Sleep -m 100 } until ( $ie.ReadyState -eq 4 -and $ie.Document.readyState -eq 'complete') } # Use this function to run JavaScript on a web page. Your $jsCommand can # return a value which will be returned by this function unless $global # switch is specified in which case $jsCommand will be executed in global # scope and cannot return a value. If you received error 80020101 it means # you need to fix your JavaScript code. Function ExecJavaScript($ie, $jsCommand, [switch]$global) { if (!$global) { $jsCommand = "document.body.setAttribute('PSResult', (function(){$jsCommand})());" } WaitForIE $document = $ie.document $window = $document.parentWindow $window.execScript($jsCommand, 'javascript') | Out-Null if (!$global) { return $document.body.getAttribute('PSResult') } } Function CheckJQueryExists { $result = ExecJavaScript $ie 'return window.hasOwnProperty("$");' return ($result -eq $true) } $ie = New-Object -COM InternetExplorer.Application -Property @{ Navigate = $url Visible = $true } do { Start-Sleep -m 100 } while ( $ie.ReadyState -ne 4 ) $jQueryExists = CheckJQueryExists $ie echo "jQuery exists? $jQueryExists" # make a jQuery call ExecJavaScript $ie @' // this is JS code, remember to use semicolons var content = $('#home-content'); return content.text(); '@ # Quit and dispose IE COM $ie.Quit() [System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie) | out-null Remove-Variable ie
PowerShellCorpus/GithubGist/bewilcox_7105046_raw_5e02ca60fcdd473634eb2547fd2652d0ce66d47f_gistfile1.ps1
bewilcox_7105046_raw_5e02ca60fcdd473634eb2547fd2652d0ce66d47f_gistfile1.ps1
#!/bin/bash export VERTX_MOD_NAME=<mod-name> PATH="${OPENSHIFT_DATA_DIR}vert.x-2.0.2-final/bin:${OPENSHIFT_DATA_DIR}jdk1.7.0_45/bin:$PATH" JAVA_HOME="${OPENSHIFT_DATA_DIR}jdk1.7.0_45" cd ${OPENSHIFT_DATA_DIR}mods nohup bash -c "exec 'vertx' 'runmod' ${VERTX_MOD_NAME} '-cd ./'${VERTX_MOD_NAME} &> ${OPENSHIFT_DIY_LOG_DIR}${VERTX_MOD_NAME.log"
PowerShellCorpus/GithubGist/matiasherranz-santex_9785941_raw_6815ecea70ede8efca6b5533af6323064a3e04c7_gistfile1.ps1
matiasherranz-santex_9785941_raw_6815ecea70ede8efca6b5533af6323064a3e04c7_gistfile1.ps1
$ git init
PowerShellCorpus/GithubGist/altrive_6487560_raw_cfc0233adbd59cad4208e586b5c29a1ead60395e_Install-PSModule.ps1
altrive_6487560_raw_cfc0233adbd59cad4208e586b5c29a1ead60395e_Install-PSModule.ps1
function Install-PSModule { [CmdletBinding()] param( [Parameter(Mandatory)] [string] $ModuleName, [Parameter(Mandatory,ParameterSetName="Local")] [string] $Path, [ValidateSet("User","System","ProgramFiles","Local")] [string] $Target = "User" ) $ErrorActionPreference = "Stop" Set-StrictMode -Version Latest if(!(Test-Path $Path -PathType Container)){ Write-Error ("Directory is not found! : {0}" -f $Path) } #Resolve target module base directory switch($Target) { "Local"{ $moduleBasePath = Join-Path (Resolve-Path .) "Modules" #Use Current Directory } default{ $moduleBasePath = $env:PSModulePath.Split(";") | where {$_.StartsWith([Environment]::GetFolderPath($Target),[StringComparison]::InvariantCultureIgnoreCase)} | select -First 1 } } if([String]::IsNullOrEmpty($moduleBasePath)){ throw ("PowerShell module path is not found for target({0})" -f $Target) } #Set target module directory $modulePath = Join-Path $moduleBasePath $ModuleName #Change current directory to get relative path Push-Location -Path $Path try{ $items = Get-ChildItem -File -Recurse #Get files under current directory Write-Verbose ("Install PowerShell module to '{0}'..." -f $modulePath) foreach($item in $items) { #Relative path to CopyFrom basepath $relativePath = Resolve-Path $item.FullName -Relative #Copy file operation target path $destination = Join-Path $modulePath $relativePath #Create directory if not exist already (New-Object IO.FileInfo($destination)).Directory.Create() Write-Verbose ("`tCopy file '{0}'" -f $relativePath) Copy-Item -Path $item.FullName -Destination $destination -Force } } finally { Pop-Location -ErrorAction Ignore } }
PowerShellCorpus/GithubGist/talatham_5765869_raw_a19c339cc95919630aa1bb5b5f62c7ca46ae4ea3_listupdates.ps1
talatham_5765869_raw_a19c339cc95919630aa1bb5b5f62c7ca46ae4ea3_listupdates.ps1
$Session = New-Object -ComObject Microsoft.Update.Session $Searcher = $Session.CreateUpdateSearcher() $HistoryCount = $Searcher.GetTotalHistoryCount() $Searcher.QueryHistory(1,$HistoryCount) | Select-Object Date, Title, Description