full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/troyhunt_9e1c5094a6eef536804c_raw_d7ad1159b13208669741a830e47066c5f3c186ff_DeleteAzureResources.ps1
troyhunt_9e1c5094a6eef536804c_raw_d7ad1159b13208669741a830e47066c5f3c186ff_DeleteAzureResources.ps1
# Input params $projectName = "TroyPSTest" # Constants $dbServerName = "snyb5o1pxk" $dbServerLogin = "troyhunt" $dbServerPassword = "P@ssw0rd" $apiVersion = "2014-04-01" # Computed vars $dbName = $projectName + "Db" $dbLogin = $dbName + "Login" # Switch over to the resource manager Switch-AzureMode AzureResourceManager # Remove the tag from the website $p = Get-AzureResource -Name $projectName -ResourceGroupName $webResourceGroup -ResourceType Microsoft.Web/sites -ApiVersion $apiVersion Set-AzureResource -Name $projectName -ResourceGroupName $webResourceGroup -ResourceType Microsoft.Web/sites -ApiVersion $apiVersion -PropertyObject $p.Properties -Tags @{ } # Remove the tag from the DB Set-AzureResource -Name $dbName -ResourceGroupName $dbResourceGroup -ParentResource servers/$dbServerName -ResourceType Microsoft.Sql/servers/databases -ApiVersion $apiVersion -Tags @{ } # Delete the tag (if you try to only delete, it may still be attached to resources even if you've already deleted THEM!) Remove-AzureTag -Name Project -Value $projectName -Force # Make sure we kick off in service management mode Switch-AzureMode AzureServiceManagement # Delete the website Remove-AzureWebsite $projectName -Force # Delete the database Remove-AzureSqlDatabase -ServerName $dbServerName -DatabaseName $dbName -Force # Delete the SQL login Import-Module SQLPS -DisableNameChecking $conn = New-Object System.Data.SqlClient.SqlConnection $conn.ConnectionString = "Server=tcp:" + $dbServerName + ".database.windows.net;Database=master;User ID=" + $dbServerLogin + ";Password=" + $dbServerPassword + ";" $srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $conn $srv.Logins[$dbLogin].Drop()
PowerShellCorpus/GithubGist/virgilwashere_7157263_raw_5bcb507ec0cbe0b18a1c42b45a72c4304898aae9_breakonexception.ps1
virgilwashere_7157263_raw_5bcb507ec0cbe0b18a1c42b45a72c4304898aae9_breakonexception.ps1
# You can add this line in your profile instead of here... Set-PSBreakpoint -Variable BreakOnException -Mode ReadWriteWrite-Host "Enter"# then just add this where you want to enable breaking on exceptionstrap { $BreakOnException; continue }Write-Host "Starting"throw "stones"Write-Host "Ending"
PowerShellCorpus/GithubGist/jhorsman_8454479_raw_3b6225eb530b597463120780a52107756d357de2_verifyDotNetVersion.ps1
jhorsman_8454479_raw_3b6225eb530b597463120780a52107756d357de2_verifyDotNetVersion.ps1
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | Get-ItemProperty -name Version -EA 0 | Where { $_.PSChildName -match '^(?!S)\p{L}'} | Select PSChildName, Version
PowerShellCorpus/GithubGist/sunnyc7_8734060_raw_1f97f5c93e5df8b2400d4647f066449d051bfc4b_Get-InstalledProducts.ps1
sunnyc7_8734060_raw_1f97f5c93e5df8b2400d4647f066449d051bfc4b_Get-InstalledProducts.ps1
#Get MOF File Method $mof = @' #PRAGMA AUTORECOVER [dynamic, provider("RegProv"), ProviderClsid("{fe9af5c0-d3b6-11ce-a5b6-00aa00680c3f}"),ClassContext("local|HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall")] class SG_InstalledProducts { [key] string KeyName; [read, propertycontext("DisplayName")] string DisplayName; [read, propertycontext("DisplayVersion")] string DisplayVersion; [read, propertycontext("InstallDate")] string InstallDate; [read, propertycontext("Publisher")] string Publisher; [read, propertycontext("EstimatedSize")] string EstimatedSize; [read, propertycontext("UninstallString")] string UninstallString; [read, propertycontext("WindowsInstaller")] string WindowsInstaller; }; [dynamic, provider("RegProv"), ProviderClsid("{fe9af5c0-d3b6-11ce-a5b6-00aa00680c3f}"),ClassContext("local|HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432node\\Microsoft\\Windows\\CurrentVersion\\Uninstall")] class SG_InstalledProducts32 { [key] string KeyName; [read, propertycontext("DisplayName")] string DisplayName; [read, propertycontext("DisplayVersion")] string DisplayVersion; [read, propertycontext("InstallDate")] string InstallDate; [read, propertycontext("Publisher")] string Publisher; [read, propertycontext("EstimatedSize")] string EstimatedSize; [read, propertycontext("UninstallString")] string UninstallString; [read, propertycontext("WindowsInstaller")] string WindowsInstaller; }; '@ $mof | Out-file -encoding ascii $env:TMP\SG_Mof.txt mofcomp.exe $env:TMP\SG_Mof.txt #Remove-Item $env:TMP\SG_Mof.txt Get-WmiObject -Namespace root\default -class SG_InstalledProducts | Select DisplayName,DisplayVersion,InstallDate,Publisher,EstimatedSize,UninstallString,WindowsInstaller | Export-csv -notypeInformation $pwd\InstalledProducst-MOF.csv -Append Remove-WmiObject -Namespace root\default -class SG_InstalledProducts Remove-WmiObject -Namespace root\default -class SG_InstalledProducts32
PowerShellCorpus/GithubGist/randomvariable_6380009_raw_136a2129f15e414165ae01b56c32b2a6f412ac42_gistfile1.ps1
randomvariable_6380009_raw_136a2129f15e414165ae01b56c32b2a6f412ac42_gistfile1.ps1
# Create a Windows Identity Principal (note the cast) $principal = [Security.Principal.WindowsPrincipal](new-object System.Security.Principal.WindowsIdentity("<username>@<domain>")) # Check if it is a member of a group $princial.IsInRole("<domain>\<group name>") # Other useful things you can do: $identity = (new-object System.Security.Principal.WindowsIdentity("<username>@<domain>")) # Token size $identity.Token # Groups $identity.Groups
PowerShellCorpus/GithubGist/rahulrrixe_9496056_raw_86e8734557eb7f45b1e7cae60386559a7fe72167_gistfile1.ps1
rahulrrixe_9496056_raw_86e8734557eb7f45b1e7cae60386559a7fe72167_gistfile1.ps1
(libREST)[rranjan@localhost libcloud.rest]$ python libcloud_rest/server.py Traceback (most recent call last): File "libcloud_rest/server.py", line 101, in <module> main() File "libcloud_rest/server.py", line 97, in main logger=logger, debug=options.debug) File "libcloud_rest/server.py", line 19, in start_server from libcloud_rest.application import LibcloudRestApp File "/home/rranjan/.virtualenvs/libREST/lib/python2.7/site-packages/libcloud_rest-0.0.1-py2.7.egg/libcloud_rest/application.py", line 7, in <module> from libcloud_rest.api.urls import urls File "/home/rranjan/.virtualenvs/libREST/lib/python2.7/site-packages/libcloud_rest-0.0.1-py2.7.egg/libcloud_rest/api/urls.py", line 6, in <module> from libcloud_rest.api.handlers.compute import compute_handler ImportError: No module named handlers.compute (libREST)[rranjan@localhost libcloud.rest]$
PowerShellCorpus/GithubGist/jjhamshaw_3305817_raw_e989fbb20fdf9099522888f70fb4e84d91af2fda_gistfile1.ps1
jjhamshaw_3305817_raw_e989fbb20fdf9099522888f70fb4e84d91af2fda_gistfile1.ps1
task BackupTestToQaDatabase { try { Invoke-Sqlcmd -InputFile $copySqlDatabase -ServerInstance $sqlserver -Database $databaseToBackUp -Username $databaseUsername -Password $databasePassword -QueryTimeout 240 -ErrorAction 'Stop' } catch { '##teamcity[buildStatus status='FAILURE' text='Build Failed']' } }
PowerShellCorpus/GithubGist/idavis_3314814_raw_f8a011c622ffdb63d6fc9579c7fbce525625d986_Get-Distance.ps1
idavis_3314814_raw_f8a011c622ffdb63d6fc9579c7fbce525625d986_Get-Distance.ps1
$point = new-object psobject $point | Add-Member NoteProperty -Name X -Value 4 $point | Add-Member NoteProperty -Name Y -Value 0 $point2 = new-object psobject $point2 | Add-Member NoteProperty -Name X -Value 0 $point2 | Add-Member NoteProperty -Name Y -Value 0 function Get-Distance { param( [Parameter(Position=0,Mandatory=$True)] [psobject]$origin, [Parameter(Position=1,Mandatory=$True,ParameterSetName="point")] [psobject]$point, [Parameter(Position=1,Mandatory=$True,ParameterSetName='xy')] [int]$x, [Parameter(Position=2,Mandatory=$True,ParameterSetName='xy')] [int]$y ) switch ($PsCmdlet.ParameterSetName) { "point" { return [Math]::Sqrt( [Math]::Pow(($origin.x - $point.x),2) + [Math]::Pow(($origin.y - $point.y),2)) } "xy" { return [Math]::Sqrt( [Math]::Pow(($origin.x - $x),2) + [Math]::Pow(($origin.y - $y),2)) } } } Get-Distance $point $point2 Get-Distance $point 0 0
PowerShellCorpus/GithubGist/dfrencham_605cdcc653f07bdd5a79_raw_c2b86d43b5228a65cb312b81b092f952a656079b_gistfile1.ps1
dfrencham_605cdcc653f07bdd5a79_raw_c2b86d43b5228a65cb312b81b092f952a656079b_gistfile1.ps1
# One liner! # Finds all duplicate CSS classes in a CSS file, and ignores hex colour codes (the #DDDDDD pattern would be a false positve) Get-Content .\filename.css | ForEach-Object { $_.Split(" ,.", [System.StringSplitOptions]::RemoveEmptyEntries) } | ForEach-Object { $_.Trim() } | where { ($_[0] -eq "#" -or $_[0] -eq "." ) -and (!$_.EndsWith(";")) } | where {$_ -notmatch '#[0-9a-fA-F]{2,}$'} | sort-object | group-object | where-object { $_.Count -gt 1 }
PowerShellCorpus/GithubGist/plioi_5359834_raw_60dce0bbb77f484e197c9b140a8a99a2673ed77e_gistfile1.ps1
plioi_5359834_raw_60dce0bbb77f484e197c9b140a8a99a2673ed77e_gistfile1.ps1
task Package -depends xUnitTest { rd .\package -recurse -force -ErrorAction SilentlyContinue | out-null mkdir .\package -ErrorAction SilentlyContinue | out-null exec { & $src\.nuget\NuGet.exe pack $src\$project\$project.csproj -Symbols -Prop Configuration=$configuration -OutputDirectory .\package } write-host write-host "To publish these packages, issue the following command:" write-host " nuget push .\package\$project.$version.nupkg" }
PowerShellCorpus/GithubGist/joshtransient_5984592_raw_1375357910aff3cc8e8445ea8e2f08627eee4c4e_Convert-HashtableXML.ps1
joshtransient_5984592_raw_1375357910aff3cc8e8445ea8e2f08627eee4c4e_Convert-HashtableXML.ps1
$tr = New-Object system.Xml.XmlTextReader("c:\metrics\scripts\out.xml") $tw = New-Object system.Xml.XmlTextWriter("c:\metrics\scripts\fullmig.xml",$null) $tw.WriteStartDocument() # 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()
PowerShellCorpus/GithubGist/n-fukuju_8487441_raw_397ce52f2951f1e8edb2b6c510b397ac82766825_getlogonuser.ps1
n-fukuju_8487441_raw_397ce52f2951f1e8edb2b6c510b397ac82766825_getlogonuser.ps1
$target = "対象のホスト名か、IPアドレス" $logonUser = (Get-WmiObject Win32_ComputerSystem -ComputerName $target).UserName # リモートアクセスの資格情報を明示的に指定する場合 $admin = "ユーザ名" $pass = "パスワード" $securePass = ConvertTo-SecureString -String $pass -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential($admin, $securePass) # コンソールから入力するなら、PromptForCredentialを使った方が楽 # $credential = $host.UI.PromptForCredential("資格情報入力", "","","") $logonUser = (Get-WmiObject Win32_ComputerSystem -ComputerName $target -Credential $credential).UserName # ユーザ名をActiveDirectoryから取得したい場合 $domain = "ドメイン名" $userId = $logonUser # 取得したログオンユーザに、ドメイン名が付いている場合、外しておく if($logonUser.Contains("\")){ $userId = $logonUser.Split("\")[1] } # .NETのSystem.DirectoryService名前空間を使用する # ローカル環境にActiveDirectory向けのPowerShellモジュールがあるなら、そちらでもよいかも [void][Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices") $path = "WinNT://{0}/{1}" -f $domain,$userId $entry = New-Object System.DirectoryServices.DirectoryEntry($path) # 必要なら資格情報を指定 # $entry = New-Object System.DirectoryServices.DirectoryEntry($path, $admin, $pass) $userFullName = $entry.Properties["FullName"].Value.ToString()
PowerShellCorpus/GithubGist/Iristyle_1672426_raw_d06e4115d80eed71e45e2efdec4949fb4e741c7e_Bootstrap-EC2-Windows-CloudInit.ps1
Iristyle_1672426_raw_d06e4115d80eed71e45e2efdec4949fb4e741c7e_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) { $netUrl = if ($IsCore) {'http://download.microsoft.com/download/3/6/1/361DAE4E-E5B9-4824-B47F-6421A6C59227/dotNetFx40_Full_x86_x64_SC.exe' } ` else { 'http://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe' } Start-BitsTransfer $netUrl dotNetFx40_Full.exe Start-Process -FilePath 'dotNetFx40_Full.exe' -ArgumentList '/norestart /q /ChainingPackage ADMINDEPLOYMENT' -Wait -NoNewWindow del dotNetFx40_Full.exe Add-Content $log -value "Found that .NET4 was not installed and downloaded / installed" } #configure powershell to use .net 4 $config = @' <?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- http://msdn.microsoft.com/en-us/library/w4atty68.aspx --> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" /> <supportedRuntime version="v2.0.50727" /> </startup> </configuration> '@ if (Test-Path "${Env:windir}\SysWOW64\WindowsPowerShell\v1.0\powershell.exe") { $config | Set-Content "${Env:windir}\SysWOW64\WindowsPowerShell\v1.0\powershell.exe.config" Add-Content $log -value "Configured 32-bit Powershell on x64 OS to use .NET 4" } if (Test-Path "${Env:windir}\system32\WindowsPowerShell\v1.0\powershell.exe") { $config | Set-Content "${Env:windir}\system32\WindowsPowerShell\v1.0\powershell.exe.config" Add-Content $log -value "Configured host OS specific Powershell at ${Env:windir}\system32\ to use .NET 4" } #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 2010 redstributable $vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/5/B/C/5BC5DBB3-652D-4DCE-B14A-475AB85EEF6E/vcredist_x86.exe'} ` else { 'http://download.microsoft.com/download/3/2/2/3224B87F-CFA0-4E70-BDA3-3DE650EFEBA5/vcredist_x64.exe' } Start-BitsTransfer $vcredist 'vcredist.exe' Start-Process -FilePath 'vcredist.exe' -ArgumentList '/norestart /q' -Wait del vcredist.exe Add-Content $log -value "Installed VC++ 2010 Redistributable from $vcredist and updated path" #vc 2008 redstributable $vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/d/d/9/dd9a82d0-52ef-40db-8dab-795376989c03/vcredist_x86.exe'} ` else { 'http://download.microsoft.com/download/d/2/4/d242c3fb-da5a-4542-ad66-f9661d0a8d19/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++ 2008 Redistributable from $vcredist and updated path" #curl $curlUri = if ($Is32Bit) { 'http://www.paehl.com/open_source/?download=curl_724_0_ssl.zip' } ` else { 'http://curl.haxx.se/download/curl-7.23.1-win64-ssl-sspi.zip' } Start-BitsTransfer $curlUri curl.zip &7z e curl.zip `-o`"c:\program files\curl`" if ($Is32Bit) { Start-BitsTransfer 'http://www.paehl.com/open_source/?download=libssl.zip' libssl.zip &7z e libssl.zip `-o`"c:\program files\curl`" del libssl.zip } SetX Path "${Env:Path};C:\Program Files\Curl" /m $Env:Path += ';C:\Program Files\Curl' del curl.zip Add-Content $log -value "Installed Curl from $curlUri and updated path" #vim curl -# -G -k -L ftp://ftp.vim.org/pub/vim/pc/vim73_46rt.zip -o vim73_46rt.zip 2>&1 > "$log" curl -# -G -k -L ftp://ftp.vim.org/pub/vim/pc/vim73_46w32.zip -o vim73_46w32.zip 2>&1 > "$log" Get-ChildItem -Filter vim73*.zip | % { &7z x `"$($_.FullName)`"; del $_.FullName; } SetX Path "${Env:Path};C:\Program Files\Vim" /m $Env:Path += ';C:\Program Files\Vim' Move-Item .\vim\vim73 -Destination "${Env:ProgramFiles}\Vim" Add-Content $log -value "Installed Vim text editor and updated path" #cloudinit.net curl http://cloudinitnet.codeplex.com/releases/83697/download/351123 `-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' [Environment]::SetEnvironmentVariable('Chocolatey_Bin_Root', '\tools', 'Machine') $Env:Chocolatey_bin_root = '\tools' } 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/aqr_5139945_raw_91c07ddcda380100122340d0853a64a321bc2a7f_icontrol.ps1
aqr_5139945_raw_91c07ddcda380100122340d0853a64a321bc2a7f_icontrol.ps1
# init $success = if ((Get-PSSnapin | Where { $_.Name -eq "iControlSnapIn"}) -eq $null) { Add-PSSnapIn iControlSnapIn } # profile $profile = new-object -typename iControl.LocalLBVirtualServerVirtualServerProfile $profile.profile_context = "PROFILE_CONTEXT_TYPE_ALL" $profile.profile_name = "http-xff"
PowerShellCorpus/GithubGist/chgeuer_8342314_raw_683639c5f084d0c3f3c8709efcb74c237948bca6_Install-Erlang.ps1
chgeuer_8342314_raw_683639c5f084d0c3f3c8709efcb74c237948bca6_Install-Erlang.ps1
# # Check if Erlang is installed # $erlangkey = Get-ChildItem HKLM:\SOFTWARE\Wow6432Node\Ericsson\Erlang -ErrorAction SilentlyContinue if ( $erlangkey -eq $null ) { Write-Host "Erlang not found, need to install it" Start-Process -Wait otp_win64_R16B03.exe /S } # # Determine Erlang home path # $ERLANG_HOME = ((Get-ChildItem HKLM:\SOFTWARE\Wow6432Node\Ericsson\Erlang)[0] | Get-ItemProperty).'(default)' [System.Environment]::SetEnvironmentVariable("ERLANG_HOME", $ERLANG_HOME, "Machine") # # Add Erlang to the path if needed # $system_path_elems = [System.Environment]::GetEnvironmentVariable("PATH", "Machine").Split(";") if (!$system_path_elems.Contains("%ERLANG_HOME%\bin") -and !$system_path_elems.Contains("$ERLANG_HOME\bin")) { Write-Host "Adding erlang to path" $newpath = [System.String]::Join(";", $system_path_elems + "$ERLANG_HOME\bin") [System.Environment]::SetEnvironmentVariable("PATH", $newpath, "Machine") }
PowerShellCorpus/GithubGist/jquintus_b9ad19e94b3842b0d15e_raw_01d3cc9d7ced199b8e3a6ecd39b88724dd9d77eb_Disable_Hyper-V.ps1
jquintus_b9ad19e94b3842b0d15e_raw_01d3cc9d7ced199b8e3a6ecd39b88724dd9d77eb_Disable_Hyper-V.ps1
# This script makes a copy of the current boot record and disables Hyper-V # The next time the computer is restarted you can elect to run without Hyper-V $output = invoke-expression 'bcdedit /copy "{current}" /d "Hyper-V Disabled"' $output -match '{.*}' $guid = $matches[0] $hyperVCommand = 'bcdedit /set "' + $guid + '" hypervisorlaunchtype off' invoke-expression $hyperVCommand
PowerShellCorpus/GithubGist/vintem_6334646_raw_30116f16c82c65b3f8b40523b07c57fad32d35e2_dev_setup.ps1
vintem_6334646_raw_30116f16c82c65b3f8b40523b07c57fad32d35e2_dev_setup.ps1
function Add-Path() { [Cmdletbinding()] param([parameter(Mandatory=$True,ValueFromPipeline=$True,Position=0)][String[]]$AddedFolder) # Get the current search path from the environment keys in the registry. $OldPath=(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path # See if a new folder has been supplied. if (!$AddedFolder) { Return 'No Folder Supplied. $ENV:PATH Unchanged' } # See if the new folder exists on the file system. if (!(TEST-PATH $AddedFolder)) { Return 'Folder Does not Exist, Cannot be added to $ENV:PATH' }cd # See if the new Folder is already in the path. if ($ENV:PATH | Select-String -SimpleMatch $AddedFolder) { Return 'Folder already within $ENV:PATH' } # Set the New Path $NewPath=$OldPath+’;’+$AddedFolder Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH –Value $newPath # Show our results back to the world Return $NewPath } ###################################################### # Install apps using Chocolatey ###################################################### Write-Host "Installing Chocolatey" iex ((new-object net.webclient).DownloadString('http://bit.ly/psChocInstall')) Write-Host Write-Host "Installing applications from Chocolatey" cinst git cinst ruby -Version 1.9.3.44800 cinst nodejs.install cinst PhantomJS cinst webpi cinst poshgit cinst notepadplusplus cinst sublimetext2 cinst SublimeText2.PackageControl cinst SublimeText2.PowershellAlias cinst ConEmu cinst python cinst DotNet4.0 cinst DotNet4.5 cinst putty cinst Firefox cinst GoogleChrome cinst fiddler4 cinst filezilla cinst dropbox cinst winmerge cinst kdiff3 cinst winrar -Version 4.20.0 cinst mongodb cinst NugetPackageExplorer cinst SkyDrive cinst Evernote cinst heroku-toolbelt Write-Host ###################################################### # Set environment variables ###################################################### Write-Host "Setting home variable" [Environment]::SetEnvironmentVariable("HOME", $HOME, "User") [Environment]::SetEnvironmentVariable("CHROME_BIN", "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "User") [Environment]::SetEnvironmentVariable("PHANTOMJS_BIN", "C:\tools\PhanomJS\phantomjs.exe", "User") Write-Host ###################################################### # Download custom .bashrc file ###################################################### Write-Host "Creating .bashrc file for use with Git Bash" $filePath = $HOME + "\.bashrc" New-Item $filePath -type file -value ((new-object net.webclient).DownloadString('http://vintem.me/winbashrc')) Write-Host ###################################################### # Install Windows installer through WebPI ###################################################### Write-Host "Installing apps from WebPI" cinst WindowsInstaller31 -source webpi cinst WindowsInstaller45 -source webpi Write-Host ###################################################### # Install SQL Express 2012 ###################################################### Write-Host do { $createSiteData = Read-Host "Do you want to install SQLExpress? (Y/N)" } while ($createSiteData -ne "Y" -and $createSiteData -ne "N") if ($createSiteData -eq "Y") { cinst SqlServer2012Express } Write-Host ###################################################### # Add Git to the path ###################################################### Write-Host "Adding Git\bin to the path" Add-Path "C:\Program Files (x86)\Git\bin" Write-Host ###################################################### # Configure Git globals ###################################################### Write-Host "Configuring Git globals" $userName = Read-Host 'Enter your name for git configuration' $userEmail = Read-Host 'Enter your email for git configuration' & 'C:\Program Files (x86)\Git\bin\git' config --global user.email $userEmail & 'C:\Program Files (x86)\Git\bin\git' config --global user.name $userName $gitConfig = $home + "\.gitconfig" Add-Content $gitConfig ((new-object net.webclient).DownloadString('http://vintem.me/mygitconfig')) $gitexcludes = $home + "\.gitexcludes" Add-Content $gitexcludes ((new-object net.webclient).DownloadString('http://vintem.me/gitexcludes')) Write-Host $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") ###################################################### # Update RubyGems and install some gems ###################################################### Write-Host "Update RubyGems" C:\Chocolatey\bin\cinst ruby.devkit.ruby193 gem update --system gem install bundler compass Write-Host ###################################################### # Install npm packages ###################################################### Write-Host "Install NPM packages" npm install -g yo grunt-cli karma bower jshint coffee-script nodemon generator-webapp generator-angular Write-Host ###################################################### # Generate public/private rsa key pair ###################################################### Write-Host "Generating public/private rsa key pair" Set-Location $home $dirssh = "$home\.ssh" mkdir $dirssh $filersa = $dirssh + "\id_rsa" ssh-keygen -t rsa -f $filersa -q -C $userEmail Write-Host ###################################################### # Add MongoDB to the path ###################################################### Write-Host "Adding MongoDB to the path" Add-Path "C:\MongoDB\bin" Write-Host ###################################################### # Download custom PowerShell profile file ###################################################### Write-Host "Creating custom $profile for Powershell" if (!(test-path $profile)) { New-Item -path $profile -type file -force } Add-Content $profile ((new-object net.webclient).DownloadString('http://vintem.me/profileps')) Write-Host
PowerShellCorpus/GithubGist/richjenks_5933149_raw_7bf34075db815597b33d3f53db95b470718f0519_batch-rename-files.ps1
richjenks_5933149_raw_7bf34075db815597b33d3f53db95b470718f0519_batch-rename-files.ps1
# Replace underscores with hyphens Dir | Rename-Item –NewName { $_.name –replace "_","-" }
PowerShellCorpus/GithubGist/mbrownnycnyc_c488b4f8885d0f51b97a_raw_c8b284a92e3f68cb7049f05e0ac3110bfad27a48_Invoke-CommandAgainstOU.ps1
mbrownnycnyc_c488b4f8885d0f51b97a_raw_c8b284a92e3f68cb7049f05e0ac3110bfad27a48_Invoke-CommandAgainstOU.ps1
#ref ## http://blogs.technet.com/b/heyscriptingguy/archive/2011/06/13/use-powershell-invoke-command-for-remoting.aspx ## http://www.powershellmagazine.com/2013/04/10/pstip-wait-for-a-service-to-reach-a-specified-status/ ## http://stackoverflow.com/a/3008717/843000 ## http://support.microsoft.com/kb/2509997 Invoke-Command -scriptblock { #is this case, I am cleaning up pending updates due to an issue with a deployed update (error 1638) $wuausvc = get-service wuauserv $wuausvc.stop() $wuausvc.waitforstatus('Stopped') remove-Item -force -recurse c:\windows\SoftwareDistribution\* $env:computername + " " + $(Get-Date -format HH:mm:ss) + " : c:\windows\SoftwareDistribution\ deleted? " + $(if ( (test-path c:\windows\SoftwareDistribution\Download) -eq $false) { echo $true } else { echo $false }) $wuausvc.start() $wuausvc.waitforstatus('Running') $env:computername + " " + $(Get-Date -format HH:mm:ss) + ": wuauserv is now " + $wuausvc.status } -computername ( get-adcomputer -filter "objectCategory -eq 'computer'" -SearchBase "OU=New York,DC=contoso,DC=corp" | select-object -expand name ) 2>&1 | tee -filepath cleanup_wuau.out
PowerShellCorpus/GithubGist/gsmiro_8022175_raw_0935bce3cf8ec342336a941caede07d7557d1901_powershell-utils.ps1
gsmiro_8022175_raw_0935bce3cf8ec342336a941caede07d7557d1901_powershell-utils.ps1
#Check path $env:Path #set path $env:Path += "<path>" #location of profile.ps1 file: ~\Documents\WindowsPowerShell
PowerShellCorpus/GithubGist/vgrem_7552775_raw_89ed825739ef646ff61c0bc73b39a67bebefd06f_ClientRuntimeContext.Load.ps1
vgrem_7552775_raw_89ed825739ef646ff61c0bc73b39a67bebefd06f_ClientRuntimeContext.Load.ps1
Function Invoke-LoadMethod() { param( $ClientObject = $(throw "Please provide an Client Object instance on which to invoke the generic method") ) $ctx = $ClientObject.Context $load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load") $type = $ClientObject.GetType() $clientObjectLoad = $load.MakeGenericMethod($type) $clientObjectLoad.Invoke($ctx,@($ClientObject,$null)) }
PowerShellCorpus/GithubGist/Restuta_2512835_raw_de75f4fb11117bcd9dec349a0b34670e15ccb42e_setup-git-ex.ps1
Restuta_2512835_raw_de75f4fb11117bcd9dec349a0b34670e15ccb42e_setup-git-ex.ps1
$os=Get-WMIObject win32_operatingsystem if ($os.OSArchitecture -eq "64-bit") { $gitInstallationDir = "c:\Program Files (x86)\Git\" } else { $gitInstallationDir = "c:\Program Files\Git\" } #adding git installation directory to PATH variable if (-not $env:Path.Contains($gitInstallationDir)) { Write-Host "Adding git installation path to system PATH..." -ForegroundColor DarkYellow $env:Path = $env:Path + ";" + $gitInstallationDir } #creating "git-ex" file in "git/bin" folder $gitExFilePath = $gitInstallationDir + "bin/git-ex" if (-not (Test-Path $gitExFilePath)) { #file content start $gitExFileContent = "#!/bin/sh ""`$PROGRAMFILES\GitExtensions\GitExtensions.exe"" ""$@"" &" #file content end New-Item $gitExFilePath -type: file -value $gitExFileContent }
PowerShellCorpus/GithubGist/guitarrapc_5829075186342d3ca143_raw_66734539a2085498c89e680bde3bc21e56916cba_ACLExecution.ps1
guitarrapc_5829075186342d3ca143_raw_66734539a2085498c89e680bde3bc21e56916cba_ACLExecution.ps1
ACLTest -OutputPath ACLTest Start-DscConfiguration -Wait -Force -Verbose -Path ACLTest
PowerShellCorpus/GithubGist/goo32_d33e2dc04b29e773eb32_raw_92920fbef205420ae4e23e5130b49e3e0c0c2d36_random_image_count.ps1
goo32_d33e2dc04b29e773eb32_raw_92920fbef205420ae4e23e5130b49e3e0c0c2d36_random_image_count.ps1
ls | ?{ $_.PSIsContainer } | Get-Random | gci -filter *.jpg -recurse | Measure-Object
PowerShellCorpus/GithubGist/r-plus_304fefcad63834ded16e_raw_97dcaa402da6edc100f46b67ce31f36a6ef24c63_matcher.ps1
r-plus_304fefcad63834ded16e_raw_97dcaa402da6edc100f46b67ce31f36a6ef24c63_matcher.ps1
$json = @" { "matcher": [ { "regexp" : "^re$", "dest" : "dest1" }, { "regexp" : "^h\\w+eほげ.{3}我$", "dest" : "dest2" }, { "regexp" : ".*", "dest" : "dest3" } ] } "@ | ConvertFrom-Json # ConvertFrom-Json requred PowerShell version 3.0 or later. $string = "ho geほげフガ負我" # chomp $string = $string -replace "`t|`n|`r","" # matching $json.matcher | % { echo "trying $($_.regexp) ..." if ($string -cmatch $_.regexp) { echo hit! break; } }
PowerShellCorpus/GithubGist/sksbrg_2699702_raw_965c923a529e49c50bd58e72744ce688999561ba_git_svn__add_remote_branch.ps1
sksbrg_2699702_raw_965c923a529e49c50bd58e72744ce688999561ba_git_svn__add_remote_branch.ps1
# Change the following 3 lines for your needs before executing the batch $svnBranch = "remote_branch_name" # The branch name used in SVN $gitBranch = "local_branch_name" # The branch name you like to see in local git-svn $branchUrl = "http://full/path/to/branches/" + $svnBranch # ---- this is where the automation starts ---- $remoteRef = "git-svn-" + $gitBranch git config svn-remote.$svnBranch.url $branchUrl git config svn-remote.$svnBranch.fetch :refs/remotes/$remoteRef git config -l | grep svn | sort git svn fetch $svnBranch git checkout -b $gitBranch --track $remoteRef git svn rebase $svnBranch git svn fetch
PowerShellCorpus/GithubGist/krote_4975388_raw_9a84842b647de25ba81550c67c156432e1217efc_classutil.ps1
krote_4975388_raw_9a84842b647de25ba81550c67c156432e1217efc_classutil.ps1
# classutil.ps1 # source from http://mojibake.seesaa.net/article/56484188.html # class to cls # var to mem # def to func $global:__cls__=@{} # this function is not worked. why... function global:cls([string] $name, [ScriptBlock] $definition) { $global:__cls__[$name] = $definition } function global:new([string] $typename) { function mem([string] $name, $value = $null){ $this | Add-Member NoteProperty $name $value } function func([string] $name, [ScriptBlock] $method) { $this | Add-Member ScriptMethod $name $method } $definition = $global:__cls__[$typename] if( !$definition ){ throw $typename + " is undefined." } $obj = New-Object PSObject $obj | Add-Member ScriptMethod "__func__" $definition $obj.__func__() $obj.psobject.members.remove("__func__") $obj }
PowerShellCorpus/GithubGist/adams-sarah_03097fc9275c04575e24_raw_e3075d14072cd4a10feccaaea05f71212208b926_windows-2003.ps1
adams-sarah_03097fc9275c04575e24_raw_e3075d14072cd4a10feccaaea05f71212208b926_windows-2003.ps1
cd C:\Documents and Settings\Administrator mkdir Programs bitsadmin /transfer pythondownloadjob /download /priority normal https://www.python.org/ftp/python/3.4.1/python-3.4.1.msi C:\Documents and Settings\Administrator\Programs\python-3.4.1.msi cd Programs msiexec /quiet /i python-3.4.1.msi setx PATH "%PATH%;C:\Python34\;C:\Python34\Scripts\" pip install awscli mkdir C:\Documents and Settings\Administrator\.aws echo [default] > C:\Documents and Settings\Administrator\.aws\config echo "aws_access_key_id = %AWS_ACCESS_KEY_ID%" >> C:\Documents and Settings\Administrator\.aws\config echo "aws_secret_access_key = %AWS_SECRET_ACCESS_KEY%" >> C:\Documents and Settings\Administrator\.aws\config echo "region = us-east-1" >> C:\Documents and Settings\Administrator\.aws\config cd C:\ notepad C:\Documents and Settings\Administrator\.aws\config cd C:\Documents and Settings\Administrator mkdir ITOA aws s3 sync s3://sproutling-chime/ITOA ITOA cd ITOA \Documents and Settings\Administrator\Programs\unzip.exe itoa12a.zip cmd /c itoa cd C:\Documents and Settings\Administrator mkdir -p chime\orig mkdir chime\conv mkdir chime\scripts cd C:\Documents and Settings\Administrator\Programs bitsadmin /transfer rubyinstallerjob /download /priority normal http://dl.bintray.com/oneclick/rubyinstaller/rubyinstaller-1.9.3-p545.exe C:\Documents and Settings\Administrator\Programs\rubyinstaller-1.9.3-p545.exe mkdir C:\Ruby193 .\rubyinstaller-1.9.3-p545.exe /silent /tasks="addtk,assocfiles,modpath" setx PATH "%PATH%;C:\Ruby193\bin" bitsadmin /transfer unzipjob /download /priority normal http://stahlworks.com/dev/unzip.exe C:\Documents and Settings\Administrator\Programs\unzip.exe aws s3 cp s3://sproutling-chime-converted/scripts/convert.rb C:\Documents and Settings\Administrator\chime\scripts\convert.rb cd chime\orig mkdir 10010 aws s3 sync s3://sproutling-chime/10010 10010 cd C:\Documents and Settings\Administrator ruby chime\scripts\convert.rb cd ITOA cmd /c C:\Documents and Settings\Administrator\chime\itoacmds.bat cd C:\Documents and Settings\Administrator aws s3 sync chime\conv s3://sproutling-chime-converted
PowerShellCorpus/GithubGist/miwaniza_9164083_raw_e52ed4d9cdb4611df572b256bc1e3bb27c878516_getall_groups.ps1
miwaniza_9164083_raw_e52ed4d9cdb4611df572b256bc1e3bb27c878516_getall_groups.ps1
Add-Type -Path "C:\Program Files (x86)\Autodesk\Autodesk Vault 2014 SDK\bin\Autodesk.Connectivity.WebServices.dll" $cred = New-Object Autodesk.Connectivity.WebServicesTools.UserPasswordCredentials ("localhost","Vault","Administrator","",$true) $webSvc = New-Object Autodesk.Connectivity.WebServicesTools.WebServiceManager ($cred) $groups = $webSvc.AdminService.GetAllGroups() $groups | Out-GridView
PowerShellCorpus/GithubGist/jstangroome_2865415_raw_39aa8dccbf97d026c55da29f920e6bca868bfc64_Export-TfsCollection.ps1
jstangroome_2865415_raw_39aa8dccbf97d026c55da29f920e6bca868bfc64_Export-TfsCollection.ps1
[CmdletBinding()] param ( [Parameter(Mandatory=$true)] [string] $ServerUrl, [Parameter(Mandatory=$true)] [string] $Name, [Parameter(Mandatory=$true)] [string] $ExportPath ) function Get-Collection ( $ConfigurationServer, $Name ) { $CollectionService = $ConfigurationServer.GetService([Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService]) $Collection = $CollectionService.GetCollections() | Where-Object { $_.Name -eq $Name } | Select-Object -First 1 if (-not $Collection) { throw "$($MyInvocation.MyCommand): Collection '$Name' not found" } return $Collection } function Detach-Collection ( $ConfigurationServer, $Collection ) { $CollectionService = $ConfigurationServer.GetService([Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService]) $ServicingTokens = $null $StopMessage = "$($MyInvocation.MyCommand): Export started $(Get-Date)" $ConnectionString = '' $Job = $CollectionService.QueueDetachCollection($Collection, $ServicingTokens, $StopMessage, [ref]$ConnectionString) $ResultCollection = $CollectionService.WaitForCollectionServicingToComplete($Job) return (New-Object -TypeName PSObject -Property @{ CollectionName = $Name ConnectionString = $ConnectionString }) } function Attach-Collection ( $ConfigurationServer, $ConnectionString ) { $CollectionService = $ConfigurationServer.GetService([Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService]) $AttachServicingTokens = $null $CloneCollection = $false $Job = $CollectionService.QueueAttachCollection($ConnectionString, $AttachServicingTokens, $CloneCollection) $Collection = $CollectionService.WaitForCollectionServicingToComplete($Job) if ($Collection.State -ne 'Started') { throw "$($MyInvocation.MyCommand): Collection at '$ConnectionString' was not attached" } Write-Verbose "$($MyInvocation.MyCommand): Collection '$($Collection.Name)' attached" return $Collection } function Backup-Collection ($ConnectionString, $Path) { $CSBuilder = New-Object -TypeName System.Data.SqlClient.SqlConnectionStringBuilder -ArgumentList $ConnectionString $DatabaseName = $CSBuilder.InitialCatalog $BackupFilePath = $Path | Join-Path -ChildPath "$DatabaseName.bak" if (Test-Path -Path $BackupFilePath) { Remove-Item -Path $BackupFilePath } $Connection = New-Object -TypeName System.Data.SqlClient.SqlConnection $Connection.ConnectionString = $CSBuilder.ConnectionString $Connection.Open() try { $Command = $Connection.CreateCommand() $Command.CommandType = 'Text' $Command.CommandText = "BACKUP DATABASE [{0}] TO DISK = N'{1}' WITH COPY_ONLY, COMPRESSION, STATS" -f $DatabaseName, $BackupFilePath $Command.CommandTimeout = (New-TimeSpan -Minutes 10).TotalSeconds $Command.ExecuteNonQuery() | Out-Null $Command.Dispose() } catch { Write-Warning "$($MyInvocation.MyCommand): Backup failed. $_" } finally { $Connection.Close() } Get-Item -Path $BackupFilePath } $script:ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest $PSScriptRoot = $MyInvocation.MyCommand.Path | Split-Path Add-Type -AssemblyName System.Web 'Microsoft.TeamFoundation.Client', 'Microsoft.TeamFoundation.Common' | ForEach-Object { Add-Type -AssemblyName "$_, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" } $Server = New-Object -TypeName Microsoft.TeamFoundation.Client.TfsConfigurationServer -ArgumentList $ServerUrl $CollectionService = $Server.GetService([Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService]) Write-Verbose "$($MyInvocation.MyCommand): Finding collection '$Name'" $Collection = Get-Collection -ConfigurationServer $Server -Name $Name $Name = $Collection.Name Write-Verbose "$($MyInvocation.MyCommand): Detaching collection '$Name'" $DetachedCollection = Detach-Collection -ConfigurationServer $Server -Collection $Collection Write-Verbose "$($MyInvocation.MyCommand): Backing up database for collection '$Name'" try { $BackupItem = Backup-Collection -ConnectionString $DetachedCollection.ConnectionString -Path $ExportPath } catch { Write-Warning "$($MyInvocation.MyCommand): Backup failed" } Write-Verbose "$($MyInvocation.MyCommand): Re-attaching collection '$Name'" $Collection = Attach-Collection -ConfigurationServer $Server -ConnectionString $DetachedCollection.ConnectionString
PowerShellCorpus/GithubGist/zerhacken_11008917_raw_33a9e9b4379eec6fbdec76d836ee73f59d2ddc9b_profile.ps1
zerhacken_11008917_raw_33a9e9b4379eec6fbdec76d836ee73f59d2ddc9b_profile.ps1
# Set environment variables for Visual Studio Command Prompt pushd 'c:\Program Files (x86)\Microsoft Visual Studio 12.0\VC' cmd /c "vcvarsall.bat&set" | foreach { if ($_ -match "=") { $v = $_.split("="); set-item -force -path "ENV:\$($v[0])" -value "$($v[1])" } } popd write-host "`nVisual Studio 2013 command prompt variables set." -ForegroundColor Yellow # Create alias for sublime text Set-Alias sublime 'C:\Program Files\Sublime Text 3\sublime_text.exe' # Add python to path $env:Path += ";C:\Python27" # Add premake to path $env:Path += ";C:\premake4" # Print path variable ($env:Path).Replace(';',"`n") # Set startup directory Set-Location D:\dev\projects
PowerShellCorpus/GithubGist/zippy1981_854911_raw_eeeb41326c4186a0d14ac6b724e2db34744e21a8_MongoTest.ps1
zippy1981_854911_raw_eeeb41326c4186a0d14ac6b724e2db34744e21a8_MongoTest.ps1
# We assume that the driver is installed via the MSI. [string] $mongoDriverPath; # Check to see if we are running the 64 bit version of Powershell. # See http://stackoverflow.com/questions/2897569/visual-studio-deployment-project-error-when-writing-to-registry if ([intptr]::size -eq 8) { $mongoDriverPath = (Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v3.5\AssemblyFoldersEx\MongoDB CSharpDriver 1.0").'(default)'; } else { $mongoDriverPath = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\.NETFramework\v3.5\AssemblyFoldersEx\MongoDB CSharpDriver 1.0").'(default)'; } Add-Type -Path "$($mongoDriverPath)\MongoDB.Bson.dll"; # The [ordered] only works in PowerShell 3.0 an later. [MongoDB.Bson.BsonDocument] $doc = [ordered]@{ "_id"= [MongoDB.Bson.ObjectId]::GenerateNewId(); "FirstName"= "Justin"; "LastName"= "Dearing"; "PhoneNumbers"= [MongoDB.Bson.BsonDocument] [ordered]@{ 'Home'= '718-555-1212'; 'Mobile'= '646-555-1212'; }; }; Add-Type -Path "$($mongoDriverPath)\MongoDB.Driver.dll"; $db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://localhost/powershell'); $collection = $db['example1']; Write-Host "Insert"; $collection.Insert($doc); $collection.FindOneById($doc['_id']); $updates = @{'email'= '[email protected]'}; $query = @{"_id"= $doc['_id']} Write-Host "Update"; $collection.Update([MongoDB.Driver.QueryDocument]$query, [MongoDb.Driver.UpdateDocument]$updates); $collection.FindOneById($doc['_id']); Write-Host "Delete"; $collection.Remove([MongoDB.Driver.QueryDocument]$query); $collection.FindOneById($doc['_id']);
PowerShellCorpus/GithubGist/organicit_5057402_raw_2c3ef0fb84d4a0b8a3ff48233f389f0f2b619a3b_gistfile1.ps1
organicit_5057402_raw_2c3ef0fb84d4a0b8a3ff48233f389f0f2b619a3b_gistfile1.ps1
'010.10.005.012' -replace '\b0*','' #returns 10.10.005.012 reference 2/28/2013 powershell.com email tip
PowerShellCorpus/GithubGist/lantrix_1e34ed4a1be1f2507dff_raw_87b6689a333698ee6b7cd04e8c44244b4e900bf5_throw_example.ps1
lantrix_1e34ed4a1be1f2507dff_raw_87b6689a333698ee6b7cd04e8c44244b4e900bf5_throw_example.ps1
try { throw "exception has occured! Failure text" } catch { #Catch throw test $throwError = $_ } finally { if ([bool]$throwError) { Write-Host "$throwError" } else { Write-Host "Finished Successfully" } }
PowerShellCorpus/GithubGist/acaire_4172880_raw_0a874461c6791fb17663a0ef84adbe0eb23812d8_Bootstrap-EC2-Windows-CloudInit.ps1
acaire_4172880_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/pohatu_e00c63db11fb173674c5_raw_be475cc4e22e5efc772bc4e7ca8817f7fdf71550_Get-FavoritesFQDN.ps1
pohatu_e00c63db11fb173674c5_raw_be475cc4e22e5efc772bc4e7ca8817f7fdf71550_Get-FavoritesFQDN.ps1
# This can help you detect which shortcuts from IE are internal or external # you may want to migrate/backup/sync https://gist.github.com/pohatu but not # something like http://secret/internal/site # madprops to madprops for below snippet #http://madprops.org/blog/list-your-favorites-in-powershell/ $favs = gci $env:userprofile\favorites -rec -inc *.url | ? {select-string -inp $_ -quiet "^URL=http"} | select @{Name="Name"; Expression={[IO.Path]::GetFileNameWithoutExtension($_.FullName)}}, @{Name="URL"; Expression={get-content $_ | ? {$_ -match "^URL=http"} | % {$_.Substring(4)}}} # With this, then pipe the .url from each of these shortcuts to resolve-dnsname, and get the Name # Name is FQDN, basically # Resolve-DNSName chokes on urls like http://foo/ or http://foo/myawesomepage.html # so [URI]($_.url).Host gets the foo out of http://foo/myawesomepage.html # and resolve-dnsname ().Name will return something like foo.mydomain.mycorp.com # so input will be http://foo/myawesomepage.html and output will be foo.mydomain.mycorp.com $myFavs = ($favs | % { @{Name=$_.name; FQDN=(Resolve-DnsName ([URI]($_.url)).Host).Name}})
PowerShellCorpus/GithubGist/jeff-french_2351828_raw_178b5c0a8c70f9119dbf49a0edfd7cd23857c868_profile.ps1
jeff-french_2351828_raw_178b5c0a8c70f9119dbf49a0edfd7cd23857c868_profile.ps1
# Add Git bin directory to path for this session $env:path += ";" + (Get-Item "Env:ProgramFiles(x86)").Value + "\Git\bin"
PowerShellCorpus/GithubGist/minakuchiya_5459119_raw_025ad025c86b63af08a8a7553358f41a9826531e_AutoLogin.ps1
minakuchiya_5459119_raw_025ad025c86b63af08a8a7553358f41a9826531e_AutoLogin.ps1
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") function login { $process = @(ps | where {$_.ProcessName -eq ‘MyApp’} | select ProcessName) if($process.count -eq 0) { ii "C:\MyApp.exe" sleep 1 [System.Windows.Forms.SendKeys]::SendWait("{S}{Y}{S}{T}{E}{M}") [System.Windows.Forms.SendKeys]::SendWait("{TAB}") [System.Windows.Forms.SendKeys]::SendWait("{p}{a}{s}{s}{w}{o}{r}{d}") } }
PowerShellCorpus/GithubGist/pkirch_809d5102b6d16bbd7c0c_raw_740576861e9ba625253c1ce4171e9307b0b76a65_AzurePowerShellModul.ps1
pkirch_809d5102b6d16bbd7c0c_raw_740576861e9ba625253c1ce4171e9307b0b76a65_AzurePowerShellModul.ps1
Get-Module -Name Azure -ListAvailable <# Output Verzeichnis: C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ServiceManagement ModuleType Version Name ExportedCommands ---------- ------- ---- ---------------- Manifest 0.8.11 Azure {Disable-AzureServiceProjectRemoteDesktop, Enable-AzureMemcacheRole, Enable-AzureServiceProjectRemoteDesktop... #>
PowerShellCorpus/GithubGist/lantrix_d868e56b4cbce7349ea8_raw_823c74f4625d5ef4b5de00d446317ff2cffe7945_create_spanned_drive.ps1
lantrix_d868e56b4cbce7349ea8_raw_823c74f4625d5ef4b5de00d446317ff2cffe7945_create_spanned_drive.ps1
$disks = (wmic diskdrive list brief | measure-object -line | select -ExpandProperty Lines)-2 #1.. $disks | ForEach-Object -Begin {$a = $null} -Process { ` $a += $("select disk "+$_+[char][int](13)+[char][int](10)) ; ` $a += "online disk noerr "+[char][int](13)+[char][int](10) ; ` $a += "clean "+[char][int](13)+[char][int](10) ; ` $a += "attributes disk clear readonly noerr "+[char][int](13)+[char][int](10) ; ` $a += "convert dynamic noerr "+[char][int](13)+[char][int](10) ;} -End { $a += "exit"+[char][int](13)+[char][int](10) ; ` $a | Set-Content c:\diskpart1.txt -Encoding ASCII ` } #2.. $a = "create volume stripe disk=1" #Fix Hardcoded disk 1... $disks | ForEach-Object -Process {$a += ","+$_} $a += [char][int](13)+[char][int](10) $a += "format fs=ntfs label=scratch quick"+[char][int](13)+[char][int](10) $a += "assign letter=z"+[char][int](13)+[char][int](10) $a += "exit"+[char][int](13)+[char][int](10) $a | Set-Content c:\diskpart2.txt -Encoding ASCII Diskpart /s c:\diskpart1.txt Diskpart /s c:\diskpart2.txt
PowerShellCorpus/GithubGist/geoyogesh_5bb7057f7550ee1b90d3_raw_7e9c21b5de57ba320c6c1f81695b8de145007f1b_gistfile1.ps1
geoyogesh_5bb7057f7550ee1b90d3_raw_7e9c21b5de57ba320c6c1f81695b8de145007f1b_gistfile1.ps1
# Revert changes to modified files. git reset --hard # Remove all untracked files and directories. git clean -fd
PowerShellCorpus/GithubGist/whataride_7638195_raw_992cf90c0e8e0d89e2e4c80c036956a064a021de_host.ps1
whataride_7638195_raw_992cf90c0e8e0d89e2e4c80c036956a064a021de_host.ps1
# more information can be found here: # http://stackoverflow.com/questions/1825585/how-to-determine-what-version-of-powershell-is-installed $host # sample output: # Name : Windows PowerShell ISE Host # Version : 2.0 # InstanceId : 25068e2e-0d9a-4df6-a913-17c462899502 # UI : System.Management.Automation.Internal.Host.InternalHostUserInterface # CurrentCulture : en-US # CurrentUICulture : en-US # PrivateData : Microsoft.PowerShell.Host.ISE.ISEOptions # IsRunspacePushed : False # Runspace : System.Management.Automation.Runspaces.LocalRunspace
PowerShellCorpus/GithubGist/sandcastle_78dcba3c8e9e6910fb12_raw_b64f937fdfac1cb6ea2a77cb729b11e13f184a49_clean.ps1
sandcastle_78dcba3c8e9e6910fb12_raw_b64f937fdfac1cb6ea2a77cb729b11e13f184a49_clean.ps1
Get-ChildItem .\ -include bin,obj,_ReSharper* -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }
PowerShellCorpus/GithubGist/mendel129_6809737_raw_1128777b24fd455c3b8e514ee2e6b500c6146690_gistfile1.ps1
mendel129_6809737_raw_1128777b24fd455c3b8e514ee2e6b500c6146690_gistfile1.ps1
$RPC =Get-Counter "\MSExchange RpcClientAccess\User Count" -computername "srv1" $OWA =Get-Counter "\MSExchange OWA\Current Unique Users" -computername "srv1" $POP = Get-Counter "\MSExchangePop3(1)\Connections Current" -ComputerName "srv1" $IMAP = get-counter "\MSExchangeImap4(1)\Current Connections" -ComputerName "srv1" $csa=New-Object PSObject -Property @{ Server = srv1" "rpc" = $RPC.CounterSamples[0].CookedValue "owa" = $OWA.CounterSamples[0].CookedValue "pop" = $POP.CounterSamples[0].CookedValue "imap" = $IMAP.CounterSamples[0].CookedValue } $RPC =Get-Counter "\MSExchange RpcClientAccess\User Count" -computername "srv2" $OWA =Get-Counter "\MSExchange OWA\Current Unique Users" -computername "srv2" $POP = Get-Counter "\MSExchangePop3(1)\Connections Current" -ComputerName "srv2" $IMAP = get-counter "\MSExchangeImap4(1)\Current Connections" -ComputerName "srv2" $csb=New-Object PSObject -Property @{ Server = "srv2" "rpc" = $RPC.CounterSamples[0].CookedValue "owa" = $OWA.CounterSamples[0].CookedValue "pop" = $POP.CounterSamples[0].CookedValue "imap" = $IMAP.CounterSamples[0].CookedValue } write-host $csa.server", pop:" $csa.pop ", imap" $csa.imap ", owa: " $csa.owa, "rpc: " $csa.rpc write-host $csb.server", pop:" $csb.pop ", imap" $csb.imap ", owa: " $csb.owa, "rpc: " $csb.rpc Read-Host "exit"
PowerShellCorpus/GithubGist/fr0gger03_b9136768a85a7d1b4321_raw_e930126cb2914b0c4bd84564c554740ea428f966_VM-to-VMFS.ps1
fr0gger03_b9136768a85a7d1b4321_raw_e930126cb2914b0c4bd84564c554740ea428f966_VM-to-VMFS.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 datacenters and datastores, then enter loop Get-Datacenter | Get-Datastore | Foreach-Object{ # capture datastore name in variable $ds = $_.Name # capture state of datastore in variable $accessible=$_.State # for each datacenter, get the virutal machine, select specific properties, # and export it all to a CSV file $_ | Get-VM | Select-Object @{n=‘VMName’;e={$_.Name}},@{n=’PowerState';e={$_.PowerState}},@{n=‘ESXi Host Name’;e={$_.VMhost}},@{n=‘DataStore’;e={$ds}},@{n=‘Accessible’;e={$accessible}},@{n=’Type’;e={$_.Type}} | Export-CSV $csvname -NoTypeInformation –Append }
PowerShellCorpus/GithubGist/joshua_5446846_raw_5bb4f59e4339e444e5324aeb2cea8e1e65ef1b54_Microsoft.PowerShell_profile.ps1
joshua_5446846_raw_5bb4f59e4339e444e5324aeb2cea8e1e65ef1b54_Microsoft.PowerShell_profile.ps1
# Default PowerShell Profile # # ~/Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1 # # Remote script execution must be enabled. # Get-ExecutionPolicy should return RemoteSigned or Unrestricted # # If no, run the following as Administrator: # Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Confirm # . (Resolve-Path "$env:LOCALAPPDATA\GitHub\shell.ps1") . $env:github_posh_git\profile.example.ps1 Set-Alias subl 'C:\Program Files\Sublime Text 2\sublime_text.exe' function cdst { Set-Location \Projects\Stratus } function touch { Set-Content -Path ($args[0]) -Value ($null) } # Sanity Set-Alias ll Get-ChildItem #Set-Alias pwd Get-Location # Git Aliases function _git_status { git status } Set-Alias gst _git_status # Edit Profile function Edit-Profile { subl $Profile } Set-Alias ep Edit-Profile # Live Reload Profile function Reload-Profile { @( $Profile.AllUsersAllHosts, $Profile.AllUsersCurrentHost, $Profile.CurrentUserAllHosts, $Profile.CurrentUserCurrentHost ) | % { if(Test-Path $_) { Write-Verbose "Running $_" . $_ } } } Set-Alias reload Reload-Profile
PowerShellCorpus/GithubGist/philoushka_08d58dce415201ffabd1_raw_e584300fc1f5963c44afa952f9dbd99ef5325b3b_NewEventLog.ps1
philoushka_08d58dce415201ffabd1_raw_e584300fc1f5963c44afa952f9dbd99ef5325b3b_NewEventLog.ps1
#set permissions for the event log; read and write to the EventLog key and its subkeys and values. $acl= get-acl -path "HKLM:\SYSTEM\CurrentControlSet\Services\EventLog" $inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit" $propagation = [system.security.accesscontrol.PropagationFlags]"None" $rule=new-object system.security.accesscontrol.registryaccessrule "Authenticated Users","FullControl",$inherit,$propagation,"Allow" $acl.addaccessrule($rule) $acl|set-acl #create the Event Log $EventLogName = "FooBar" $EventLogExists = Get-EventLog -list | Where-Object {$_.logdisplayname -eq $EventLogName} if (! $EventLogExists) { Write-Host "Creating '$EventLogName' event log" New-EventLog -LogName $EventLogName -Source $EventLogName -ErrorAction Ignore| Out-Null Write-EventLog -LogName $EventLogName -Source $EventLogName -Message "Creating Event Log $EventLogName" -EventId 0 -EntryType information Write-Host "If you have Event Viewer open, you should probably close and reopen it." Get-EventLog -list } else{ Write-Host "There is already an '$EventLogName' event log" Write-EventLog -LogName $EventLogName -Source $EventLogName -Message "Hello Event Log $EventLogName" -EventId 0 -EntryType information }
PowerShellCorpus/GithubGist/josheinstein_9898245_raw_c042da6b60fb944f99e87d185c70f96589406ff1_Export-Excel.ps1
josheinstein_9898245_raw_c042da6b60fb944f99e87d185c70f96589406ff1_Export-Excel.ps1
#.SYNOPSIS # Exports objects to an Excel spreadsheet by writing them to a temporary # CSV file and using Excel automation model to import it into a workbook. # This allows formatting to be applied to columns which would not otherwise # be possible in a plain CSV export. function Export-Excel { [CmdletBinding()] param( # The path to save the Excel spreadsheet to. [Parameter(Position=1)] [String]$Path, # An object or array of objects to write out to an Excel spreadsheet. # This parameter typically comes from pipeline input. [Parameter(ValueFromPipeline=$true)] [Object[]]$InputObject, # A hashtable that contains column headers as keys and # valid Excel format strings as values. The formats will # be applied to the columns after the worksheet is generated. [Parameter()] [Hashtable]$Format, # An array of column names to hide. # You should probably exclude them from the output by using the # Select-Object command earlier in the pipeline, but if you want them # to be in the spreadsheet, but simply hidden, use this parameter. [Parameter()] [String[]]$Hide, # Turns off column wrapping on all cells. [Parameter()] [Switch]$NoWrap, # Quits Excel after the spreadsheet is generated. # This parameter should be used with caution since Excel may already be # open prior to the command. [Parameter()] [Switch]$Quit ) begin { if ($Path) { # If they supplied an output path, we will actually save the temp file # to the specified path in the format indicated by the extension. Since # the path will be given to Excel, we need to resolve the native path # in case a PowerShell path (like ~\Desktop\blah.xls) was used. $Path = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) # If the output file already exists, nuke it. if (Test-Path $Path -PathType Leaf) { Remove-Item $Path -Force } } # Excel VBA objects $Excel = $Null $Workbook = $Null $Sheet = $Null # Use a temporary file in the system temp directory to write the # results to. If it already exists, delete it. $ScratchName = "Export-Excel.html" $ScratchPath = "$ENV:TEMP\$ScratchName" Write-Verbose "Writing output to $ScratchPath" Remove-Item $ScratchPath -Force -ErrorAction 0 # Create a wrapped pipeline that we can pass each input # object to as if it were piped directly to ConvertTo-Html. # We're using ConvertTo-Html because it produces a decent # table that Excel can open without worrying about newlines # in a CSV file. $ScriptBlock = { ConvertTo-Html -As Table -Title "Export-Excel" | Set-Content $ScratchPath -Encoding UTF8 -Force } $Pipeline = $ScriptBlock.GetSteppablePipeline($MyInvocation.CommandOrigin) $Pipeline.Begin($PSCmdlet) # Define some helper functions for modifying the worksheet # using the named column headers $Headers = @{} # Sets the display format string on columns with a given name function SetColumnFormat($Header, $Format) { if ($Headers[$Header]) { $Range = $Sheet.Cells.Item(1, $Headers[$Header]).EntireColumn try { $Range.NumberFormat = $Format } catch { Write-Warning "Column $Header has invalid format string: $Format ($_)" } } } # Hides columns with a given name function SetColumnHidden($Header) { if ($Headers[$Header]) { $Range = $Sheet.Cells.Item(1, $Headers[$Header]).EntireColumn try { $Range.Hidden = $True } catch { Write-Warning "Could not hide column $Header ($_)" } } } } process { # Not much to do here except pass the input object to the # wrapped pipeline which sends it to the output file. foreach ($o in $InputObject) { $Pipeline.Process($o) } } end { $Pipeline.End() $Pipeline.Dispose() # Figure out column headings and store them in a hashtable. # This makes it easier to refer to a column range by name. $i = 1 foreach ($Match in [Regex]::Matches($(Get-Content $ScratchPath), '(?is)<TH>([^<]+)</TH>')) { $Headers[$Match.Groups[1].Value] = $i++ } # Excel Automation try { $Excel = [System.Runtime.InteropServices.Marshal]::GetActiveObject('Excel.Application') } catch [System.Management.Automation.MethodInvocationException] { $Excel = New-Object -ComObject 'Excel.Application' } $Workbook = $Excel.Workbooks.Open($ScratchPath) $Sheet = $Workbook.Worksheets.Item(1) # Turn off cell wrapping if ($NoWrap) { $Sheet.UsedRange.WrapText = $False } # Set column formats foreach ($Key in $Format.Keys) { SetColumnFormat $Key $Format[$Key] } # Hide certain columns foreach ($Key in $Hide) { SetColumnHidden $Key } $Workbook.Activate() $Excel.ActiveWindow.DisplayGridlines = $true # Save As? if ($Path) { $FileFormat = 51 switch ([IO.Path]::GetExtension($Path)) { '.xlsb' { $FileFormat = 50 } # Excel 12 Binary '.xlsx' { $FileFormat = 51 } # Excel 12 XML (No Macro) '.xlsm' { $FileFormat = 52 } # Excel 12 (With Macro) '.xls' { $FileFormat = 56 } # Excel Classic } $Workbook.SaveAs($Path, $FileFormat) } if ($Quit) { $Excel.Quit() } else { $Excel.Visible = $true $Excel.ActiveWindow.Activate() } $Excel = $null } } $ExcelArgs = @{ Verbose = $True Path = "~\Desktop\EventLogs.xlsx" Format = @{ InstanceId = '#,##0' TimeGenerated = 'm/d/yy h:mm AM/PM' TimeWritten = 'm/d/yy h:mm AM/PM' } Hide = ('Data','ReplacementStrings') NoWrap = $True Quit = $True } Get-EventLog Application -Newest 100 | Export-Excel @ExcelArgs
PowerShellCorpus/GithubGist/fe80Grau_9682010_raw_094de5212a67e0e606b529150f664bef764d0d12_ADDS.ps1
fe80Grau_9682010_raw_094de5212a67e0e606b529150f664bef764d0d12_ADDS.ps1
import-csv .usuarios.csv | foreach-object{ ## ---> primera variable del dominio para crear las ou en primer nivel (si es necesario) $dominio = [ADSI]"LDAP://DC=dominio,DC=org" ## ---> segunda variable de dominio para crear los objetos dentro de la OU que sea necesaria $dominiog = [ADSI]"LDAP://OU=$($_.UO),DC=dominio,DC=org" $busqueda = New-Object System.DirectoryServices.DirectorySearcher($dominio) ## ---> Buscamos la UO entre el DA ## ---> Si la UO no existe se creará $busqueda.Filter=`(objectcategory=organizationalUnit)` $busqueda.Filter="(OU=$($_.UO))" $buscar = $busqueda.FindAll() if ($buscar.count -eq 0){ $ou = $dominio.Create("organizationalUnit","ou=$($_.UO)") $ou.SetInfo() }else{ echo "YA EXISTE LA UO $($_.UO)"; } ## ---> Buscamos el grupo dentro de la UO ## ---> Si el grupo no existe se creará $busqueda.Filter=`(objectclass=group)` $busqueda.Filter="(OU=$($_.UO))" $busqueda.Filter="(CN=$($_.grupo))" $buscar = $busqueda.FindAll() if ($buscar.count -eq 0){ $grupo = $dominiog.Create("group","CN=$($_.grupo)") $grupo.SetInfo() }else{ echo "YA EXISTE EL GRUPO $($_.grupo) EN LA UO $($_.UO)" } ## ---> Buscamos el usuario dentro de la UO ## ---> Si el usuario no existe se creará $busqueda.Filter=`(&(objectclass=user)(objectcategory=person))` $busqueda.Filter="(OU=$($_.UO))" $busqueda.Filter="(CN=$($_.usuario))" $buscar = $busqueda.FindAll() if ($buscar.count -eq 0){ $usuario = $dominiog.Create("user", "CN=$($_.usuario)") $usuario.Put("SamAccountName","$($_.usuario)") $usuario.Put("UserPrincipalName","$($_.usuario)@dominio.org") $usuario.SetInfo() $usuario = [ADSI]"LDAP://CN=$($_.usuario), OU=$($_.UO), DC=dominio, DC=org" $usuario.psbase.InvokeSet("AccountDisabled",$False) $usuario.SetPassword("$($_.password)") $usuario.SetInfo() ## ---> Mover los usuarios al grupo que pertenecen $grupo = [ADSI]"LDAP://CN=$($_.grupo), OU=$($_.UO), DC=dominio, DC=org" $grupo.Add("LDAP://CN=$($_.usuario), OU=$($_.UO), DC=dominio, DC=org") }else{ echo "YA EXISTE EL USUARIO $($_.usuario)" } }
PowerShellCorpus/GithubGist/michischatz_81ab5f290b6c608f7209_raw_0d28ed19f0e5ae389231273b85b296622d26c6b9_Logging_Functions.ps1
michischatz_81ab5f290b6c608f7209_raw_0d28ed19f0e5ae389231273b85b296622d26c6b9_Logging_Functions.ps1
Function Log-Start{ <# .SYNOPSIS Creates log file .DESCRIPTION Creates log file with path and name that is passed. Checks if log file exists, and if it does deletes it and creates a new one. Once created, writes initial logging data .PARAMETER LogPath Mandatory. Path of where log is to be created. Example: C:\Windows\Temp .PARAMETER LogName Mandatory. Name of log file to be created. Example: Test_Script.log .PARAMETER ScriptVersion Mandatory. Version of the running script which will be written in the log. Example: 1.5 .INPUTS Parameters above .OUTPUTS Log file created .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 10/05/12 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 19/05/12 Purpose/Change: Added debug mode support .EXAMPLE Log-Start -LogPath "C:\Windows\Temp" -LogName "Test_Script.log" -ScriptVersion "1.5" #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$LogName, [Parameter(Mandatory=$true)][string]$ScriptVersion) Process{ $sFullPath = $LogPath + "\" + $LogName #Check if file exists and delete if it does If((Test-Path -Path $sFullPath)){ Remove-Item -Path $sFullPath -Force } #Create file and start logging New-Item -Path $LogPath -Name $LogName –ItemType File Add-Content -Path $sFullPath -Value "***************************************************************************************************" Add-Content -Path $sFullPath -Value "Started processing at [$([DateTime]::Now)]." Add-Content -Path $sFullPath -Value "***************************************************************************************************" Add-Content -Path $sFullPath -Value "" Add-Content -Path $sFullPath -Value "Running script version [$ScriptVersion]." Add-Content -Path $sFullPath -Value "" Add-Content -Path $sFullPath -Value "***************************************************************************************************" Add-Content -Path $sFullPath -Value "" #Write to screen for debug mode Write-Debug "***************************************************************************************************" Write-Debug "Started processing at [$([DateTime]::Now)]." Write-Debug "***************************************************************************************************" Write-Debug "" Write-Debug "Running script version [$ScriptVersion]." Write-Debug "" Write-Debug "***************************************************************************************************" Write-Debug "" } } Function Log-Write{ <# .SYNOPSIS Writes to a log file .DESCRIPTION Appends a new line to the end of the specified log file .PARAMETER LogPath Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log .PARAMETER LineValue Mandatory. The string that you want to write to the log .INPUTS Parameters above .OUTPUTS None .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 10/05/12 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 19/05/12 Purpose/Change: Added debug mode support .EXAMPLE Log-Write -LogPath "C:\Windows\Temp\Test_Script.log" -LineValue "This is a new line which I am appending to the end of the log file." #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$LineValue) Process{ Add-Content -Path $LogPath -Value $LineValue #Write to screen for debug mode Write-Debug $LineValue } } Function Log-Error{ <# .SYNOPSIS Writes an error to a log file .DESCRIPTION Writes the passed error to a new line at the end of the specified log file .PARAMETER LogPath Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log .PARAMETER ErrorDesc Mandatory. The description of the error you want to pass (use $_.Exception) .PARAMETER ExitGracefully Mandatory. Boolean. If set to True, runs Log-Finish and then exits script .INPUTS Parameters above .OUTPUTS None .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 10/05/12 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 19/05/12 Purpose/Change: Added debug mode support. Added -ExitGracefully parameter functionality .EXAMPLE Log-Error -LogPath "C:\Windows\Temp\Test_Script.log" -ErrorDesc $_.Exception -ExitGracefully $True #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$ErrorDesc, [Parameter(Mandatory=$true)][boolean]$ExitGracefully) Process{ Add-Content -Path $LogPath -Value "Error: An error has occurred [$ErrorDesc]." #Write to screen for debug mode Write-Debug "Error: An error has occurred [$ErrorDesc]." #If $ExitGracefully = True then run Log-Finish and exit script If ($ExitGracefully -eq $True){ Log-Finish -LogPath $LogPath Break } } } Function Log-Finish{ <# .SYNOPSIS Write closing logging data & exit .DESCRIPTION Writes finishing logging data to specified log and then exits the calling script .PARAMETER LogPath Mandatory. Full path of the log file you want to write finishing data to. Example: C:\Windows\Temp\Test_Script.log .PARAMETER NoExit Optional. If this is set to True, then the function will not exit the calling script, so that further execution can occur .INPUTS Parameters above .OUTPUTS None .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 10/05/12 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 19/05/12 Purpose/Change: Added debug mode support Version: 1.2 Author: Luca Sturlese Creation Date: 01/08/12 Purpose/Change: Added option to not exit calling script if required (via optional parameter) .EXAMPLE Log-Finish -LogPath "C:\Windows\Temp\Test_Script.log" .EXAMPLE Log-Finish -LogPath "C:\Windows\Temp\Test_Script.log" -NoExit $True #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$false)][string]$NoExit) Process{ Add-Content -Path $LogPath -Value "" Add-Content -Path $LogPath -Value "***************************************************************************************************" Add-Content -Path $LogPath -Value "Finished processing at [$([DateTime]::Now)]." Add-Content -Path $LogPath -Value "***************************************************************************************************" #Write to screen for debug mode Write-Debug "" Write-Debug "***************************************************************************************************" Write-Debug "Finished processing at [$([DateTime]::Now)]." Write-Debug "***************************************************************************************************" #Exit calling script if NoExit has not been specified or is set to False If(!($NoExit) -or ($NoExit -eq $False)){ Exit } } } Function Log-Email{ <# .SYNOPSIS Emails log file to list of recipients .DESCRIPTION Emails the contents of the specified log file to a list of recipients .PARAMETER LogPath Mandatory. Full path of the log file you want to email. Example: C:\Windows\Temp\Test_Script.log .PARAMETER EmailFrom Mandatory. The email addresses of who you want to send the email from. Example: "[email protected]" .PARAMETER EmailTo Mandatory. The email addresses of where to send the email to. Seperate multiple emails by ",". Example: "[email protected], [email protected]" .PARAMETER EmailSubject Mandatory. The subject of the email you want to send. Example: "Cool Script - [" + (Get-Date).ToShortDateString() + "]" .INPUTS Parameters above .OUTPUTS Email sent to the list of addresses specified .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 05.10.12 Purpose/Change: Initial function development .EXAMPLE Log-Email -LogPath "C:\Windows\Temp\Test_Script.log" -EmailFrom "[email protected]" -EmailTo "[email protected], [email protected]" -EmailSubject "Cool Script - [" + (Get-Date).ToShortDateString() + "]" #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$EmailFrom, [Parameter(Mandatory=$true)][string]$EmailTo, [Parameter(Mandatory=$true)][string]$EmailSubject) Process{ Try{ $sBody = (Get-Content $LogPath | out-string) #Create SMTP object and send email $sSmtpServer = "smtp.yourserver" $oSmtp = new-object Net.Mail.SmtpClient($sSmtpServer) $oSmtp.Send($EmailFrom, $EmailTo, $EmailSubject, $sBody) Exit 0 } Catch{ Exit 1 } } }
PowerShellCorpus/GithubGist/stefanwalther_81ce696d0a8dac05dfa9_raw_30a57f2ef6ec495a696a4c05e6f811799b4cfd41_Backup_MongoDB.ps1
stefanwalther_81ce696d0a8dac05dfa9_raw_30a57f2ef6ec495a696a4c05e6f811799b4cfd41_Backup_MongoDB.ps1
$date = Get-Date -UFormat %Y-%m-%d; $backupFolder = $date; $basePath = "C:\bla"; $destinationPath = Join-Path $basePath $backupFolder; if(!(Test-Path -Path $destinationPath)) { New-Item -ItemType directory -Path $destinationPath; (C:\mongodb\bin\mongodump.exe --out $destinationPath); }
PowerShellCorpus/GithubGist/VertigoRay_7b73da2cace3d49a2cf2_raw_99ca60ed53c1ad44e4454f7d2ca31b6a5349663e_CatchLineNumbers.ps1
VertigoRay_7b73da2cace3d49a2cf2_raw_99ca60ed53c1ad44e4454f7d2ca31b6a5349663e_CatchLineNumbers.ps1
function a { param( [string]$UninstallString = 'thing' ) $MyInvocation Write-Host -Fore Cyan "$($here.File) $($MyInvocation.MyCommand):$($MyInvocation.ScriptLineNumber)" b try { Throw('Thing!!!!') } catch { Write-Host -Fore Magenta ("{0} {1}:{2}: ErRaWr!! $_" -f @($here.File, $MyInvocation.MyCommand, $_.InvocationInfo.ScriptLineNumber)) } } function b { $MyInvocation Write-Host -Fore Cyan "$($here.File) $($MyInvocation.MyCommand):$($MyInvocation.ScriptLineNumber)" } # Buiding a $this style variable, but $this is an auto variable. $here = @{ 'File'='Test' } Write-Host -Fore Cyan "$($here.File) $($MyInvocation.MyCommand):$($MyInvocation.ScriptLineNumber)" a Write-Host -Fore Cyan "$($here.File) $($MyInvocation.MyCommand):$($MyInvocation.ScriptLineNumber)"
PowerShellCorpus/GithubGist/johnmiller_50fd88f950dbf367d5cf_raw_de16a9625a44b35b5e4e8319d6dd5635e09303ae_clone-all-repositories.ps1
johnmiller_50fd88f950dbf367d5cf_raw_de16a9625a44b35b5e4e8319d6dd5635e09303ae_clone-all-repositories.ps1
$Workspace = "C:\Workspace\" function create-command($dir) { $ProjDir = $Workspace + $dir $GitDir = $ProjDir + "\.git" $Config = $GitDir + "\config" $IsRepository = Test-Path $GitDir if (!$IsRepository) { return } $RemoteUrl = git config -f $Config --get remote.origin.url cd $ProjDir $CurrentBranch = git rev-parse --abbrev-ref HEAD Write-Host "git clone $RemoteUrl $ProjDir" Write-Host "cd $ProjDir" Write-Host "git checkout $CurrentBranch" Write-Host "" } Get-ChildItem -Directory $Workspace | foreach { create-command($_.Name); }
PowerShellCorpus/GithubGist/wishi_255625_raw_0ccf27cc76cb785d2682330a152824b70eac92c3_ssh-agent-utils.ps1
wishi_255625_raw_0ccf27cc76cb785d2682330a152824b70eac92c3_ssh-agent-utils.ps1
# SSH Agent Functions # Mark Embling (http://www.markembling.info/) # # How to use: # - Place this file into %USERPROFILE%\Documents\WindowsPowershell (or location of choice) # - Import into your profile.ps1: # e.g. ". (Resolve-Path ~/Documents/WindowsPowershell/ssh-agent-utils.ps1)" [without quotes] # - Enjoy # # Note: ensure you have ssh and ssh-agent available on your path, from Git's Unix tools or Cygwin. # Retrieve the current SSH agent PId (or zero). Can be used to determine if there # is an agent already starting. function Get-SshAgent() { $agentPid = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "User") if ([int]$agentPid -eq 0) { $agentPid = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "Process") } if ([int]$agentPid -eq 0) { 0 } else { # Make sure the process is actually running $process = Get-Process -Id $agentPid -ErrorAction SilentlyContinue if(($process -eq $null) -or ($process.ProcessName -ne "ssh-agent")) { # It is not running (this is an error). Remove env vars and return 0 for no agent. [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "User") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "User") 0 } else { # It is running. Return the PID. $agentPid } } } # Start the SSH agent. function Start-SshAgent() { # Start the agent and gather its feedback info [string]$output = ssh-agent $lines = $output.Split(";") $agentPid = 0 foreach ($line in $lines) { if (([string]$line).Trim() -match "(.+)=(.*)") { # Set environment variables for user and current process. [Environment]::SetEnvironmentVariable($matches[1], $matches[2], "Process") [Environment]::SetEnvironmentVariable($matches[1], $matches[2], "User") if ($matches[1] -eq "SSH_AGENT_PID") { $agentPid = $matches[2] } } } # Show the agent's PID as expected. Write-Host "SSH agent PID:", $agentPid } # Stop a running SSH agent function Stop-SshAgent() { [int]$agentPid = Get-SshAgent if ([int]$agentPid -gt 0) { # Stop agent process $proc = Get-Process -Id $agentPid if ($proc -ne $null) { Stop-Process $agentPid } # Remove all enviroment variables [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "User") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "User") } } # Add a key to the SSH agent function Add-SshKey() { if ($args.Count -eq 0) { # Add the default key (~/id_rsa) ssh-add } else { foreach ($value in $args) { ssh-add $value } } } # Start the agent if not already running; provide feedback $agent = Get-SshAgent if ($agent -eq 0) { Write-Host "Starting SSH agent..." Start-SshAgent # Start agent Add-SshKey # Add my default key } else { Write-Host "SSH agent is running (PID $agent)" }
PowerShellCorpus/GithubGist/healeyio_fac1ba9672a1807b6104_raw_7d57d20d7ebfd497ab6dfd22744202d66b811942_Set-LyncNoteWithTwitter.ps1
healeyio_fac1ba9672a1807b6104_raw_7d57d20d7ebfd497ab6dfd22744202d66b811942_Set-LyncNoteWithTwitter.ps1
#requires –Version 3.0 <# .SYNOPSIS Sets Lync 2013 Client's PersonalNote field with latest tweet from your favorite twitter personality: @SwiftOnSecurity .DESCRIPTION What's happening today? Find out with the Set-LyncNoteWithTwitter.ps1 script. It sets the Lync 2013 Client's personal note to match the latest tweet from your favorite twitter personality. Authentication and authorization are handled throughTwitter's Oauth implementation. Everything else is via their REST API. The Lync COM is used to update the Lync client. The secret tokens are sensitive. Be like Taylor and protect your secrets. Your app permissions only need to be read-only. Be like Taylor and follow the principle of least privilege. ****Requires Lync 2013 SDK.**** The SDK install requires Visual Studio 2010 SP1. To avoid installing Visual Studio, download the SDK, use 7-zip to extract the files from the install, and install the MSI relevant to your Lync Client build (x86/x64). .INPUTS None. You cannot pipe objects to Set-LyncNoteWithTwitter.ps1. .OUTPUTS None. Set-LyncNoteWithTwitter.ps1 does not generate any output. .NOTES Author Name: Andrew Healey (@healeyio) Creation Date: 2015-02-02 Version Date: 2015-02-02 .LINK Author: http://healey.io/blog/update-lync-notes-with-twitter-status/ Github: https://gist.github.com/healeyio/fac1ba9672a1807b6104#file-set-lyncnotewithtwitter-ps1 Lync 2013 SDK: http://www.microsoft.com/en-us/download/details.aspx?id=36824 Some code referenced from: MyTwitter: https://github.com/MyTwitter/MyTwitter .EXAMPLE PS C:\PS> .\Set-LyncNoteWithTwitter.ps1 #> ## Parameters [string]$Consumer_Key = 'abcdefghijklmnopqrstuvwxyz' [string]$Consumer_Secret = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz' [string]$Access_Token = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz' [string]$Access_Token_Secret = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrst' [string]$screen_name = 'SwiftOnSecurity' [int] $count = 1 [string]$exclude_replies = 'true' [string]$include_rts = 'false' [string]$HttpEndPoint = 'https://api.twitter.com/1.1/statuses/user_timeline.json' [Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null [Reflection.Assembly]::LoadWithPartialName("System.Net") | Out-Null ## Generate a random 32-byte string. Strip out '=' per twitter req's $OauthNonce = [System.Convert]::ToBase64String(([System.Text.Encoding]::ASCII.GetBytes("$([System.DateTime]::Now.Ticks.ToString())12345"))).Replace('=', 'g') Write-Verbose "Generated Oauth none string '$OauthNonce'" ## Find the total seconds since 1/1/1970 (epoch time) $EpochTimeNow = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null) Write-Verbose "Generated epoch time '$EpochTimeNow'" $OauthTimestamp = [System.Convert]::ToInt64($EpochTimeNow.TotalSeconds).ToString(); Write-Verbose "Generated Oauth timestamp '$OauthTimestamp'" ## Build the signature $SignatureBase = "$([System.Uri]::EscapeDataString($HttpEndPoint))&" $SignatureParams = @{ 'oauth_consumer_key' = $Consumer_Key; 'oauth_nonce' = $OauthNonce; 'oauth_signature_method' = 'HMAC-SHA1'; 'oauth_timestamp' = $OauthTimestamp; 'oauth_token' = $Access_Token; 'oauth_version' = '1.0'; } ## Add Signature Params $SignatureParams.screen_name = $screen_name $SignatureParams.exclude_replies = $exclude_replies $SignatureParams.include_rts = $include_rts $SignatureParams.count = $count ## Create a string called $SignatureBase that joins all URL encoded 'Key=Value' elements with a & ## Remove the URL encoded & at the end and prepend the necessary 'POST&' verb to the front $SignatureParams.GetEnumerator() | sort name | foreach { Write-Verbose "Adding '$([System.Uri]::EscapeDataString(`"$($_.Key)=$($_.Value)&`"))' to signature string" $SignatureBase += [System.Uri]::EscapeDataString("$($_.Key)=$($_.Value)&".Replace(',','%2C').Replace('!','%21')) } $SignatureBase = $SignatureBase.TrimEnd('%26') $SignatureBase = 'GET&' + $SignatureBase Write-Verbose "Base signature generated '$SignatureBase'" ## Create the hashed string from the base signature $SignatureKey = [System.Uri]::EscapeDataString($Consumer_Secret) + "&" + [System.Uri]::EscapeDataString($Access_Token_Secret); $hmacsha1 = new-object System.Security.Cryptography.HMACSHA1; $hmacsha1.Key = [System.Text.Encoding]::ASCII.GetBytes($SignatureKey); $OauthSignature = [System.Convert]::ToBase64String($hmacsha1.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($SignatureBase))); Write-Verbose "Using signature '$OauthSignature'" ## Build the authorization headers using most of the signature headers elements. This is joining all of the 'Key=Value' elements again ## and only URL encoding the Values this time while including non-URL encoded double quotes around each value $AuthorizationParams = $SignatureParams $AuthorizationParams.Add('oauth_signature', $OauthSignature) ## Remove any REST API call-specific params from the authorization params $AuthorizationParams.Remove('exclude_replies') $AuthorizationParams.Remove('include_rts') $AuthorizationParams.Remove('screen_name') $AuthorizationParams.Remove('count') $AuthorizationString = 'OAuth ' $AuthorizationParams.GetEnumerator() | sort name | foreach { $AuthorizationString += $_.Key + '="' + [System.Uri]::EscapeDataString($_.Value) + '",' } $AuthorizationString = $AuthorizationString.TrimEnd(',') Write-Verbose "Using authorization string '$AuthorizationString'" ## Build URI Body $URIBody = "?count=$count&exclude_replies=$exclude_replies&include_rts=$include_rts&screen_name=$screen_name" Write-Verbose "Using GET URI: $($HttpEndPoint + $Body)" $tweet = Invoke-RestMethod -URI $($HttpEndPoint + $URIBody) -Method Get -Headers @{ 'Authorization' = $AuthorizationString } -ContentType "application/x-www-form-urlencoded" ## Verify lync 2013 object model dll is either in script directory or SDK is installed $lyncSDKPath = "Microsoft Office\Office15\LyncSDK\Assemblies\Desktop\Microsoft.Lync.Model.dll" $lyncSDKError = "Lync 2013 SDK is required. Download here and install: http://www.microsoft.com/en-us/download/details.aspx?id=36824" if (-not (Get-Module -Name Microsoft.Lync.Model)) { if (Test-Path (Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath $lyncSDKPath)) { $lyncPath = Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath $lyncSDKPath } elseif (Test-Path (Join-Path -Path ${env:ProgramFiles} -ChildPath $lyncSDKPath)) { $lyncPath = Join-Path -Path ${env:ProgramFiles} -ChildPath $lyncSDKPath } else { $fileError = New-Object System.io.FileNotFoundException("SDK Not Found: $lyncSDKError") throw $fileError } # End SDK/DLL check try { Import-Module -Name $lyncPath -ErrorAction Stop } catch { $fileError = New-Object System.io.FileNotFoundException ("Import-Module Error: $lyncSDKError") throw $fileError } # End object model import } # End dll check ## Check if Lync is signed in, otherwise, nothing to do $Client = [Microsoft.Lync.Model.LyncClient]::GetClient() if ($Client.State -eq "SignedIn") { ## Set PersonalNote in Lync $LyncInfo = New-Object 'System.Collections.Generic.Dictionary[Microsoft.Lync.Model.PublishableContactInformationType, object]' $LyncInfo.Add([Microsoft.Lync.Model.PublishableContactInformationType]::PersonalNote, "@$($screen_name): $($tweet.text)") $Self = $Client.Self $Publish = $Self.BeginPublishContactInformation($LyncInfo, $null, $null) $Self.EndPublishContactInformation($Publish) } else { Write-Warning "Lync must be signed in." } # End client sign-in check
PowerShellCorpus/GithubGist/RobinNilsson_2420987_raw_1394e83b487904ff850eb4ba4fcedcdb2bc98bbf_gistfile1.ps1
RobinNilsson_2420987_raw_1394e83b487904ff850eb4ba4fcedcdb2bc98bbf_gistfile1.ps1
$whatever $opt = [GenericUriParserOptions]::GenericAuthority $parser = new-object system.GenericUriParser $opt if (![UriParser]::IsKnownScheme("whatever")) { [UriParser]::Register($parser,"/" $whatever,-1) } new-object system.uri("http:localhost:7080")
PowerShellCorpus/GithubGist/jm-welch_6198171_raw_f9cc71fa0ed373fc1963a18b85610aa670ab681e_Send-MailMessages.ps1
jm-welch_6198171_raw_f9cc71fa0ed373fc1963a18b85610aa670ab681e_Send-MailMessages.ps1
function Send-MailMessages { <# .SYNOPSIS Send a batch of emails very quickly. .DESCRIPTION This script is designed to assist in generating email messages for testing internal/external message flow for your messaging infrastructure. The ability to quickly send a batch of messages with an attachment on a schedule can help track flow issues, to confirm mail routing, or to test 'high-load' scenarios. .EXAMPLE Send-MailMessages -Count 10 Send 10 messages with no delay. .EXAMPLE Send-MailMessages -Count 10 -Batch 1 Send 10 messages with no delay, and include "Batch 1" in the Subject. .EXAMPLE Send-MailMessages 10 1 Same as Example 2 .EXAMPLE Send-MailMessages -Count 5 -Delay 300 Send 5 messages 5 minutes (300 seconds) apart. .EXAMPLE Send-MailMesages -Count 24 -Delay 3600 -AttachmentSizeMB 2 Send one message an hour for 24 hours, each with a 2 MB attachment. .PARAMETER Count Number of email messages to send in this batch .PARAMETER Batch (Optional) Prepends "Batch # - " to the subject of the email if set. .PARAMETER Delay (Optional) Number of seconds to delay between messages. If not present or 0, there will be no delay between messages. .PARAMETER AttachmentSizeMB (Optional) Attach a file of the given size to the messages. Files will be created in %TEMP% in the following format: "1mbfile.txt" Once added, the attachment becomes part of the persistent settings. Run with -Setup to remove. .PARAMETER Body (Optional) Customize the text in the body of the email messages. .PARAMETER TimeStamp (Optional) If present, include a timestamp in the message subject. .PARAMETER Setup Manually trigger the Setup segment, and exit the script once complete. .LINK This Script: http://creativelazy.blogspot.com/2013/08/send-batches-of-test-email-from.html Original : http://jfrmilner.wordpress.com/2010/08/26/send-mailmessages .NOTES Based on jfrmilner's Send-MailMessages.ps1 from http://jfrmilner.wordpress.com/2010/08/26/send-mailmessages File Name: Send-MailMessages.ps1 Authors : jfrmilner ([email protected]) jm-welch ([email protected]) Requires : Powershell v2 Requires : Exchange Management Shell (to auto-discover the SMTP server) Legal : This script is provided "AS IS" with no warranties or guarantees, and confers no rights. You may use, modify, reproduce, and distribute this script file in any way provided that you agree to give the original author credit. Version : v1.0 - 2010 Aug 08 (jfrmilner) - First Version http://poshcode.org/* Version : v1.1 - 2012 April 26 (jfrmilner) - Fixed when only a single HT Server is available. - Added check for existing file. - Fixed attachment parameter to use varible. Version : v2.0 - 2013 Aug 09 (jwelch) - Restructured script with new features/variables. - Added option for no delay between messages. - Added option to specify a "Batch" number. - Made timestamping in Subject optional. - Added Setup segment to store persistent variables, with check for Exchange function (so EMS isn't required, just recommended) - Expanded AutoHelp comment with new values - Added Try/Catch block to exit if we get an SmtpException - Added test for administrator role to file create #> param([Int32]$Count=0, [int32]$Batch=0, [Int32]$Delay=0, [Int32]$AttachmentSizeMB=0, [string]$Body, [switch]$TimeStamp, [switch]$Setup) if (!(Test-Path variable:MessageParameters) -or $Setup){ Write-Host -ForegroundColor Yellow "`nSetup Persistent Values" if (!($Setup)) { Write-Host -ForegroundColor Yellow "(You will only have to do this once for this PS session)" } $To = Read-Host 'Enter the "To" email address' $From = Read-Host 'Enter the "From" email address' if (! $Body) { $Body = "Test message, please ignore" } Try { Write-Host -ForegroundColor Yellow "`nSMTP servers:" Get-TransportServer | Select -ExpandProperty Name $SmtpServer = Read-Host "`nEnter the name of the SMTP server to use (blank to use first server in list)" if ($SmtpServer -eq '') { $SmtpServer = @(Get-TransportServer)[0].Name.ToString() } } Catch [System.Management.Automation.CommandNotFoundException] { Write-Host -ForegroundColor Red "Run this script in EMS to show a list of SMTP servers." $SmtpServer = Read-Host "Manually specify the SMTP server to use" } $global:messageParameters = @{ Body = $Body From = $From To = $To SmtpServer = $SmtpServer } } if ($AttachmentSizeMB) { if (!(Test-Path $Env:TMP\$($AttachmentSizeMB)mbfile.txt)) { If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Write-Host -ForegroundColor Red "Administrative privileges are required to create the attachment file." Write-Host -ForegroundColor Red "Launch PowerShell using 'Run As Administrator' for this feature." } Else { fsutil file createnew $Env:TMP\$($AttachmentSizeMB)mbfile.txt $($AttachmentSizeMB * 1MB) } } if ((Test-Path $Env:TMP\$($AttachmentSizeMB)mbfile.txt)) { $messageParameters.Add("Attachment", "$Env:TMP\$($AttachmentSizeMB)mbfile.txt") } } $msg = "`nSending $Count Mail Message(s)" if ($Batch -gt 0) { $msg += " as Batch $Batch" } if ($Delay -gt 0) { $msg += " every $Delay seconds" } $msg += " with the following parameters:" Write-Host -ForegroundColor Yellow $msg $MessageParameters Write-Host -ForegroundColor Yellow "`nRun 'Send-MailMessages -Setup' to change these values" if ($Setup) { return } if ($Count -lt 1) { Write-Host -ForegroundColor Red "Send aborted - no count provided." Write-Host -ForegroundColor Red "Use '-Count #' to specify." return } $Subject = "Test email " if ($TimeStamp) { $Subject += (Get-Date).ToLongTimeString() } if ($Batch -gt 0) { $Subject = "Batch $batch - " + $Subject } 1..$Count | %{ if ($Delay) { Sleep -Seconds $Delay } Try { Send-MailMessage @MessageParameters -Subject ("$Subject (" + $_ + "/$Count)") -BodyAsHtml } Catch [System.Net.Mail.SmtpException] { Write-Host -ForegroundColor Red ("`nSmtpServer " + $MessageParameters.SmtpServer + " is not valid.") Write-Host -ForegroundColor Red "Run 'Send-MailMessages -Setup' and specify a valid server." return } } Write-Host -ForegroundColor Yellow "`nProcessing complete" }
PowerShellCorpus/GithubGist/mlhDevelopment_f84f7297131705a63191_raw_030b95afdce4b4444e8870881e95dcc57b06df4f_gistfile1.ps1
mlhDevelopment_f84f7297131705a63191_raw_030b95afdce4b4444e8870881e95dcc57b06df4f_gistfile1.ps1
# Rotates a vertical set similar to an Excel PivotTable # # Given $data in the format: # # Category Activity Duration # ------------ ------------ -------- # Management Email 1 # Management Slides 4 # Project A Email 2 # Project A Research 1 # Project B Research 3 # # with $keep = "Category", $rotate = "Activity", $value = "Duration" # # Return # # Category Email Slides Research # ---------- ----- ------ -------- # Management 1 4 # Project A 2 1 # Project B 3 $rotate = "Activity" $keep = "Category" $value = "Duration" $pivots = $data | select -unique $rotate | foreach { $_.Activity} $data | group $keep | foreach { $group = $_.Group $row = new-object psobject $row | add-member NoteProperty $keep $_.Name foreach ($pivot in $pivots) { $row | add-member NoteProperty $pivot ($group | where { $_.$rotate -eq $pivot } | measure -sum $value).Sum } $row }
PowerShellCorpus/GithubGist/bcatcho_4531873_raw_df131f2bcf525f28c9de7f2eef4e90a884643c40_CompileForAzure.ps1
bcatcho_4531873_raw_df131f2bcf525f28c9de7f2eef4e90a884643c40_CompileForAzure.ps1
& ("C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe") /nologo ` ../Ask3Cloud/Ask3Cloud.sln ` /p:SkipInvalidConfigurations=true ` /p:TargetProfile="Dev" ` /t:"publish;Build" ` /p:Configuration="Release" ` /p:Platform="Any CPU" ` /p:RunCodeAnalysis="False" ` /v:minimal
PowerShellCorpus/GithubGist/Pampus_d6ba7c400b92ee60fbdd_raw_1b655e6f73bea4126c270c09468a750bba0f9674_importSjisCsv.ps1
Pampus_d6ba7c400b92ee60fbdd_raw_1b655e6f73bea4126c270c09468a750bba0f9674_importSjisCsv.ps1
Get-Content <filepath> | ConvertFrom-Csv
PowerShellCorpus/GithubGist/selfcommit_9139532_raw_8d9b38aa20f25b5f61c291eae8d611cec5565163_view.ps1
selfcommit_9139532_raw_8d9b38aa20f25b5f61c291eae8d611cec5565163_view.ps1
############################################################################ # Scriptname: Pool_Prov.ps1 # Description: Checks against ADAM for Pool Status # By: Adam Baldwin # Edited for Hillsborough Township Public Schools by Dan O'Boyle # Usage: Use this script to check whether any pools are in a non-provisioning # state and send an email alert with a list of errors # ############################################################################ # Specify the LDAP path to bind to, here the Pools OU (Server Group) $LDAPPath = 'OUR_LDAP_SERVERPATH_HERE' $LDAPEntry = New-Object DirectoryServices.DirectoryEntry $LDAPPath # Create a selector and start searching from the path specified in $LDAPPath $Selector = New-Object DirectoryServices.DirectorySearcher $Selector.SearchRoot = $LDAPEntry # Run the FindAll() method and limit to only return what corresponds to Pools # in VMware View $Pools = $Selector.FindAll() | where {$_.Properties.objectcategory -match "CN=pae-ServerPool"} # Creates registry keys if they do not already exist if (!(Test-Path -Path "hklm:software\VMWare, Inc.\stats")) { new-item -path "hklm:software\VMWare, Inc.\stats" New-ItemProperty "hklm:\software\VMWare, Inc.\stats" -Name "enabled" -Value "" -PropertyType "String" New-ItemProperty "hklm:\software\VMWare, Inc.\stats" -Name "disabled" -Value "" -PropertyType "String" } # Instantiate variables $list = "" $pool_ids = @() $pool_state = @() $pool_error = @() $error_msg = "" $a = 0 $hash = @{} $error_hash = @{} $error_count = 0 $disabled = "" $enabled = "" # Loop thru each pool found in the above $Pools $count = $pools.count for ( $i = 0 ; $i -lt $count; $i++ ) { $pool_ids += @($i) } for ( $i = 0 ; $i -lt $count; $i++ ) { $pool_state += @($i) } if ($count -eq $null) { $Pool_ids = @(1) $Pool_state = @(1) } foreach ($Pool in $Pools) { $attribute = $Pool.Properties # Define what value we are looking for, here we are retrieving pool name $value = 'name' $status = 'pae-vmprovenabled' $msg = 'pae-vmproverror' $pool = $attribute.$value $state = $attribute.$status $error_msg = $attribute.$msg # Check if pool is provisioning or disabled and record into hash table if (!$error_msg) { $error_msg = "No error to report." } $pool_state[$a] = $state $pool_ids[$a] = $pool if ($($pool_state[$a]) -eq 0) { $hash.add("$pool", 0) $error_hash.add("$pool", "$error_msg") $Error_count += 1 $disabled += $pool + "," $disabled = $disabled -Replace " ", "" } elseif ($($pool_state[$a]) -eq 1) { $hash.Add("$pool", 1) $enabled += $pool + "," $enabled = $enabled -Replace " ", "" } $a++ } # Build hashtables for error count and messages, build variables $Pool_msg = @() for ( $i = 0 ; $i -lt $error_count; $i++ ) { $pool_error += @($i) } for ( $i = 0 ; $i -lt $error_count; $i++ ) { $pool_msg += @($i) } $a = 0 $exc = 0 $ds_test = (Get-ItemProperty "hklm:software\VMWare, Inc.\stats").disabled $ds_test = $ds_test -split "," $disable_new = $disabled -split "," foreach ($id in $pool_ids) { if ($($hash[$id]) -eq 1) { } elseif ($($hash[$id]) -eq 0) { $pool_error[$exc] = $id $pool_msg[$exc] = " - " + $error_hash["$id"] $exc++ } $a++ } # count to determine whether email should be sent $send = 0 $exc = 0 foreach ($fail in $pool_error) { if ($ds_test -contains $disable_new[$exc]) {} else { $list += $pool_error[$exc] + $pool_msg[$exc] + "`n" $send++ } $exc++ } $date = Get-Date $EmailTo = "[email protected]", "[email protected]" $EmailFrom = "[email protected]" $EmailSubject = "POOL - PROVISION ERROR "+$date $SMTPSRV = "post.hillsborough.k12.nj.us" $MyReport = "The following Pools have stopped provisioning due to one or more errors: `n`n" + $list #Set-ItemProperty "hklm:software\VMWare, Inc.\stats" -Name enabled -Value $enabled #Set-ItemProperty "hklm:software\VMWare, Inc.\stats" -Name disabled -Value $disabled if ($send -ne "0"){send-Mailmessage -To $EmailTo -From $EmailFrom -Subject $EmailSubject -SmtpServer $SMTPSRV -Body $MyReport}
PowerShellCorpus/GithubGist/sopelt_ed8315998f3105c2a7a5_raw_e23732df4d39d70cc131ffe24f8fb74b7d3d265d_PrintAzureServiceVersions.ps1
sopelt_ed8315998f3105c2a7a5_raw_e23732df4d39d70cc131ffe24f8fb74b7d3d265d_PrintAzureServiceVersions.ps1
# based on http://blogs.msdn.com/b/wats/archive/2014/05/19/how-to-determine-current-guest-os-family-only-for-pass-instance-web-role-and-worker-role-windows-azure-powershell.aspx # # setup Azure publish settings according to http://blogs.msdn.com/b/wats/archive/2013/02/18/windows-azure-powershell-getting-started.aspx foreach ($Subscription in (Get-AzureSubscription)) { Select-AzureSubscription -SubscriptionName $Subscription.SubscriptionName Write-Host "Subscription:" $Subscription.SubscriptionName foreach ($Service in (Get-AzureService)) { Write-Host " Service:" $Service.ServiceName foreach ($Deployment in (Get-AzureDeployment -ErrorAction SilentlyContinue -ServiceName $Service.ServiceName)) { Write-Host " Deployment:" $Deployment.Label [System.Xml.XmlDocument] $DeploymentConfigurationXML = new-object System.Xml.XmlDocument $DeploymentConfigurationXML.LoadXml($Deployment.Configuration) Write-Host " SDK:" $Deployment.SdkVersion Write-Host " OS Family:" $DeploymentConfigurationXML.ServiceConfiguration.osFamily Write-Host " OS Version:" $DeploymentConfigurationXML.ServiceConfiguration.osVersion Write-Host } } Write-Host }
PowerShellCorpus/GithubGist/blakmatrix_3026832_raw_a482692f53872ae5892b46babb207ec6e77538b4_gistfile1.ps1
blakmatrix_3026832_raw_a482692f53872ae5892b46babb207ec6e77538b4_gistfile1.ps1
PS C:\Users\fred rosak> cd .\projects PS C:\Users\fred rosak\projects> jitsu install path.existsSync is now called `fs.existsSync`. info: Welcome to Nodejitsu blakmatrix info: It worked if it ends with Nodejitsu ok info: Executing command install help: The install command downloads pre-built node applications help: To continue, you will need to select an application info: Please choose a node app so we can get you started info: Available node apps: info: helloworld demo `hello world` http server info: express express.js boilerplate info: socket.io socket.io boilerplate info: http-server a robust and customizable http server prompt: Which node app would you like to install? (helloworld): socket.io info: Installing socket.io locally warn: Downloading packages from npm, this may take a moment... info: socket.io installed path.exists is now called `fs.exists`. help: You can now jitsu deploy this application prompt: Would you like to start this application locally? (yes): info: socket.io is now starting help: To exit application, press CTRL-C '.' is not recognized as an internal or external command, operable program or batch file. error: Error running command install error: [email protected] start: `./bin/server` `cmd "/c" "./bin/server"` failed with 1 info: Nodejitsu not ok PS C:\Users\fred rosak\projects> ls Directory: C:\Users\fred rosak\projects Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 6/30/2012 9:34 PM socket.io PS C:\Users\fred rosak\projects> c socket.io The term 'c' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:2 + c <<<< socket.io + CategoryInfo : ObjectNotFound: (c:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\fred rosak\projects> cd socket.io PS C:\Users\fred rosak\projects\socket.io> ls Directory: C:\Users\fred rosak\projects\socket.io Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 6/30/2012 9:34 PM bin d---- 6/30/2012 9:34 PM node_modules d---- 6/30/2012 9:34 PM public -a--- 6/30/2012 9:34 PM 453 package.json -a--- 6/30/2012 9:34 PM 1669 ReadMe.md PS C:\Users\fred rosak\projects\socket.io> jitsu login path.existsSync is now called `fs.existsSync`. info: Welcome to Nodejitsu blakmatrix info: It worked if it ends with Nodejitsu ok info: Executing command login prompt: username: blakmatrix prompt: password: tty.setRawMode: Use `process.stdin.setRawMode()` instead. info: Authenticated as blakmatrix info: Nodejitsu ok PS C:\Users\fred rosak\projects\socket.io> jitsu deploy path.existsSync is now called `fs.existsSync`. info: Welcome to Nodejitsu blakmatrix info: It worked if it ends with Nodejitsu ok info: Executing command deploy warn: warn: Your package.json file is missing required fields: warn: warn: subdomain warn: warn: Your package.json file has invalid required fields: warn: warn: engines warn: warn: Prompting user for required fields. warn: Press ^C at any time to quit. warn: help: help: The subdomain is where your application will reside. help: Your application will then become accessible at: http://yourdomain.jit.su help: prompt: subdomain (blakmatrix.socket.io): prompt: engines (0.8.x): warn: About to write C:\Users\fred rosak\projects\socket.io\package.json data: data: { data: subdomain: 'blakmatrix.socket.io', data: optionalDependencies: {}, data: devDependencies: {}, data: dependencies: { socket.io: 'v0.8.x', express: 'v2.5.x' }, data: scripts: { start: './bin/server' }, data: version: '0.1.0-1', data: name: 'nodeapps-socket.io', data: author: { email: '[email protected]', name: 'Nodejitsu Inc.' }, data: engines: { node: '0.8.x' }, data: dist: { shasum: '34ed79d668fbf5265c2db137cffcf939f9b97e0a' }, data: analyze: false data: } data: prompt: Is this ok? (yes): info: Skipping require-analyzer because noanalyze option is set info: Checking app availability nodeapps-socket.io info: Creating app nodeapps-socket.io info: Creating snapshot 0.1.0-1 info: Updating app nodeapps-socket.io info: Activating snapshot 0.1.0-1 for nodeapps-socket.io info: Stopping app nodeapps-socket.io info: App nodeapps-socket.io is now stopped info: Starting app nodeapps-socket.io error: Error running command deploy error: Nodejitsu Error (500): Internal Server Error error: There was an error while attempting to deploy your application. error: error: Error spawning drone: no matching engine found error: Repository configuration error: error: This type of error is usually a user error. error: Error output from Haibu: error: error: Error: Error spawning drone: no matching engine found error: at [object Object].getSpawnOptions (/root/haibu-orchestra/node_modules/haibu/lib/haibu/core/spawner.js:34:17) error: at [object Object].getSpawnOptions (/root/haibu-orchestra/node_modules/haibu/lib/haibu/plugins/useraccounts.js:30:33) error: at spawnNpm (/root/haibu-orchestra/node_modules/haibu/lib/haibu/plugins/useraccounts.js:58:32) error: at Object.oncomplete (/root/haibu-orchestra/node_modules/haibu/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js:94:5) info: Nodejitsu not ok PS C:\Users\fred rosak\projects\socket.io>
PowerShellCorpus/GithubGist/tugberkugurlu_a330503930565bbae4e1_raw_073750edf56055af3376d2a7fe17234eb7f845c8_build.ps1
tugberkugurlu_a330503930565bbae4e1_raw_073750edf56055af3376d2a7fe17234eb7f845c8_build.ps1
param( $buildFile = (join-path (Split-Path -parent $MyInvocation.MyCommand.Definition) "build.msbuild"), $buildParams = "/p:Configuration=Release", $buildTarget = "/t:Default" ) & "${env:ProgramFiles(x86)}\MSBuild\14.0\Bin\MSBuild.exe" $buildFile $buildParams $buildTarget /verbosity:diagnostic
PowerShellCorpus/GithubGist/thedrow_5518156_raw_45bb26d9259da4ac23edb33f32fc66ddb7a1647a_gistfile1.ps1
thedrow_5518156_raw_45bb26d9259da4ac23edb33f32fc66ddb7a1647a_gistfile1.ps1
cinst poshgit Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Confirm
PowerShellCorpus/GithubGist/aigarsdz_6071059_raw_851de9e25326a440c32f0f5cd15bf7f9281ba836_create.ps1
aigarsdz_6071059_raw_851de9e25326a440c32f0f5cd15bf7f9281ba836_create.ps1
param ( # A user has to provide the post title as a -Post parameter in order # for script to work. [string]$post = $(throw "-post is required") ) # Convert any text to a URL friendly string. # # $title - String to convert. # # Examples: # # parameterize("Šis ir gadījuma teksts!") # #=> sis-ir-gadijuma-teksts # # Returns a String. function parameterize($title) { $parameterized_title = $title.ToLower() $words = $parameterized_title.Split() $normalized_words = @() foreach ($word in $words) { # Convert a Unicode string into its ASCII counterpart, e.g. māja -> maja. $normalized_word = $word.Normalize([Text.NormalizationForm]::FormD) # Normalize method returns ASCII letters together with a symbol that "matches" # the diacritical mark used in the Unicode. These symbols have to be removed # in order to get a valid string. $normalized_words += $normalized_word -replace "[^a-z0-9]", [String]::Empty } $normalized_words -join "-" } $current_datetime = get-date $current_date = $current_datetime.ToString("yyyy-MM-dd") $url_title = parameterize($post) $filename = "{0}-{1}.md" -f $current_date, $url_title # Jekyll and Pretzel stores posts in a _posts directory, # therefore we have to make sure this directory exists. if (-not (test-path _posts)) { new-item -itemtype directory _posts } $path = "_posts/{0}" -f $filename new-item -itemtype file $path # Add the default YAML Front Matter at the top of the file. "---" >> $path "layout: post" >> $path "title: " + $post >> $path "---" >> $path
PowerShellCorpus/GithubGist/obscuresec_df5f652c7e7088e2412c_raw_3aa76e30b3d08f236a42a83bbcfdaf20f71c6044_gistfile1.ps1
obscuresec_df5f652c7e7088e2412c_raw_3aa76e30b3d08f236a42a83bbcfdaf20f71c6044_gistfile1.ps1
function Test-SmbPassword { <# .SYNOPSIS Tests a username and password to see if it is valid against a remote machine or domain. Author: Chris Campbell (@obscuresec) License: BSD 3-Clause Required Dependencies: None Optional Dependencies: None Version: 0.1.0 .DESCRIPTION Tests a username and password to see if it is valid against a remote machine or domain. .EXAMPLE PS C:\> Test-SmbPassword -ComputerName 2K8DC -UserName test123 -Password password123456! -Domain Password Username Valid -------- -------- ----- password123456! test123 True .EXAMPLE PS C:\> Get-Content 'c:\demo\usernames.txt' | Test-SmbPassword -ComputerName 'DC1' -Password 'Passsword123456!' -Domain Password Username Valid -------- -------- ----- password123456! test False password123456! Administrator False password123456! tomcat False password123456! test123 True .LINK #> [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [String] $ComputerName, [parameter(Mandatory = $True,ValueFromPipeline=$True)] [String] $UserName, [parameter(Mandatory = $True)] [String] $Password, [parameter()] [Switch] $Domain ) Begin {Set-StrictMode -Version 2} Process { #try to load assembly Try {Add-Type -AssemblyName System.DirectoryServices.AccountManagement} Catch {Write-Error $Error[0].ToString() + $Error[0].InvocationInfo.PositionMessage} If ($Domain) {$ContextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain} Else {$ContextType = [System.DirectoryServices.AccountManagement.ContextType]::Machine} Try { $PrincipalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ContextType, $ComputerName) $Valid = $PrincipalContext.ValidateCredentials($Username, $Password).ToString() If ($Valid) {Write-Verbose "SUCCESS: $Username works with $Password"} Else {Write-Verbose "FAILURE: $Username did not work with $Password"} #Create custom object to output results $ObjectProperties = @{'Username' = $UserName; 'Password' = $Password; 'Valid' = $Valid} $ResultsObject = New-Object -TypeName PSObject -Property $ObjectProperties Return $ResultsObject } Catch {Write-Error $Error[0].ToString() + $Error[0].InvocationInfo.PositionMessage} } }
PowerShellCorpus/GithubGist/Jiangtang_5420439_raw_404dca8f1cd0af628e62d4b1723060e90d6506fe_SasMetadataGetColumns.ps1
Jiangtang_5420439_raw_404dca8f1cd0af628e62d4b1723060e90d6506fe_SasMetadataGetColumns.ps1
# SasMetadataGetColumns.ps1 # Example usage: # For table grid display, use: # .\SasMetadataGetColumns.ps1 | Out-Gridview # For export to CSV # .\SasMetadataGetColumns.ps1 | Export-Csv -Path "c:\output\cols.csv" -NoTypeInformation # ------------------------------------------------------------------- # create the Integration Technologies objects $objFactory = New-Object -ComObject SASObjectManager.ObjectFactoryMulti2 $objServerDef = New-Object -ComObject SASObjectManager.ServerDef # assign the attributes of your metadata server $objServerDef.MachineDNSName = "yournode.company.com" $objServerDef.Port = 8561 # metadata server port $objServerDef.Protocol = 2 # 2 = IOM protocol # Class Identifier for SAS Metadata Server $objServerDef.ClassIdentifier = "0217E202-B560-11DB-AD91-001083FF6836" # connect to the server # we'll get back an OMI handle (Open Metadata Interface) try { $objOMI = $objFactory.CreateObjectByServer( "", $true, $objServerDef, "sasdemo", # metadata user ID "Password1" # password ) Write-Host "Connected to " $objServerDef.MachineDNSName } catch [system.exception] { Write-Host "Could not connect to SAS metadata server: " $_.Exception exit -1 } # get list of repositories $reps="" # this is an "out" param we need to define $rc = $objOMI.GetRepositories([ref]$reps,0,"") # parse the results as XML [xml]$result = $reps # filter down to "Foundation" repository $foundationNode = $result.Repositories.Repository | ? {$_.Name -match "Foundation"} $foundationId = $foundationNode.Id Write-Host "Foundation ID is $foundationId" $libTemplate = "<Templates>" + "<PhysicalTable/>" + "<Column SASColumnName=`"`" SASColumnType=`"`" SASColumnLength=`"`"/>" + "<SASLibrary Name=`"`" Engine=`"`" Libref=`"`"/>" + "</Templates>" $libs="" # Use GetMetadataObjects method # Usage is similar to PROC METADATA, so you # can look at PROC METADATA doc to get examples # of templates and queries # 2309 flag plus template gets table name, column name, # engine, libref, and object IDs. The template specifies # attributes of the nested objects. $rc = $objOMI.GetMetadataObjects( $foundationId, "PhysicalTable", [ref]$libs, "SAS", 2309, $libTemplate ) # parse the results as XML [xml]$libXml = $libs Write-Host "Total tables discovered: " $libXml.Objects.PhysicalTable.Count # Create output, which you can pipe to another cmdlet # such as Out-Gridview or Export-CSV # for each column in each table, create an output object # (named $objCol here) for ($i=0; $i -lt $libXml.Objects.PhysicalTable.Count; $i++) { $table = $libXml.Objects.PhysicalTable[$i] for ($j=0; $j -lt $table.Columns.Column.Count ; $j++) { $column = $table.Columns.Column[$j] $objCol = New-Object psobject $objCol | add-member noteproperty -name "Libref" -value $table.TablePackage.SASLibrary.Libref $objCol | add-member noteproperty -name "Table" -value $table.SASTableName $objCol | add-member noteproperty -name "Column" -value $column.SASColumnName $objCol | add-member noteproperty -name "Type" -value $column.SASColumnType $objCol | add-member noteproperty -name "Length" -value $column.SASColumnLength # emit the object to stdout or other cmdlet $objCol } }
PowerShellCorpus/GithubGist/piers7_6432985_raw_9a5c62dbf11794b8214601d093401d1951d334a7_Load-TeamCityProperties.ps1
piers7_6432985_raw_9a5c62dbf11794b8214601d093401d1951d334a7_Load-TeamCityProperties.ps1
<# .Synopsis Loads TeamCity system build properties into the current scope Unless forced, doesn't do anything if not running under TeamCity #> param( $prefix = 'TeamCity.', $file = $env:TEAMCITY_BUILD_PROPERTIES_FILE + ".xml", [switch] $inTeamCity = (![String]::IsNullOrEmpty($env:TEAMCITY_VERSION)) ) if($inTeamCity){ Write-Host "Loading TeamCity properties from $file" $file = (Resolve-Path $file).Path; $buildPropertiesXml = New-Object System.Xml.XmlDocument $buildPropertiesXml.XmlResolver = $null; # force the DTD not to be tested $buildPropertiesXml.Load($file); $buildProperties = @{}; foreach($entry in $buildPropertiesXml.SelectNodes("//entry")){ $key = $entry.key; $value = $entry.'#text'; $buildProperties[$key] = $value; $key = $prefix + $key; Write-Verbose ("[TeamCity] Set {0}={1}" -f $key,$value); Set-Variable -Name:$key -Value:$value -Scope:1; # variables are loaded into parent scope } }
PowerShellCorpus/GithubGist/dfinke_5182497_raw_d799777e9e8aded409527c2baaafabe3edc48d74_IseNode.ps1
dfinke_5182497_raw_d799777e9e8aded409527c2baaafabe3edc48d74_IseNode.ps1
$sb = { $node = "node.exe" if(!(Get-Command $node -ErrorAction SilentlyContinue)) { throw "Could not find $node" } $psISE.CurrentFile.Save() & $node $psISE.CurrentFile.FullPath } $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Invoke Node", $sb, "CTRL+F6")
PowerShellCorpus/GithubGist/timparkinson_3851325_raw_27ffae38589369a620001643b37afc506e45782c_LoadConfig.ps1
timparkinson_3851325_raw_27ffae38589369a620001643b37afc506e45782c_LoadConfig.ps1
# LoadConfig.ps1 # # Simplified method of maintaining module specific configuration files. # Based on: http://rkeithhill.wordpress.com/2006/06/01/creating-and-using-a-configuration-file-for-your-powershell-scripts/ # and: http://poshcode.org/1608 # [email protected] # Expects a file ModuleName.config.xml # <configuration> # <node key='Name' value='Tim' /> # </configuration> #requires -version 2.0 $module = $ExecutionContext.SessionState.Module if (-not $module) { throw "An active module not found. LoadConfig is to be run from a module manifest's NestedModules field." } else { $settings_name = "$($module.Name)Settings" $configuration_output = @{} $path = Join-Path -Path $PSScriptRoot -ChildPath "$($module.Name).config.xml" if (-not (Test-Path $path)) { throw "Invalid configuration file." } else { $config = [xml](Get-Content -Path $path) foreach ($node in $config.configuration.node) { if ($node.Value.Contains(',')) { # Array $value = $node.Value.Split(',') for ($i = 0; $i -lt $value.length; $i++) { $value[$i] = $value[$i].Trim() } } else { # Scalar $value = $node.value } $configuration_output[$node.Key] = $value } Set-Variable -Name $settings_name -Value $configuration_output -Scope Global } }
PowerShellCorpus/GithubGist/a-oishi_806a873c9a6859ba6ed6_raw_4bf9f741a4f213b77024242e0fee24155ef46f12_gistfile1.ps1
a-oishi_806a873c9a6859ba6ed6_raw_4bf9f741a4f213b77024242e0fee24155ef46f12_gistfile1.ps1
# serial for P9500 $dkc = "" $outfile = "" cd "c:\Program Files\Hewlett-Packard\Performance Advisor\clui" # Get thp pools .\thp.bat -dkc $dkc -L # Get lund pools .\lund.bat -dkc $dkc -dver 015100 -L # Get configs .\exportdb.bat -dkc $dkc -st 02.01.2015 00:00:00 -et 02.01.2015 00:00:10 -dver 020000 -file $outfile .\exportdb.bat -dkc $dkc -st 01.15.2015 00:00:00 -et 01.15.2015 00:00:10 -dver 020000 -file $outfile .\exportdb.bat -dkc $dkc -st 01.31.2015 00:00:00 -et 01.31.2015 00:00:10 -dver 020000 -file $outfile
PowerShellCorpus/GithubGist/zplume_5865633_raw_a529bbe7c3264f171eb83c8c15a69858c32663c5_UpdateUserInfo.ps1
zplume_5865633_raw_a529bbe7c3264f171eb83c8c15a69858c32663c5_UpdateUserInfo.ps1
##### ABOUT ##### # This script updates the mobile number and work number values # for all users in the "User Information List" for all site collections # in the specified web application (see variables below) ##### VARIABLES ##### $webAppURL = "http://mywebapp" $logPath = "C:\temp\UpdateUserInfo\UpdateUserInfo" ##### FUNCTIONS ##### Function GetUserInfo($web) { $list = $web.Lists["User Information List"] $items = $list.Items return $items } Function UpdateUserInfoFromAD($log, $userInformationItem, $loginName, $spMobileNo, $spWorkNo) { # get the username from the login name (remove "DOMAIN\") $username = $loginName.Split("\")[1] # get the user object from AD $query = "SELECT * FROM ds_user where ds_sAMAccountName='$username'" $user = Get-WmiObject -Query $query -Namespace "root\Directory\LDAP" # track whether or not the item was updated $itemUpdated = $false $mobileNo = $user.DS_mobile if(![string]::IsNullOrEmpty($mobileNo)) { if($mobileNo -ne $spMobileNo) { Write-Host -foregroundcolor Green "Mobile number in AD is" $mobileNo $userInformationItem["MobilePhone"] = $mobileNo # update $itemUpdated = $true } } else { Write-Host -foregroundcolor Red "Mobile number not found in AD" } $log += $($mobileNo + "`t") $workNo = $user.DS_telephoneNumber if(![string]::IsNullOrEmpty($workNo)) { if($workNo -ne $spWorkNo) { Write-Host -foregroundcolor Green "Work number in AD is" $workNo $userInformationItem["WorkPhone"] = $workNo # update $itemUpdated = $true } } else { Write-Host -foregroundcolor Red "Work number not found in AD" } $log += $($workNo + "`t") if($itemUpdated) { $userInformationItem.SystemUpdate() # save the changes } $log += $($itemUpdated.ToString() + "`r`n") return $log } ##### SCRIPT START ###### $webApp = Get-SPWebApplication $webAppURL foreach($site in $webApp.Sites) { $web = $site.RootWeb $web.AllowUnsafeUpdates = $true # get last bit of URL, store in $webName variable (used to name the log file) $urlParts = $web.Url.Split("/") [System.Array]::Reverse($urlParts) $webName = $urlParts[0] # create the log variable for this site collection (tab separated values file), set the headers $log = "Site`tUser`tSPMobile`tSPWork`tADMobile`tADWork`tItemUpdated`r`n"; Write-Host -foregroundcolor White $web.Url $items = GetUserInfo $web # create error log variable (tab separated values file), set the headers $errLog = "Site`tUser`tError`r`n" # create a flag to determine whether or not any errors occured for this site collection $errorsLogged = $false foreach($item in $items) { $userInfo = [xml]$item.Xml # get the Xml try { # skip groups if($userInfo.row.ows_ContentType -eq "Person") { $log += $($web.Url + "`t") # log web URL $log += $($userInfo.row.ows_Name + "`t") # log user login name # get mobile number $spMobileNo = $userInfo.row.ows_MobilePhone # get work number $spWorkNo = $userInfo.row.ows_WorkPhone $log += $($spMobileNo + "`t") # log the MobileNumber value in the User Information List $log += $($spWorkNo + "`t") # log the WorkNumber value in the User Information List # Update the User Information List item with any changes from AD and add the values in AD to the log $log = UpdateUserInfoFromAD $log $item $userInfo.row.ows_Name $spMobileNo $spWorkNo } } catch [Exception] { # log site collection, user, and error message $errLog += $($web.Url + "`t" + $userInfo.row.ows_Name + "`t" + $_.Exception.Message + "`r`n") $errorsLogged = $true # update the error flag so that we know to save the errors to a log file } } if($errorsLogged) { $errLog | Out-File $($logPath + "\ERROR_" + $webName + ".csv") # save the error log } $log | Out-File $($logPath + "\" + $webName + ".csv") # save the log file $web.Dispose() $site.Dispose() }
PowerShellCorpus/GithubGist/jtw_5722025_raw_e42317fa38945f038fb42a36c683d67c900987a3_restoreDB.ps1
jtw_5722025_raw_e42317fa38945f038fb42a36c683d67c900987a3_restoreDB.ps1
# # PowerShell # # Script to determine latest backup file (.bak) for a particular database and restore it. Meant to be used with a scheduled daily job. # # CREATED: 2013-06-06 # MODIFIED: 2013-06-06 @ 11:44AM # AUTHOR: SHATTUCK, JUSTIN $ElapsedTime = [System.Diagnostics.Stopwatch]::StartNew() $productionBackup = Get-ChildItem '\\US-MID-DW1\SQL Backup\BWDW_backup_*.bak' | ?{!($_.PSIsContainer)} | sort -property lastwritetime -Descending | select -first 1 $backupPath = '\\US-MID-DW1\SQL Backup\' Write-Host "Copying backup file " $productionBackup " to local directory..." Copy-Item $productionBackup 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\' Write-Host "Copying backup took : " $ElapsedTime.Elapsed.ToString() $latestbackup = Get-ChildItem 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\BWDW_backup_*.bak' | ?{!($_.PSIsContainer)} | sort -property lastwritetime -Descending | select -first 1 Write-Host "Restoring backup : " $latestbackup.Name # Install SQL-CMD Snap-In for PowerShell Support $sqlSnapin = Get-PSSnapin | where {$_.Name -eq "SqlServerCmdletSnapin100"} if($sqlSnapin -eq $null) { Add-PSSnapin SqlServerCmdletSnapin100 Write-Host "Installing SQL Server Cmdlet Snap-in" } function global:RestoreDB ([string] $restoreDBName) { [string] $dbCommand = "RESTORE DATABASE [$restoreDBname] " + "FROM DISK = N'$latestbackup' " + "WITH FILE = 1, NOUNLOAD, STATS = 10, REPLACE" Write-Host "Starting SQL Restore..." Invoke-Sqlcmd -QueryTimeout 600 -Query $dbCommand } RestoreDB "BWDW" Write-Host "Removing backup file : " $latestbackup.Name Remove-Item $latestbackup Write-Host "Restore completed in : " $ElapsedTime.Elapsed.ToString()
PowerShellCorpus/GithubGist/urasandesu_0765055d973d21bd3743_raw_3857e736e3dd42362228885ce1333d7bb02649ca_ConvertTo-MethodIdentity.ps1
urasandesu_0765055d973d21bd3743_raw_3857e736e3dd42362228885ce1333d7bb02649ca_ConvertTo-MethodIdentity.ps1
function TypeToIdentity { param ( [type] $Type ) if ($Type.HasElementType) { $typeIdentity = TypeToIdentity $Type.GetElementType() } else { $typeIdentity = $Type.Name } if ($Type.IsByRef) { $typeIdentity += "Ref" } if ($Type.IsArray) { $typeIdentity += "Array" } if ($Type.IsPointer) { $typeIdentity += "Pointer" } if ($Type.IsGenericType) { $typeIdentity = $typeIdentity -replace '`', '' } $typeIdentity } function ParameterInfoToIdentity { param ( [System.Reflection.ParameterInfo] $ParameterInfo ) TypeToIdentity $ParameterInfo.ParameterType } function ParameterInfosToIdentity { param ( [System.Reflection.ParameterInfo[]] $ParameterInfos ) $paramsIdentity = "" if (0 -lt $ParameterInfos.Length) { $paramIdentities = New-Object "System.Collections.Generic.List[string]" foreach ($param in $ParameterInfos) { $paramIdentities.Add((ParameterInfoToIdentity $param)) } $paramsIdentity = [string]::Join('', $paramIdentities) } $paramsIdentity } function ConstructorInfoToIdentity { param ( [System.Reflection.ConstructorInfo] $ConstructorInfo ) $name = "Constructor" $paramsIdentity = ParameterInfosToIdentity $ConstructorInfo.GetParameters() $name + $paramsIdentity } function MethodInfoToIdentity { param ( [System.Reflection.MethodInfo] $MethodInfo ) $name = ($MethodInfo.Name -creplace '^get_(.*)', '$1Get') -creplace '^set_(.*)', '$1Set' $genericArgsName = "" if ($MethodInfo.IsGenericMethod) { $genericArgs = $MethodInfo.GetGenericArguments() $genericArgNames = New-Object "System.Collections.Generic.List[string]" foreach ($genericArg in $genericArgs) { $genericArgNames.Add("Of" + $genericArg.Name) } $genericArgsName = [string]::Join('', $genericArgNames) } $paramsIdentity = ParameterInfosToIdentity $MethodInfo.GetParameters() $name + $genericArgsName + $paramsIdentity } function ConvertTo-MethodIdentity { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [System.Reflection.MethodBase[]] $InputObject ) begin { } process { if ($null -ne $InputObject) { foreach ($methodBase in $InputObject) { switch ($methodBase) { { $_ -is [System.Reflection.ConstructorInfo] } { ConstructorInfoToIdentity $methodBase } { $_ -is [System.Reflection.MethodInfo] } { MethodInfoToIdentity $methodBase } Default { throw New-Object System.ArgumentException ('Parameter $Info({0}) is not supported.' -f $methodBase.GetType()) } } } } } end { } } [array].GetMembers() | ? { $_ -is [System.Reflection.MethodBase] } | ConvertTo-MethodIdentity # --- # GetEnumerator # AsReadOnlyOfTTArray # ResizeOfTTArrayRefInt32 # CreateInstanceTypeInt32 # CreateInstanceTypeInt32Int32 # CreateInstanceTypeInt32Int32Int32 # CreateInstanceTypeInt32Array # CreateInstanceTypeInt64Array # CreateInstanceTypeInt32ArrayInt32Array # CopyArrayArrayInt32 # CopyArrayInt32ArrayInt32Int32 # ConstrainedCopyArrayInt32ArrayInt32Int32 # CopyArrayArrayInt64 # CopyArrayInt64ArrayInt64Int64 # ClearArrayInt32Int32 # GetValueInt32Array # GetValueInt32 # GetValueInt32Int32 # GetValueInt32Int32Int32 # GetValueInt64 # GetValueInt64Int64 # GetValueInt64Int64Int64 # GetValueInt64Array # SetValueObjectInt32 # SetValueObjectInt32Int32 # SetValueObjectInt32Int32Int32 # SetValueObjectInt32Array # SetValueObjectInt64 # SetValueObjectInt64Int64 # SetValueObjectInt64Int64Int64 # SetValueObjectInt64Array # LengthGet # LongLengthGet # GetLengthInt32 # GetLongLengthInt32 # RankGet # GetUpperBoundInt32 # GetLowerBoundInt32 # SyncRootGet # IsReadOnlyGet # IsFixedSizeGet # IsSynchronizedGet # Clone # BinarySearchArrayObject # BinarySearchArrayInt32Int32Object # BinarySearchArrayObjectIComparer # BinarySearchArrayInt32Int32ObjectIComparer # BinarySearchOfTTArrayT # BinarySearchOfTTArrayTIComparer1 # BinarySearchOfTTArrayInt32Int32T # BinarySearchOfTTArrayInt32Int32TIComparer1 # ConvertAllOfTInputOfTOutputTInputArrayConverter2 # CopyToArrayInt32 # CopyToArrayInt64 # ExistsOfTTArrayPredicate1 # FindOfTTArrayPredicate1 # FindAllOfTTArrayPredicate1 # FindIndexOfTTArrayPredicate1 # FindIndexOfTTArrayInt32Predicate1 # FindIndexOfTTArrayInt32Int32Predicate1 # FindLastOfTTArrayPredicate1 # FindLastIndexOfTTArrayPredicate1 # FindLastIndexOfTTArrayInt32Predicate1 # FindLastIndexOfTTArrayInt32Int32Predicate1 # ForEachOfTTArrayAction1 # IndexOfArrayObject # IndexOfArrayObjectInt32 # IndexOfArrayObjectInt32Int32 # IndexOfOfTTArrayT # IndexOfOfTTArrayTInt32 # IndexOfOfTTArrayTInt32Int32 # LastIndexOfArrayObject # LastIndexOfArrayObjectInt32 # LastIndexOfArrayObjectInt32Int32 # LastIndexOfOfTTArrayT # LastIndexOfOfTTArrayTInt32 # LastIndexOfOfTTArrayTInt32Int32 # ReverseArray # ReverseArrayInt32Int32 # SortArray # SortArrayArray # SortArrayInt32Int32 # SortArrayArrayInt32Int32 # SortArrayIComparer # SortArrayArrayIComparer # SortArrayInt32Int32IComparer # SortArrayArrayInt32Int32IComparer # SortOfTTArray # SortOfTKeyOfTValueTKeyArrayTValueArray # SortOfTTArrayInt32Int32 # SortOfTKeyOfTValueTKeyArrayTValueArrayInt32Int32 # SortOfTTArrayIComparer1 # SortOfTKeyOfTValueTKeyArrayTValueArrayIComparer1 # SortOfTTArrayInt32Int32IComparer1 # SortOfTKeyOfTValueTKeyArrayTValueArrayInt32Int32IComparer1 # SortOfTTArrayComparison1 # TrueForAllOfTTArrayPredicate1 # Initialize # ToString # EqualsObject # GetHashCode # GetType
PowerShellCorpus/GithubGist/omittones_8509005_raw_004fd22a0577ac1aba994df8b5c4e99ae118eba3_ssh-agent-utils.ps1
omittones_8509005_raw_004fd22a0577ac1aba994df8b5c4e99ae118eba3_ssh-agent-utils.ps1
# SSH Agent Functions # Mark Embling (http://www.markembling.info/) # # How to use: # - Place this file into %USERPROFILE%\Documents\WindowsPowershell (or location of choice) # - Import into your profile.ps1: # e.g. ". (Resolve-Path ~/Documents/WindowsPowershell/ssh-agent-utils.ps1)" [without quotes] # - Enjoy # # Note: ensure you have ssh and ssh-agent available on your path, from Git's Unix tools or Cygwin. # Retrieve the current SSH agent PId (or zero). Can be used to determine if there # is an agent already starting. function Get-SshAgent() { $agentPid = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "User") if ([int]$agentPid -eq 0) { $agentPid = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "Process") } if ([int]$agentPid -eq 0) { 0 } else { # Make sure the process is actually running $process = Get-Process -Id $agentPid -ErrorAction SilentlyContinue if(($process -eq $null) -or ($process.ProcessName -ne "ssh-agent")) { # It is not running (this is an error). Remove env vars and return 0 for no agent. [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "User") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "User") 0 } else { # It is running. Return the PID. $agentPid } } } # Start the SSH agent. function Start-SshAgent() { # Start the agent and gather its feedback info [string]$output = ssh-agent $lines = $output.Split(";") $agentPid = 0 foreach ($line in $lines) { if (([string]$line).Trim() -match "(.+)=(.*)") { # Set environment variables for user and current process. [Environment]::SetEnvironmentVariable($matches[1], $matches[2], "Process") [Environment]::SetEnvironmentVariable($matches[1], $matches[2], "User") if ($matches[1] -eq "SSH_AGENT_PID") { $agentPid = $matches[2] } } } # Show the agent's PID as expected. Write-Host "SSH agent PID:", $agentPid } # Stop a running SSH agent function Stop-SshAgent() { [int]$agentPid = Get-SshAgent if ([int]$agentPid -gt 0) { # Stop agent process $proc = Get-Process -Id $agentPid if ($proc -ne $null) { Stop-Process $agentPid Write-Host "SSH agent ($agentPid) stopped" } # Remove all enviroment variables [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "User") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "User") } } # Add a key to the SSH agent function Add-SshKey() { if ($args.Count -eq 0) { # Add the default key (~/id_rsa) ssh-add } else { foreach ($value in $args) { ssh-add $value } } } # Start the agent if not already running; provide feedback $agent = Get-SshAgent if ($agent -eq 0) { Write-Host "Starting SSH agent..." Start-SshAgent # Start agent Add-SshKey # Add my default key } else { Write-Host "SSH agent is running (PID $agent)" }
PowerShellCorpus/GithubGist/glombard_7457530_raw_5adf52f7ed52ac531b1f250ce96cf54e98d523d7_get-jenkins-git-plugins.ps1
glombard_7457530_raw_5adf52f7ed52ac531b1f250ce96cf54e98d523d7_get-jenkins-git-plugins.ps1
$plugins = "${env:ProgramFiles(x86)}\Jenkins\plugins" $c = New-Object Net.WebClient $c.DownloadFile('http://updates.jenkins-ci.org/download/plugins/git-client/1.4.6/git-client.hpi', "$plugins\git-client.hpi") $c.DownloadFile('http://updates.jenkins-ci.org/download/plugins/scm-api/0.2/scm-api.hpi', "$plugins\scm-api.hpi") $c.DownloadFile('http://updates.jenkins-ci.org/download/plugins/git/2.0/git.hpi', "$plugins\git.hpi") Restart-Service Jenkins
PowerShellCorpus/GithubGist/awmckinley_5fae30c32e5388fdeb13_raw_39706abc4d9326cffd8bd912cb50abc82d8185ce_boxstarter.ps1
awmckinley_5fae30c32e5388fdeb13_raw_39706abc4d9326cffd8bd912cb50abc82d8185ce_boxstarter.ps1
Disable-UAC Set-WindowsExplorerOptions -EnableShowFileExtensions -EnableShowHiddenFilesFoldersDrives Update-ExecutionPolicy -Policy 'RemoteSigned' cinst 7Zip.Install cinst BTSync cinst Cygwin cinst DaemonToolsLite cinst Foobar2000 cinst Git.Install cinst HG cinst Inconsolata cinst Java.JDK cinst KeePass.Install cinst KeePassX cinst LibreOffice cinst LightTable cinst MarkPad cinst Notepad2 cinst PowerShell4 cinst PuTTY.Install cinst ResophNotes cinst SourceTree cinst SublimeText3 cinst SublimeText3.PackageControl cinst SublimeText3.PowerShellAlias cinst Vagrant cinst VirtualBox cinst Waterfox # Install by hand: # GeForce Experience # IntelliType Pro 8.2 # PotPlayer # PureText # TeraCopy # Update for Root Certificates # Visual Studio
PowerShellCorpus/GithubGist/nightroman_1272334_raw_3c338e3c692c329f960878ab37aa0266c8ed1508_Measure-Command2.ps1
nightroman_1272334_raw_3c338e3c692c329f960878ab37aa0266c8ed1508_Measure-Command2.ps1
# Measure-Command with several iterations and progress. # Moved to https://github.com/nightroman/PowerShelf
PowerShellCorpus/GithubGist/HostileCoding_bffd6f7e14eef6c6fa0d_raw_2db6a9d0a1f00bbfffb88183cce2559566db3b29_IFTTT_Alarms.ps1
HostileCoding_bffd6f7e14eef6c6fa0d_raw_2db6a9d0a1f00bbfffb88183cce2559566db3b29_IFTTT_Alarms.ps1
#Variable declaration $vCenterIPorFQDN="192.168.243.172" $vCenterUsername="[email protected]" $vCenterPassword="vmware" $OutputFile="C:\Inetpub\wwwroot\mywebsite\feed.xml" #Where you want to place generated report Remove-Item $OutputFile #Delete files from previous runs Write-Host "Connecting to vCenter" -foregroundcolor "magenta" Connect-VIServer -Server $vCenterIPorFQDN -User $vCenterUsername -Password $vCenterPassword $date = Get-Date -Format o #Feed Header $header=@" <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Triggered Alarms Feed</title> <subtitle>This feed contains all triggered alarms and warnings</subtitle> <link href="http://hostilecoding.blogspot.com" rel="self" /> <link href="http://hostilecoding.blogspot.com/" /> <updated>$($date)</updated> "@ #Feed Footer $footer=@" </feed> "@ $hosts = Get-VMHost | Get-View #Retrieve all hosts from vCenter $HostList = $null #Prevent variable to get dirtied from previous runs foreach ($esxihost in $hosts){ #For each Host foreach($triggered in $esxihost.TriggeredAlarmState){ #For each triggered alarm of each host $arrayline={} | Select HostName, AlarmType, AlarmInformations #Initialize line $alarmDefinition = Get-View -Id $triggered.Alarm #Get info on Alarm $arrayline.HostName = $esxihost.Name #Get host which has this alarm triggered $arrayline.AlarmType = $triggered.OverallStatus #Get if this is a Warning or an Alert $arrayline.AlarmInformations = $alarmDefinition.Info.Name #Get infos about alarm $HostList += $arrayline #Add line to array $HostList = @($HostList) #Post-Declare this is an array } } $header | Out-File -Encoding "UTF8" -Filepath $OutputFile #Do not append, recreate blank file each time $result | Out-File -Encoding "UTF8" -Filepath $OutputFile -append foreach ($item in $HostList){ $body = @" <entry> <title>$(if($($item.AlarmType -eq "red")){"Alarm:"}else{"Warning:"}) $($item.HostName)</title> <link href="http://hostilecoding.blogspot.com/" /> <link rel="alternate" type="text/html" href="http://hostilecoding.blogspot.com/"/> <link rel="edit" href="http://hostilecoding.blogspot.com/"/> <updated>$($date)</updated> <summary>$(if($($item.AlarmType -eq "red")){"Alarm Triggered"}else{"Warning Triggered"}).</summary> <content type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml"> <p>$($item.AlarmInformations)</p> </div> </content> <author> <name>$($vCenterUsername)</name> </author> </entry> "@ $body | Out-File -Encoding "UTF8" -Filepath $OutputFile -append } $footer | Out-File -Encoding "UTF8" -Filepath $OutputFile -append Write-Host "Disconnecting from vCenter" -foregroundcolor "magenta" Disconnect-VIServer -Server $vCenterIPorFQDN -Confirm:$false
PowerShellCorpus/GithubGist/zamber_ac2ff92371496b74a68c_raw_7ee4b6de690f2f231f711f7c270d1d7e00b48fa6_MT-Generate-Worlds.ps1
zamber_ac2ff92371496b74a68c_raw_7ee4b6de690f2f231f711f7c270d1d7e00b48fa6_MT-Generate-Worlds.ps1
# # MTSH (MoreTerra Simple Helper) v0.1.0 # PowerShell 3.0 # # Generate world images from Terraria world with MoreTerra # Configure and fork it as you see fit. # # To schedule it as a task follow this http://j.mp/schedule-powershell # # To host it use http://cestana.com/mongoose.shtml # # Remember to http://j.mp/powershell-dl Get-Help About_Signing # # @author Piotr Zaborowski # @license CC BY-SA 4.0 https://creativecommons.org/licenses/by-sa/4.0/ # # # config $root = "C:\Users\zamber\Documents" $mt = "$root\MoreTerra" $worlds = "$root\My Games\Terraria\Worlds" $dest = "$root\World Maps" $log = "$root\World Maps\log.txt" Function Log { Param ([String]$logstring) $date = Get-Date -UFormat %c Add-Content $log -Value "$date : $logstring" } function Main { Log "Starting ----------------------------------------------------------" Get-ChildItem $worlds\* -Include *.wld | % { $image = "$dest\" + $_.Name + ".png" $worldPath = $_.FullName $args = "-w `"$worldPath`" -o `"$image`"" Log "Running $mt\MoreTerra.exe $args" Start-Process "cmd.exe" "/c $mt\MoreTerra.exe $args" -Wait Log "Done" } } Main
PowerShellCorpus/GithubGist/codingoutloud_f3c74eeceb84f2f7ae15_raw_5e325f41632c473bb8fbe3d9b23250c1520c824d_Format-AzureStorageKey.ps1
codingoutloud_f3c74eeceb84f2f7ae15_raw_5e325f41632c473bb8fbe3d9b23250c1520c824d_Format-AzureStorageKey.ps1
Function Format-AzureStorageKey { [CmdletBinding()] Param ( [parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$True)] [string[]] $Primary, [parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$True)] [string[]] $Secondary, [parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$True)] [string[]] $StorageAccountName, [switch] $AsConnectionString, # noop since is really only current option [switch] $UseSecondary, [switch] $UseHttp # Not providing UsePrimary or UseHttps switches since they are defaults # Consider adding support for proxies and specific services: # http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx ) if ($UseSecondary) { $key = $Secondary } else { $key = $Primary } if ($UseHttp) { $protocol = "http" } else { $protocol = "https" } Write-Host "DefaultEndpointsProtocol=$protocol;AccountName=$StorageAccountName;AccountKey=$key" }
PowerShellCorpus/GithubGist/VertigoRay_6091281_raw_f28fc4a9ad127ec18f2b6b159c382e0ad53cf89c_InstallFirefox.ps1
VertigoRay_6091281_raw_f28fc4a9ad127ec18f2b6b159c382e0ad53cf89c_InstallFirefox.ps1
Param ( [parameter( Position = 0, Mandatory = $true, HelpMessage = 'This is the version number, such as "22.0". Valid version numbers can be found here: http://mzl.la/1c9hPmo' )] [string] $version, [parameter( Position = 1, Mandatory = $false, HelpMessage = 'This is language string, such as "en-US". Valid language strings can be found here: http://mzl.la/1c9n7OJ' )] [string] $language ) Write-Debug "VERS: $version" Write-Debug "TEMP: $env:Temp" $ini_file = @" [Install] QuickLaunchShortcut=false DesktopShortcut=false MaintenanceService=false "@ Write-Debug "INI: $ini_file" Write-Debug "LANG: $language" if (-not $language) { Write-Debug "Language NOT supplied ..." $lang_pattern = '^[^(]+\(([^)]+)\)' try { Write-Debug "Detecting Language x64 ..." $language = [regex]::Replace((Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Mozilla\Mozilla Firefox" -ErrorAction Stop).CurrentVersion, $lang_pattern, '$1', 'IgnoreCase') } catch { try { Write-Debug "Detecting Language x86 ..." $language = [regex]::Replace((Get-ItemProperty "HKLM:\SOFTWARE\Mozilla\Mozilla Firefox" -ErrorAction Stop).CurrentVersion, $lang_pattern, '$1', 'IgnoreCase') } catch { Write-Debug "Language NOT detectable, using default ..." $language = "en-US" } } } Write-Debug "LANG: $language" $url = "http://ftp.mozilla.org/pub/mozilla.org/firefox/releases/${version}/win32/${language}/Firefox Setup ${version}.exe" Write-Debug "URL: $url" $webclient = New-Object System.Net.WebClient Write-Debug "Downloading ..." try { $webclient.DownloadFile($url, "${env:Temp}\Firefox Setup ${version}.exe") } catch { Throw("Download of Firefox setup exe file failed. Check your version number and try again.`nValid version numbers can be found here: http://mzl.la/1c9hPmo`n ") } Write-Debug "Creating .ini file ..." $ini_file | Out-File -Encoding ASCII -FilePath "${env:Temp}\FirefoxSetup${version}.ini" Write-Debug "Installing ..." $proc = Start-Process "${env:Temp}\Firefox Setup ${version}.exe" -ArgumentList "/INI=""${env:Temp}\FirefoxSetup${version}.ini""" -Wait -PassThru Write-Debug ("Done:{0}!" -f $proc.ExitCode) Exit $proc.ExitCode
PowerShellCorpus/GithubGist/adsmit14_8072908_raw_3522c11956bf2e9946c70ea1d72ef61f5219210c_AddFtpUser.ps1
adsmit14_8072908_raw_3522c11956bf2e9946c70ea1d72ef61f5219210c_AddFtpUser.ps1
<# Name: AddFtpUser.ps1 Author: Adam Smith Date: 12/21/2013 #> ############################################################################### # FTP Server Specific Settings ############################################################################### $ftpUsersRoot = "C:\inetpub\ftproot\" $ftpSiteName = "Default" ############################################################################### # FTP User Information ############################################################################### $userName = Read-Host "Enter the username" $password = Read-Host "Enter the password" $retryPassword = Read-Host "Re-enter the password" if ($password -ne $retryPassword) { "`nPasswords are not the same. Try again." Write-Host "Press any key to continue ..." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Exit } ############################################################################### # Create FTP User Directory ############################################################################### $ftpUserPath = Join-Path $ftpUsersRoot $userName New-Item -ItemType directory -Path $ftpUserPath | out-null ############################################################################### # Add IIS Manager User ############################################################################### Add-Type -Path 'C:\Windows\System32\inetsrv\Microsoft.Web.Management.dll' [Microsoft.Web.Management.Server.ManagementAuthentication]::CreateUser($userName, $password) | out-null [Microsoft.Web.Management.Server.ManagementAuthorization]::Grant($userName, $ftpSiteName, $FALSE)| out-null ############################################################################### # Add User to Authorization Rules ############################################################################### Import-Module WebAdministration Add-WebConfiguration -Filter /System.FtpServer/Security/Authorization -Value (@{AccessType="Allow"; Users="$userName"; Permissions="Read, Write"}) -PSPath IIS: -Location $ftpSiteName | out-null "`nUser $userName was created successfully." Write-Host "`nPress any key to continue ..." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
PowerShellCorpus/GithubGist/jpoul_5dfb4abfe7f68a96e4d5_raw_cde4887ccdc8fd8c11791bc98ee4889c2ae513f6_boxstarter.base.ps1
jpoul_5dfb4abfe7f68a96e4d5_raw_cde4887ccdc8fd8c11791bc98ee4889c2ae513f6_boxstarter.base.ps1
Set-ExecutionPolicy -ExecutionPolicy Bypass -Confirm:$false Disable-InternetExplorerESC Enable-RemoteDesktop Set-TaskbarOptions -UnLock #Set-CornerNavigationOptions -EnableUsePowerShellOnWinX # Set-StartScreenOptions -EnableBootToDesktop -EnableListDesktopAppsFirst -EnableDesktopBackgroundOnStart -EnableListDesktopAppsFirst -EnableShowStartOnActiveScreen Set-WindowsExplorerOptions -EnableShowFileExtensions -EnableShowHiddenFilesFoldersDrives -EnableShowProtectedOSFiles -EnableShowFullPathInTitleBar cinst notepadplusplus.install cinst 7zip.install cinst visualsubst cinst VirtualCloneDrive cinst freefilesync cinst ChocolateyGUI cinst adobeair cinst adobereader cinst dropbox cinst googledrive cinst fiddler cinst Recuva cinst LinkShellExtension cinst putty.install cinst treesizefree cinst ccleaner cinst filezilla cinst IcoFx cinst ccenhancer cinst vcredist2005 cinst vcredist2008 cinst vcredist2010 # cinst PowerGUI cinst pscx cinst git.install cinst poshgit cinst TeraCopy # cinst powertab # cinst Listary cinst GoogleChrome cinst javaruntime cinst WindowsLiveWriter cinst Silverlight cinst webpi cinst webpicmd cinst skype cinst teamviewer cinst flashplayerplugin cinst lastpass cinst NugetPackageExplorer cinst NugetPackageManager # cinst mediamonkey cinst calibre # cinst yumi cinst spotify Install-WindowsUpdate -AcceptEula
PowerShellCorpus/GithubGist/4E71_7453589_raw_acdd8ea9f90e93cb1159af58ecd4aa3f483058e9_LoC.ps1
4E71_7453589_raw_acdd8ea9f90e93cb1159af58ecd4aa3f483058e9_LoC.ps1
# Add/Remove types as needed ls * -recurse -include *.aspx, *.ascx, *.cs, *.ps1, *js | Get-Content | Measure-Object -Line
PowerShellCorpus/GithubGist/yan-shuai_d4e0e8c1651040f0cb3a_raw_2fe6444c211cfd23277712c075f2e71923fbbb65_MyPSSnippets.ps1
yan-shuai_d4e0e8c1651040f0cb3a_raw_2fe6444c211cfd23277712c075f2e71923fbbb65_MyPSSnippets.ps1
# Set a static IP and default gateway Get-NetAdapter -Name Ethernet | New-NetIPAddress -AddressFamily IPv4 -IPAddress 10.0.1.100 -PrefixLength 24 -Type Unicast ` -DefaultGateway 10.0.1.1 # Configure DNS server address Get-NetAdapter -Name Ethernet | Set-DnsClientServerAddress -InterfaceAlias Ethernet -ServerAddresses 10.0.1.10 # Join computer to a domain Add-Computer -DomainName "psa.local" -Credential "psa\adminaccount" # Preferences: # 1 --- http://thepracticalsysadmin.com/powershell/
PowerShellCorpus/GithubGist/janikvonrotz_8653473_raw_8e385204007f1b57bde43960e1d1ce1725f64b71_Sync-ServiceMailboxAccessGroups.ps1
janikvonrotz_8653473_raw_8e385204007f1b57bde43960e1d1ce1725f64b71_Sync-ServiceMailboxAccessGroups.ps1
<# $Metadata = @{ Title = "Synchronize Service Mailbox Access Groups" Filename = "Sync-ServiceMailboxAccessGroups.ps1" Description = "" Tags = "powershell, activedirectory, exchange, synchronization, access, mailbox, groups, permissions" Project = "" Author = "Janik von Rotz" AuthorContact = "http://janikvonrotz.ch" CreateDate = "2014-01-27" LastEditDate = "2014-01-27" Url = "" Version = "0.0.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. '@ } #> $Config = @{ OU = "OU=Mailbox,OU=Exchange,OU=Services,OU=vblusers2,DC=vbl,DC=ch" ADGroupFilter = @{ NamePrefix = "EX_" NameInfix = "" NameSuffix = "" } ADGroup = @{ NamePrefix = "EX_" PermissionSeperator = "#" } SyncMailboxUsersWith = "F_Service Mailbox" ADGroupMailboxReferenceAttribute = "extensionAttribute1" MailBoxFilter = @{ RecipientTypeDetails = "UserMailbox","EquipmentMailbox","RoomMailbox" ADGroupsAndUsers = "F_Mitarbeiter","F_Archivierte Benutzer" ExcludeDisplayName = "FederatedEmail.4c1f4d8b-8179-4148-93bf-00a95fa1e042" } } | %{New-Object PSObject -Property $_} # required modules Import-Module ActiveDirectory # Connect Exchange Server $ExchangeServer = (Get-RemoteConnection ex1).Name if(-not (Get-PSSession | where{$_.ComputerName -eq $ExchangeServer})){ $PSSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$ExchangeServer/PowerShell/" -Authentication Kerberos Import-PSSession $PSSession } # get domain name $Domain = "$(((Get-ADDomain).Name).toupper())\" # get ad user objects $Config.MailBoxFilter.ADGroupsAndUsers = $Config.MailBoxFilter.ADGroupsAndUsers | %{ Get-ADObject -Filter {(Name -eq $_) -or (ObjectGUID -eq $_)} | %{ if($_.ObjectClass -eq "user"){$_.DistinguishedName }elseif($_.ObjectClass -eq "group"){ Get-ADGroupMember $_.DistinguishedName -Recursive} } | Get-ADUser -Properties Mail } # create mail list to filter mailboxes $Config.MailboxFilter.AllowedMails = $Config.MailBoxFilter.ADGroupsAndUsers | %{"$($_.Mail)"} # create SamAccountName list to filter mailbox permissions $Config.ADGroupFilter.AllowedUsers = $Config.MailboxFilter.ADGroupsAndUsers | %{"$($Domain + $_.SamAccountName)"} # get exisiting mailbox permission ad groups $ADGroups = Get-ADGroup -Filter * -SearchBase $Config.OU -Properties $Config.ADGroupMailboxReferenceAttribute | where{$_.Name.StartsWith($Config.ADGroupFilter.NamePrefix) -and $_.Name.Contains($Config.ADGroupFilter.NameInfix) -and $_.Name.EndsWith($Config.ADGroupFilter.NameSuffix)} # sync mailbox access groups for each mailbox $Mailboxes = Get-Mailbox | where{$Config.MailBoxFilter.RecipientTypeDetails -contains $_.RecipientTypeDetails -and $Config.MailboxFilter.AllowedMails -notcontains $_.PrimarySmtpAddress.tolower() -and $Config.MailBoxFilter.ExcludeDisplayName -notcontains $_.DisplayName} $MailboxData = $Mailboxes | %{ # set variables $ADPermissionGroups = @() $Mailbox = $_ Write-Host "Parsing permissions on mailbox: $($_.Alias)" # get existing permission groups $ADPermissionGroups += $ADGroups | where{(iex "`$_.$($Config.ADGroupMailboxReferenceAttribute)") -eq $Mailbox.Guid} $ADExistingPermissionGroupTypes = $ADPermissionGroups| where{$_} | %{$_.Name.split("#")[1]} # get existing and allowed mailbox permissions $MailboxPermissions = $Mailbox | Get-MailboxPermission | where{$Config.ADGroupFilter.AllowedUsers -contains $_.User} # create an ad group foreach permissiontype that is required $NewADPermissionGroupTypes = $MailboxPermissions | %{"$($_.AccessRights)".split(", ") | where{$_} | %{$_} | %{$_ | where{$ADExistingPermissionGroupTypes -notcontains $_}}} $ADPermissionGroups += $NewADPermissionGroupTypes | Group | %{ # create ad group name foreach permission type $Name = $config.ADGroup.NamePrefix + $Mailbox.Displayname + $Config.ADGroup.PermissionSeperator + $_.Name Write-PPEventLog -Message "Add service mailbox access group: $Name" -Source "Synchronize Service Mailbox Access Groups" -WriteMessage New-ADGroup -Name $Name -SamAccountName $Name -GroupCategory Security -GroupScope Global -DisplayName $Name -Path $Config.OU -Description "Exchange Access Group for: $($Mailbox.Displayname)" Get-ADGroup $Name } | %{ # set the reference from the adgroup to the mailbox iex "`$_.$($Config.ADGroupMailboxReferenceAttribute) = `"$($Mailbox.Guid)`"" Set-ADGroup -Instance $_ $ADGroup = $_ # add existing members to the permission group $MailboxPermissions | where{$_.AccessRights -match $ADGroup.Name.split("#")[1]} | %{ Add-ADGroupMember -Identity $ADGroup -Members ($_.User -replace "$Domain\","") } # output ad permission groups $_ } # check members foreach permission group $ADPermissionGroups | where{$_} | %{ # get permission type $Permission = $_.Name.split("#")[1] # get existing ad user groups $ADPermissionGroupUsers = $_ | Get-ADGroupMember -Recursive | select @{L="User";E={$($Domain + $_.SamAccountName)}} $MailboxUsers = $MailboxPermissions | where{$_.AccessRights -match $Permission} | select user # compare these groups and update members if($ADPermissionGroupUsers){ $PermissionDiff = Compare-Object -ReferenceObject $ADPermissionGroupUsers -DifferenceObject $MailboxUsers -Property User # add member $PermissionDiff | where{$_.SideIndicator -eq "<="} | %{ Write-PPEventLog -Message "Add mailbox permission: $Permission for user: $($_.User) on mailbox: $($Mailbox.Alias)" -Source "Synchronize Service Mailbox Access Groups" -WriteMessage Add-MailboxPermission -Identity $Mailbox.Alias -User $_.User -AccessRights $Permission } # remove member $PermissionDiff | where{$_.SideIndicator -eq "=>"} | %{ Write-PPEventLog -Message "Remove mailbox permission: $Permission for user: $($_.User) on mailbox: $($Mailbox.Alias)" -Source "Synchronize Service Mailbox Access Groups" -WriteMessage Remove-MailboxPermission -Identity $Mailbox.Alias -User $_.User -AccessRights $Permission -Confirm:$false } # output ad permission group @{ADGroup = $_} } } # output mailbox identity @{Identity = $Mailbox.UserPrincipalName | %{Get-ADUser -Filter{UserPrincipalName -eq $_}}} } $RequiredADGroups = $MailboxData | %{$_.ADGroup} $ADGroups | where{$RequiredADGroups -notcontains $_} | %{ Write-PPEventLog -Message "Remove service mailbox access group: $Name" -Source "Synchronize Service Mailbox Access Groups" -WriteMessage Remove-ADGroup -Identity $_ -Confirm:$false } $Member = $($MailboxData | %{$_.Identity}) | where{$_} Sync-ADGroupMember -ADGroup $Config.SyncMailboxUsersWith -Member $Member -LogScriptBlock{Write-PPEventLog $Message -Source "Synchronize Service Mailbox Access Groups" -WriteMessage} Remove-PSSession $PSSession Write-PPErrorEventLog -Source "Synchronize Service Mailbox Access Groups" -ClearErrorVariable
PowerShellCorpus/GithubGist/sheeeng_368fd7ef332bfde409d8_raw_9dedc6d342934f2945152d0ca2319e0e8f817579_gitpull.ps1
sheeeng_368fd7ef332bfde409d8_raw_9dedc6d342934f2945152d0ca2319e0e8f817579_gitpull.ps1
$dirs = Get-ChildItem -Path .\* | ?{ $_.PSIsContainer } $currentDir = Get-Location # dir env:ProgramFiles`(x86`) # dir "env:ProgramFiles(x86)" # ${Env:ProgramFiles(x86)} # [Environment]::GetEnvironmentVariable("ProgramFiles(x86)") # & ${Env:WinDir}\notepad.exe # Invoke-Item ${Env:WinDir}\notepad.exe foreach ($dir in $dirs) { Set-Location $dir.FullName Write-Host $dir.FullName &"${Env:ProgramFiles(x86)}\Git\bin\git.exe" pull origin &"${Env:ProgramFiles(x86)}\Git\bin\git.exe" fetch --all &"${Env:ProgramFiles(x86)}\Git\bin\git.exe" reset --hard origin } Set-Location $currentDir.Path
PowerShellCorpus/GithubGist/williamjacksn_3708009_raw_58d91f0173a7b8481200ac5943d8243e7e47fb5b_gpo-backup-script.ps1
williamjacksn_3708009_raw_58d91f0173a7b8481200ac5943d8243e7e47fb5b_gpo-backup-script.ps1
Import-Module GroupPolicy Get-GPO -All | Where-Object {$_.DisplayName -like "ops*"} | Backup-GPO -Path "\\server\share" -Comment "Backup Comment"
PowerShellCorpus/GithubGist/grahammcallister_a4752722bba535b9e0b7_raw_b27fb722652b7aee2813b37f2ffb855c3912aa0b_Setup-BuildServer.ps1
grahammcallister_a4752722bba535b9e0b7_raw_b27fb722652b7aee2813b37f2ffb855c3912aa0b_Setup-BuildServer.ps1
try { cinst javaruntime #cinst Gmac.TeamCity Set-ExplorerOptions -showHiddenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions Install-WindowsUpdate -AcceptEula Write-ChocolateySuccess 'Setup-BuildServer' } catch { Write-ChocolateyFailure 'Setup-BuildServer' $($_.Exception.Message) throw }
PowerShellCorpus/GithubGist/crancker_5491509_raw_49a1321638b86298f8659b3803892809b0b52d26_sccm_check.ps1
crancker_5491509_raw_49a1321638b86298f8659b3803892809b0b52d26_sccm_check.ps1
$sitecode = "yoursitecode" $server = "your server" Get-WmiObject -Namespace root\sms\Site_$sitecode -query "Select * from SMS_ComponentSummarizer where Status <> 0 AND TallyInterval = '0281128000100008'" -ComputerName $server |select Status,State,Sitecode,Componentname,Errors|format-table -autosize
PowerShellCorpus/GithubGist/alvinsim_9699481_raw_14faefadce36b02003921a80646328ea6c91cbe2_win_autoinstall_chocolatey.ps1
alvinsim_9699481_raw_14faefadce36b02003921a80646328ea6c91cbe2_win_autoinstall_chocolatey.ps1
######################### # Autoinstall script using chocolatey ######################### # Note: Net 4.0 must be installed prior to running this script # #Modify this line to change packages $items = @("ccleaner", "microsoftsecurityessentials", "7zip", "adobereader", "javaruntime", "libreoffice", "googlechrome", "firefox", "vim", "teracopy", "winscp", "wget", "putty", "emacs", "hg") ################# # Create packages.config based on passed arguments ################# $xml = '<?xml version="1.0" encoding="utf-8"?>'+ "`n" +'<packages>' + "`n" foreach ($item in $items) { $xml += "`t" +'<package id="' + $item + '"/>' + "`n" } $xml += '</packages>' $file = ([system.environment]::getenvironmentvariable("userprofile") + "\packages.config") $xml | out-File $file #### # Install chocolatey #### iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) && SET PATH=%PATH%;%systemdrive%\chocolatey\bin ###### # Install packages with cinst ###### cinst $file ######## # Delete packages.config Remove-Item $file
PowerShellCorpus/GithubGist/AmrEldib_4eaa69ac18f22a30d78b_raw_e1b08242d607211dd97613e4ed0035dc568d449d_GetDate.ps1
AmrEldib_4eaa69ac18f22a30d78b_raw_e1b08242d607211dd97613e4ed0035dc568d449d_GetDate.ps1
Get-Date -format "yyyy-MM-dd HH-mm-ss"
PowerShellCorpus/GithubGist/zahhak_11145046_raw_1e0192cf92b955baa9c63880892f24d1e09f89fe_gistfile1.ps1
zahhak_11145046_raw_1e0192cf92b955baa9c63880892f24d1e09f89fe_gistfile1.ps1
# Windows AMIs don't have WinRM enabled by default -- this script will enable WinRM # AND install 7-zip, curl and .NET 4 if its missing. # Then use the EC2 tools to create a new AMI from the result, and you have a system # that will execute user-data as a PowerShell script after the instance fires up! # This has been tested on Windows 2008 SP2 64bits AMIs provided by Amazon # # Inject this as user-data of a Windows 2008 AMI, like this (edit the adminPassword to your needs): # # <powershell> # Set-ExecutionPolicy Unrestricted # icm $executioncontext.InvokeCommand.NewScriptBlock((New-Object Net.WebClient).DownloadString('https://gist.github.com/masterzen/6714787/raw')) -ArgumentList "adminPassword" # </powershell> # Start-Transcript -Path 'c:\bootstrap-transcript.txt' -Force Set-StrictMode -Version Latest Set-ExecutionPolicy Unrestricted $log = 'c:\Bootstrap.txt' $sysNative = [IO.Path]::Combine($env:windir, "sysnative") #http://blogs.msdn.com/b/david.wang/archive/2006/03/26/howto-detect-process-bitness.aspx $Is32Bit = (($Env:PROCESSOR_ARCHITECTURE -eq 'x86') -and ($Env:PROCESSOR_ARCHITEW6432 -eq $null)) Add-Content $log -value "Is 32-bit [$Is32Bit]" #http://msdn.microsoft.com/en-us/library/ms724358.aspx $coreEditions = @(0x0c,0x27,0x0e,0x29,0x2a,0x0d,0x28,0x1d) $IsCore = $coreEditions -contains (Get-WmiObject -Query "Select OperatingSystemSKU from Win32_OperatingSystem" | Select -ExpandProperty OperatingSystemSKU) Add-Content $log -value "Is Core [$IsCore]" # move to home, PS is incredibly complex :) cd $Env:USERPROFILE Set-Location -Path $Env:USERPROFILE [Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath $client = new-object System.Net.WebClient #7zip $7zUri = if ($Is32Bit) { 'http://sourceforge.net/projects/sevenzip/files/7-Zip/9.22/7z922.msi/download' } ` else { 'http://sourceforge.net/projects/sevenzip/files/7-Zip/9.22/7z922-x64.msi/download' } $client.DownloadFile( $7zUri, '7z922.msi') Start-Process -FilePath "msiexec.exe" -ArgumentList '/i 7z922.msi /norestart /q INSTALLDIR="c:\program files\7-zip"' -Wait SetX Path "${Env:Path};C:\Program Files\7-zip" /m $Env:Path += ';C:\Program Files\7-Zip' del 7z922.msi Add-Content $log -value "Installed 7-zip from $7zUri and updated path" #vc 2010 redstributable $vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/5/B/C/5BC5DBB3-652D-4DCE-B14A-475AB85EEF6E/vcredist_x86.exe'} ` else { 'http://download.microsoft.com/download/3/2/2/3224B87F-CFA0-4E70-BDA3-3DE650EFEBA5/vcredist_x64.exe' } $client.DownloadFile( $vcredist, 'vcredist.exe') Start-Process -FilePath 'C:\Users\Administrator\vcredist.exe' -ArgumentList '/norestart /q' -Wait del vcredist.exe Add-Content $log -value "Installed VC++ 2010 Redistributable from $vcredist and updated path" #vc 2008 redstributable $vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/d/d/9/dd9a82d0-52ef-40db-8dab-95376989c03/vcredist_x86.exe'} ` else { 'http://download.microsoft.com/download/d/2/4/d242c3fb-da5a-4542-ad66-f9661d0a8d19/vcredist_x64.exe' } $client.DownloadFile( $vcredist, 'vcredist.exe') Start-Process -FilePath 'C:\Users\Administrator\vcredist.exe' -ArgumentList '/norestart /q' -Wait del vcredist.exe Add-Content $log -value "Installed VC++ 2008 Redistributable from $vcredist and updated path" #curl $curlUri = if ($Is32Bit) { 'http://www.paehl.com/open_source/?download=curl_724_0_ssl.zip' } ` else { 'http://curl.haxx.se/download/curl-7.23.1-win64-ssl-sspi.zip' } $client.DownloadFile( $curlUri, 'curl.zip') &7z e curl.zip `-o`"c:\program files\curl`" if ($Is32Bit) { $client.DownloadFile( 'http://www.paehl.com/open_source/?download=libssl.zip', 'libssl.zip') &7z e libssl.zip `-o`"c:\program files\curl`" del libssl.zip } SetX Path "${Env:Path};C:\Program Files\Curl" /m $Env:Path += ';C:\Program Files\Curl' del curl.zip Add-Content $log -value "Installed Curl from $curlUri and updated path" #vim curl -# -G -k -L ftp://ftp.vim.org/pub/vim/pc/vim73_46rt.zip -o vim73_46rt.zip 2>&1 > "$log" curl -# -G -k -L ftp://ftp.vim.org/pub/vim/pc/vim73_46w32.zip -o vim73_46w32.zip 2>&1 > "$log" Get-ChildItem -Filter vim73*.zip | % { &7z x `"$($_.FullName)`"; del $_.FullName; } SetX Path "${Env:Path};C:\Program Files\Vim" /m $Env:Path += ';C:\Program Files\Vim' Move-Item .\vim\vim73 -Destination "${Env:ProgramFiles}\Vim" Add-Content $log -value "Installed Vim text editor and updated path" #chocolatey - standard one line installer doesn't work on Core b/c Shell.Application can't unzip if (-not $IsCore) { Invoke-Expression ((new-object net.webclient).DownloadString('http://bit.ly/psChocInstall')) } else { #[Environment]::SetEnvironmentVariable('ChocolateyInstall', 'c:\nuget', [System.EnvironmentVariableTarget]::User) #if (![System.IO.Directory]::Exists('c:\nuget')) {[System.IO.Directory]::CreateDirectory('c:\nuget')} $tempDir = Join-Path $env:TEMP "chocInstall" if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)} $file = Join-Path $tempDir "chocolatey.zip" $client.DownloadFile("http://chocolatey.org/api/v1/package/chocolatey", $file) &7z x $file `-o`"$tempDir`" Add-Content $log -value 'Extracted Chocolatey' $chocInstallPS1 = Join-Path (Join-Path $tempDir 'tools') 'chocolateyInstall.ps1' & $chocInstallPS1 Add-Content $log -value 'Installed Chocolatey / Verifying Paths' } Add-Content $log -value "Installed Chocolatey" # install puppet #https://downloads.puppetlabs.com/windows/puppet-3.2.4.msi curl -# -G -k -L https://downloads.puppetlabs.com/windows/puppet-3.2.4.msi -o puppet-3.2.4.msi 2>&1 > "$log" Start-Process -FilePath "msiexec.exe" -ArgumentList '/qn /passive /i puppet-3.2.4.msi /norestart' -Wait SetX Path "${Env:Path};C:\Program Files\Puppet Labs\Puppet\bin" /m &sc.exe config puppet start= demand Add-Content $log -value "Installed Puppet" #wait a bit, it's windows after all Start-Sleep -m 10000 #Write-Host "Press any key to reboot and finish image configuration" #[void]$host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') Restart-Computer
PowerShellCorpus/GithubGist/mrxinu_4142396_raw_274b2f37e89c3b94c62d8f6ef0e9e8130953e214_fix-phone.ps1
mrxinu_4142396_raw_274b2f37e89c3b94c62d8f6ef0e9e8130953e214_fix-phone.ps1
# # Script: fix-phone.ps1 # # Purpose: Reformat phone numbers in .txt files from XXX-XXX-XXXX to # (XXX) XXX-XXXX. # # Written by Steven Klassen, [email protected] # ############################################################################# # define the pattern $rxPhone = New-Object System.Text.RegularExpressions.Regex "(?<Prefix>\d+)-(?<Number>\d+-\d+)" # run through the txt files Get-Item "*.txt" | ForEach-Object { # read in the contents of the original file $text = [System.IO.File]::ReadAllText($_.FullName) # do the replacement $text = $rxPhone.Replace($text, "(`${Prefix}) `${Number}") # write it back out to a new file $outputFile = [System.IO.File]::CreateText($_.BaseName + ".fixed.txt") $outputFile.Write($text) $outputFile.Close() }
PowerShellCorpus/GithubGist/daveshah_7789090_raw_1676e7799eeca7fb474e31adebff83966d26ab15_restart.ps1
daveshah_7789090_raw_1676e7799eeca7fb474e31adebff83966d26ab15_restart.ps1
# May require # Set-ExecutionPolicy Remote # if Get-ExecutionPolicy returns "Restricted" Set-Service W3SVC -StartupType Automatic Start-Service W3SVC iisreset
PowerShellCorpus/GithubGist/belotn_6868028_raw_91bbbe1c0a9abe3df7c2313b9685d34c32cc9abd_disabled-unusedgpoparts1L.ps1
belotn_6868028_raw_91bbbe1c0a9abe3df7c2313b9685d34c32cc9abd_disabled-unusedgpoparts1L.ps1
Get-ADOrganizationalUnit -Filter 'OU -like "*Citrix*"' -SearchBase 'dc=fabrikam,dc=com' -Properties * |% { $_.gpLink -split ']' } |? { $_ -match '[0,2]$'} |% {(($_ -replace '\[','').split(';')[0]) -replace 'LDAP://',''} |% { get-adobject $_ -properties * } |sort -Unique DisplayName |% {if( $_.Flags -ne 3 ){if([bool]( gci "$($_.gPCFileSysPath)\User") -eq $false){if([bool](gci "$($_.gPCFileSysPath)\Machine") -eq $false){(get-gpo -Name $_.DisplayName).GpoStatus = "AllSettingsDisabled" }else{(get-gpo -Name $_.DisplayName).GpoStatus = "UserSettingsDisabled"}}else {if([bool](gci "$($_.gPCFileSysPath)\Machine") -eq $false){(get-gpo -Name $_.DisplayName).GpoStatus = "ComputerSettingsDisabled"}ELSE{}}}} }
PowerShellCorpus/GithubGist/vpag_1092a507f389e99fc669_raw_323e5548781a920f76925c4d9fcdcabe05b17ec3_gistfile1.ps1
vpag_1092a507f389e99fc669_raw_323e5548781a920f76925c4d9fcdcabe05b17ec3_gistfile1.ps1
# get help Get-Help <subj> -Online Get-Help <subj> -ShowWindow # grep -f GetContent -Wait # gc # alias # WMI Get-WmiObject <class> | Get-Member Get-WmiObject <class> | Select-Object * Get-WmiObject -Namespace "root/default" -List (Get-WmiObject -Class Win32_Service -Filter "name='WinRM'").StopService() Get-WmiObject <class> -ComputerName <hostA>, <hostB> -Credential administrator Get-WMIObject -Query "Associators of {Win32_Service.Name='Winmgmt'} Where ResultRole=Antecedent" | Select-Object * # gwmi # alias # select/filter Get-Process | Where-Object {$_.handles -ge 200} Get-Content C:\Scripts\Test.txt | Select-String "\(\d{3}\)-\d{3}-\d{4}"
PowerShellCorpus/GithubGist/rikkit_1c994ef5a8f549216b3d_raw_dd1e2971d4023326fb0aabeea239f0c27cd1ccf3_boxstarter.ps1
rikkit_1c994ef5a8f549216b3d_raw_dd1e2971d4023326fb0aabeea239f0c27cd1ccf3_boxstarter.ps1
##### # START http://boxstarter.org/package/url?https://gist.github.com/rikkit/1c994ef5a8f549216b3d ##### # update windows Install-WindowsUpdate -AcceptEula # windows features cinst Microsoft-Hyper-V-All -source windowsFeatures # system config Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions Update-ExecutionPolicy RemoteSigned Enable-RemoteDesktop # this will always be step #1 cinst Firefox # fun stuff cinst lastfmscrobbler cinst spotify cinst vlc cinst mumble cinst InkScape cinst audacity cinst blender cinst steam cinst battle.net cinst origin cinst minecraft cinst openttd # utilities cinst adblockplusie cinst colorcop cinst f.lux cinst winscp cinst winrar cinst handbrake cinst inssider cinst windirstat cinst speedfan cinst mp3tag cinst picard cinst ProduKey cinst uTorrent ## cinst ps3mediaserver # dev tools cinst kitty.portable cinst git.install cinst githubforwindows cinst TortoiseGit cinst beyondcompare cinst fiddler4 cinst filezilla ## cinst Xming # ides cinst phpstorm cinst sublimetext3 cinst SublimeText3.PackageControl cinst notepadplusplus.install # dev runtimes cinst nodejs.install cinst npm cinst mongodb ## cinst processing2 ## cinst xampp.app ## cinst mysql ## cinst postgresql # vs cinst VisualStudio2013Ultimate cinst visualstudio2013-update1 cinst visualstudio2013-update2 cinst visualstudio2013-update3 cinst resharper # how do i install these? # zune + zuseme # office # photoshop # illustrator # xamlspy # bluestacks