full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/charlieoleary_1d986491b88420dcd5ca_raw_5bbb8c29151deb81dcdd7bda816aad7bd7581f72_dropTranscode.ps1
charlieoleary_1d986491b88420dcd5ca_raw_5bbb8c29151deb81dcdd7bda816aad7bd7581f72_dropTranscode.ps1
# Clear the screen Clear-Host # Number of Seconds $secondsOlder = 15 # Time Between Checks $sleepTime = 5 $ffmbcPath = "c:\bin\Debug\ffmbc.exe" # Path to Watch $srcPath = Read-Host "Full path of directory to be watched: " # Path to Drop $dstPath = Read-Host "Location where transcoded files will be placed: " # Path to Complete $cmpPath = Read-Host "Location where you would like the source file to be placed: " # Create directories if they do not exist... if (!(Test-Path -path $srcPath)) { New-Item $srcPath -Type Directory } if (!(Test-Path -path $dstPath)) { New-Item $dstPath -Type Directory } if (!(Test-Path -path $cmpPath)) { New-Item $cmpPath -Type Directory } while ($x -ne 1) { # Today $today = Get-Date foreach ($file in dir $srcPath) { if ($file.FullName -ne $cmpPath -and $file.FullName -ne $dstPath) { Write-Host ("Looking at " + $file.FullName + " in " + $srcPath + "...") if ($file.LastWriteTime -le $today.AddSeconds(-$secondsOlder)) { Write-Host ($file.Name + " is older than " + $secondsOlder + " minute(s)"); $ffmbcCommand = ("$ffmbcPath -y -copy_streams_metadata -i `"" + $file.FullName + "`" -timecode `"00:00:00:00`" -r 29.97 -b 145000.00k -vcodec dnxhd -threads 4 -pix_fmt yuv422p -tff -flags +ilme+ildct -acodec pcm_s32le -f mov `"" + $dstPath +"\Transcoded_"+ $file.Name + "`"") cmd /c $ffmbcCommand if (!(Test-Path -path $cmpPath)) { New-Item $dstPath -Type Directory } try { Write-Host ("Transcode complete! Moving file " + $file.Name + " to completed location.") Move-Item ($srcPath +"\"+ $file.Name) $cmpPath; } catch { Write-Host ("Error moving " + $file.Name) continue; } } else { Write-host ($file.Name + " is less than " + $secondsOlder + " second(s) old.") } } } Write-Host ("Sleeping for " + $sleepTime + " seconds...") Start-Sleep -s $sleepTime }
PowerShellCorpus/GithubGist/briped_dc9e8c6f30caf703688e_raw_c618267b086c357ca8ce12561277ebcafae59b7c_Merge-ADGroupMembers.ps1
briped_dc9e8c6f30caf703688e_raw_c618267b086c357ca8ce12561277ebcafae59b7c_Merge-ADGroupMembers.ps1
Param( [parameter(Mandatory=$true, HelpMessage="Enter one or more AD groups to merge/copy from.")] [string[]] $SourceGroups, [parameter(Mandatory=$true, HelpMessage="Enter AD group to merge/copy to.")] [string] $TargetGroup, [parameter(Mandatory=$false, HelpMessage="Enter one or more AD groups with users to exclude from TargetGroup.")] [string[]] $ExcludeGroup ) Import-Module -Name ActiveDirectory -ErrorAction SilentlyContinue If (!(Get-ADGroup -Identity $TargetGroup | Out-Null)) { Write-Warning -Message "The AD Group '$($TargetGroup)' does not exist. Exiting script." Exit } ForEach ($Source in $SourceGroups) { Get-ADGroupMember -Recursive -Identity $Source | Get-ADUser | Where-Object { $_.Enabled -eq $true } | ForEach-Object { Add-ADGroupMember -Identity $TargetGroup -Members $_.SamAccountName } } ForEach ($Exclude in $ExcludeGroup) { If (!(Get-ADGroup -Identity $Exclude | Out-Null)) { Write-Warning -Message "The AD Group '$($Exclude)' does not exist. Skipping." Continue } Get-ADGroupMember -Recursive -Identity $Exclude | ForEach-Object { Remove-ADGroupMember -Identity $TargetGroup -Members $_.SamAccountName -Confirm:$false } }
PowerShellCorpus/GithubGist/tamagokun_3004344_raw_8712e4cd917f8e31a59c7cdb83aa1bb1ed50ea30_sync.ps1
tamagokun_3004344_raw_8712e4cd917f8e31a59c7cdb83aa1bb1ed50ea30_sync.ps1
function sync_dir { Param($src,$dest,[switch]$whatif) # Make sure destination exists if(!(test-path -literalPath $dest)) { Write-Host "Creating destination directory." New-Item $dest -type Directory -force | out-Null } $regex_src_path = $src -replace "\\","\\" -replace "\:","\:" $regex_dest_path = $dest -replace "\\","\\" -replace "\:","\:" $src_items = Get-ChildItem $src -Recurse $dest_items = Get-ChildItem $dest -Recurse foreach($item in $src_items) { $name = $item.Name $compare_item = $item.Fullname -replace $regex_src_path,$dest if($compare_item -ne "") { if(test-path -literalPath $compare_item) { if(!$item.PSIsContainer) { if( $item.LastWriteTime -gt (Get-Item -literalPath $compare_item).LastWriteTime ) { Write-Host "Source location has a newer version $name" Copy-Item -literalPath $item.Fullname -destination $compare_item -force -whatif:$whatif }else { #Write-Host "Skipping $name" } } }else { if($item.PSIsContainer) { Write-Host "Copying $name" New-Item $compare_item -type Directory -whatif:$whatif | out-Null }else { Write-Host "Copying new file $name" Copy-Item -literalPath $item.Fullname -destination $compare_item -force -whatif:$whatif } } } } # Remove old destination files foreach($item in $dest_items) { $name = $item.Name $compare_item = $item.Fullname -replace $regex_dest_path,$src if($compare_item -ne "") { if(!(test-path -literalPath $compare_item)) { Write-Host "$name does not exist in source, cleaning up." Remove-Item -literalPath $item.Fullname -whatif:$whatif } } } } sync_dir "c:\inetpub\wwwroot\acgme.mslideas.com\" "c:\inetpub\wwwroot\just_a_test\"
PowerShellCorpus/GithubGist/ashwin_3269777_raw_7cf54d4d3eeac5135f0c027e25a75a4db3f0b8cb_gistfile1.ps1
ashwin_3269777_raw_7cf54d4d3eeac5135f0c027e25a75a4db3f0b8cb_gistfile1.ps1
# Delete page 170 from foo.djvu djvm -d foo.djvu 170 # Delete pages 170-174 from foo.djvu for ( $i = 0; $i -lt 5; $i++ ) { djvm -d foo.djvu 170 }
PowerShellCorpus/GithubGist/ianblenke_87a042abdd0102343386_raw_705872070981b140095547630d17a2dcb3b3e7cc_Bootstrap-EC2-Windows-CloudInit.ps1
ianblenke_87a042abdd0102343386_raw_705872070981b140095547630d17a2dcb3b3e7cc_Bootstrap-EC2-Windows-CloudInit.ps1
# Copied shamelessly from: https://gist.githubusercontent.com/masterzen/6714787/raw/3166173255caef341f578e1ea3fff1eea3072d5b/Bootstrap-EC2-Windows-CloudInit.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.githubusercontent.com/ianblenke/87a042abdd0102343386/raw')) -ArgumentList "adminPassword" # </powershell> # param( [Parameter(Mandatory=$true)] [string] $AdminPassword ) Start-Transcript -Path 'c:\bootstrap-transcript.txt' -Force Set-StrictMode -Version Latest Set-ExecutionPolicy Unrestricted $log = 'c:\Bootstrap.txt' while (($AdminPassword -eq $null) -or ($AdminPassword -eq '')) { $AdminPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host "Enter a non-null / non-empty Administrator password" -AsSecureString))) } $systemPath = [Environment]::GetFolderPath([Environment+SpecialFolder]::System) $sysNative = [IO.Path]::Combine($env:windir, "sysnative") #http://blogs.msdn.com/b/david.wang/archive/2006/03/26/howto-detect-process-bitness.aspx $Is32Bit = (($Env:PROCESSOR_ARCHITECTURE -eq 'x86') -and ($Env:PROCESSOR_ARCHITEW6432 -eq $null)) Add-Content $log -value "Is 32-bit [$Is32Bit]" #http://msdn.microsoft.com/en-us/library/ms724358.aspx $coreEditions = @(0x0c,0x27,0x0e,0x29,0x2a,0x0d,0x28,0x1d) $IsCore = $coreEditions -contains (Get-WmiObject -Query "Select OperatingSystemSKU from Win32_OperatingSystem" | Select -ExpandProperty OperatingSystemSKU) Add-Content $log -value "Is Core [$IsCore]" # move to home, PS is incredibly complex :) cd $Env:USERPROFILE Set-Location -Path $Env:USERPROFILE [Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath #change admin password net user Administrator $AdminPassword Add-Content $log -value "Changed Administrator password" $client = new-object System.Net.WebClient #.net 4 if ((Test-Path "${Env:windir}\Microsoft.NET\Framework\v4.0.30319") -eq $false) { $netUrl = if ($IsCore) {'http://download.microsoft.com/download/3/6/1/361DAE4E-E5B9-4824-B47F-6421A6C59227/dotNetFx40_Full_x86_x64_SC.exe' } ` else { 'http://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe' } $client.DownloadFile( $netUrl, 'dotNetFx40_Full.exe') Start-Process -FilePath 'C:\Users\Administrator\dotNetFx40_Full.exe' -ArgumentList '/norestart /q /ChainingPackage ADMINDEPLOYMENT' -Wait -NoNewWindow del dotNetFx40_Full.exe Add-Content $log -value "Found that .NET4 was not installed and downloaded / installed" } #configure powershell to use .net 4 $config = @' <?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- http://msdn.microsoft.com/en-us/library/w4atty68.aspx --> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" /> <supportedRuntime version="v2.0.50727" /> </startup> </configuration> '@ if (Test-Path "${Env:windir}\SysWOW64\WindowsPowerShell\v1.0\powershell.exe") { $config | Set-Content "${Env:windir}\SysWOW64\WindowsPowerShell\v1.0\powershell.exe.config" Add-Content $log -value "Configured 32-bit Powershell on x64 OS to use .NET 4" } if (Test-Path "${Env:windir}\system32\WindowsPowerShell\v1.0\powershell.exe") { $config | Set-Content "${Env:windir}\system32\WindowsPowerShell\v1.0\powershell.exe.config" Add-Content $log -value "Configured host OS specific Powershell at ${Env:windir}\system32\ to use .NET 4" } #check winrm id, if it's not valid and LocalAccountTokenFilterPolicy isn't established, do it $id = &winrm id if (($id -eq $null) -and (Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -ErrorAction SilentlyContinue) -eq $null) { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -value 1 -propertyType dword Add-Content $log -value "Added LocalAccountTokenFilterPolicy since winrm id could not be executed" } #enable powershell servermanager cmdlets (only for 2008 r2 + above) if ($IsCore) { DISM /Online /Enable-Feature /FeatureName:MicrosoftWindowsPowerShell /FeatureName:ServerManager-PSH-Cmdlets /FeatureName:BestPractices-PSH-Cmdlets Add-Content $log -value "Enabled ServerManager and BestPractices Cmdlets" #enable .NET flavors - on server core only -- errors on regular 2008 DISM /Online /Enable-Feature /FeatureName:NetFx2-ServerCore /FeatureName:NetFx2-ServerCore-WOW64 /FeatureName:NetFx3-ServerCore /FeatureName:NetFx3-ServerCore-WOW64 Add-Content $log -value "Enabled .NET frameworks 2 and 3 for x86 and x64" } #7zip $7zUri = if ($Is32Bit) { 'http://sourceforge.net/projects/sevenzip/files/7-Zip/9.22/7z922.msi/download' } ` else { 'http://sourceforge.net/projects/sevenzip/files/7-Zip/9.22/7z922-x64.msi/download' } $client.DownloadFile( $7zUri, '7z922.msi') Start-Process -FilePath "msiexec.exe" -ArgumentList '/i 7z922.msi /norestart /q INSTALLDIR="c:\program files\7-zip"' -Wait SetX Path "${Env:Path};C:\Program Files\7-zip" /m $Env:Path += ';C:\Program Files\7-Zip' del 7z922.msi Add-Content $log -value "Installed 7-zip from $7zUri and updated path" #vc 2010 redstributable $vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/5/B/C/5BC5DBB3-652D-4DCE-B14A-475AB85EEF6E/vcredist_x86.exe'} ` else { 'http://download.microsoft.com/download/3/2/2/3224B87F-CFA0-4E70-BDA3-3DE650EFEBA5/vcredist_x64.exe' } $client.DownloadFile( $vcredist, 'vcredist.exe') Start-Process -FilePath 'C:\Users\Administrator\vcredist.exe' -ArgumentList '/norestart /q' -Wait del vcredist.exe Add-Content $log -value "Installed VC++ 2010 Redistributable from $vcredist and updated path" #vc 2008 redstributable $vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/d/d/9/dd9a82d0-52ef-40db-8dab-95376989c03/vcredist_x86.exe'} ` else { 'http://download.microsoft.com/download/d/2/4/d242c3fb-da5a-4542-ad66-f9661d0a8d19/vcredist_x64.exe' } $client.DownloadFile( $vcredist, 'vcredist.exe') Start-Process -FilePath 'C:\Users\Administrator\vcredist.exe' -ArgumentList '/norestart /q' -Wait del vcredist.exe Add-Content $log -value "Installed VC++ 2008 Redistributable from $vcredist and updated path" #curl $curlUri = if ($Is32Bit) { 'http://www.paehl.com/open_source/?download=curl_724_0_ssl.zip' } ` else { 'http://curl.haxx.se/download/curl-7.23.1-win64-ssl-sspi.zip' } $client.DownloadFile( $curlUri, 'curl.zip') &7z e curl.zip `-o`"c:\program files\curl`" if ($Is32Bit) { $client.DownloadFile( 'http://www.paehl.com/open_source/?download=libssl.zip', 'libssl.zip') &7z e libssl.zip `-o`"c:\program files\curl`" del libssl.zip } SetX Path "${Env:Path};C:\Program Files\Curl" /m $Env:Path += ';C:\Program Files\Curl' del curl.zip Add-Content $log -value "Installed Curl from $curlUri and updated path" #vim & 'C:\Program Files\Curl\curl.exe' -# -G -k -L ftp://ftp.vim.org/pub/vim/pc/vim73_46rt.zip -o vim73_46rt.zip 2>&1 > "$log" & 'C:\Program Files\Curl\curl.exe' -# -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('https://chocolatey.org/install.ps1')) } 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 & 'C:\Program Files\Curl\curl.exe' -# -G -k -L https://downloads.puppetlabs.com/windows/puppet-3.2.4.msi -o puppet-3.2.4.msi 2>&1 > "$log" Start-Process -FilePath "msiexec.exe" -ArgumentList '/qn /passive /i puppet-3.2.4.msi /norestart' -Wait SetX Path "${Env:Path};C:\Program Files\Puppet Labs\Puppet\bin" /m &sc.exe config puppet start= demand Add-Content $log -value "Installed Puppet" &winrm quickconfig `-q &winrm set winrm/config/client/auth '@{Basic="true"}' &winrm set winrm/config/service/auth '@{Basic="true"}' &winrm set winrm/config/service '@{AllowUnencrypted="true"}' Add-Content $log -value "Ran quickconfig for winrm" &netsh firewall set portopening tcp 445 smb enable Add-Content $log -value "Ran firewall config to allow incoming smb/tcp" #run SMRemoting script to enable event log management, etc - available only on R2 $remotingScript = [IO.Path]::Combine($systemPath, 'Configure-SMRemoting.ps1') if (-not (Test-Path $remotingScript)) { $remotingScript = [IO.Path]::Combine($sysNative, 'Configure-SMRemoting.ps1') } Add-Content $log -value "Found Remoting Script: [$(Test-Path $remotingScript)] at $remotingScript" if (Test-Path $remotingScript) { . $remotingScript -force -enable Add-Content $log -value 'Ran Configure-SMRemoting.ps1' } #wait a bit, it's windows after all Start-Sleep -m 10000 #Write-Host "Press any key to reboot and finish image configuration" #[void]$host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') Restart-Computer
PowerShellCorpus/GithubGist/zhujo01_e10d69ec4b1249c3c5e3_raw_a50bb1b433ec397ed7a40395f16b9d84ff2cd758_amazon-openstack.ps1
zhujo01_e10d69ec4b1249c3c5e3_raw_a50bb1b433ec397ed7a40395f16b9d84ff2cd758_amazon-openstack.ps1
######################################################################## # AWS EC2 Windows Bootstrapping Script # Supported OS: # - Windows 2008 Server R2 SP1 (TESTED) # - Windows 2008 Server (TO BE TESTED) # - Windows 2012 Server (TO BE TESTED) # Image Transformation Target Cloud # - Openstack # # Coppyright (c) 2014, CliQr Technologies, Inc. All rights reserved. ########################################################################
PowerShellCorpus/GithubGist/johntseng_62b90f4df5bc595db55e_raw_388d018e61a818d78209092f26121fef3fd8f87d_gistfile1.ps1
johntseng_62b90f4df5bc595db55e_raw_388d018e61a818d78209092f26121fef3fd8f87d_gistfile1.ps1
param([string]$filename, [string]$fullname) $tempZ = "c:\temp\$filename.7z" if (!(get-S3Object -BucketName database-backups -key (split-path $tempZ -leaf))) { exit 1 } Read-S3Object -BucketName database-backups -key (split-path $tempZ -leaf) -File $tempZ C:\7za.exe x $tempZ mv "$filename" "$fullname" rm $tempZ
PowerShellCorpus/GithubGist/forsythetony_0c43e8a9305c0a3867ba_raw_277a382a15d7512266ac51dc3376c1862e7c42e6_gettingFiles.ps1
forsythetony_0c43e8a9305c0a3867ba_raw_277a382a15d7512266ac51dc3376c1862e7c42e6_gettingFiles.ps1
function updateFilesInRange($range) { $pathToFiles = $range.folderPath # Selection all items within the $pathToFiles directory that meet the following conditions... # 1. It is not a directory # 2. It was created after the start of the date range # 3. It was created before the end of the date range Get-ChildItem -Path $pathToFiles -Recurse | Where-Object {$_.Name -like "*.avi" -and !$_.PSIsDirectory -and $_.CreationTime -ge $range.start -and $_.CreationTime -le $range.end} | Foreach-Object{ # $newName = $_.Basename + ".mp4"; #C:\Users\Bigben\Desktop\ffmpeg-20140519-git-76191c0-win64-static\bin\ffmpeg.exe "$_" -f mp4 -r 25 -s 320*240 -b 768 -ar 44000 -ab 112 $newName; # Here you would use the file path along with ffmpeg to do the conversion $newVideo = [io.path]::ChangeExtension($_.FullName, '.mp4') # Declare the command line arguments for ffmpeg.exe $ArgumentList = '-i "{0}" -an -b:v 64k -bufsize 64k -vcodec libx264 -pix_fmt yuv420p "{1}"' -f $_.FullName, $newVideo; # Display message show user the arguments list of the conversion $convertMessage = ("Converting video with argument list " + $ArgumentList) Write-Host $convertMessage #Start-Process -FilePath C:\Users\muengrcerthospkinect\Desktop\Kinect\ffmpeg.exe -ArgumentList $ArgumentList -Wait -NoNewWindow; } }
PowerShellCorpus/GithubGist/colinbowern_6314743_raw_310043826e36e6de1a1546e125f97fc2f530c06e_Update-ADObjects.ps1
colinbowern_6314743_raw_310043826e36e6de1a1546e125f97fc2f530c06e_Update-ADObjects.ps1
# Reads CSV generated by CSVDE and updates the properties for Active Directory User param([Parameter(Position=0, Mandatory=$true)] $FileName) $ReadOnlyProperties = "DN", "objectClass", "sAMAccountName" Write-Host "Reading from $FileName" $UserRecords = Import-Csv $FileName foreach($UserRecord in $UserRecords) { Write-Host "Updating $($UserRecord.DN)" $User = [adsi]$("LDAP://" + $UserRecord.DN) foreach($Attribute in $($UserRecord.PSObject.Properties | Where { $ReadOnlyProperties -NotContains $_.Name })) { Write-Host "Setting $($Attribute.Name) to $($Attribute.Value)" $User.Put($Attribute.Name, $Attribute.Value) } $User.SetInfo() }
PowerShellCorpus/GithubGist/taddev_3962965_raw_35a03d6541b8cda59a0e42052de4d5b896e94bca_RunElevated.ps1
taddev_3962965_raw_35a03d6541b8cda59a0e42052de4d5b896e94bca_RunElevated.ps1
# # Author: Tad DeVries # Email: taddevries@gmail.com # FileName: RunElevated.ps1 # # Description: # Creates a "sudo" like command to elevate another # command to administrative level. This is used to # simplify the CLI interaction and create a little # home like feeling for the *nix users out there. # # # Copyright (C) 2010 Tad DeVries # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # License Info: http://www.gnu.org/licenses/gpl-2.0.html # # function RunElevated { param( [string]$Program=$(Throw "Please specify a program"), [string]$Arguments = $args ) $psi = new-object System.Diagnostics.ProcessStartInfo $Program; $psi.Arguments = $Arguments; $psi.Verb = "runas"; $psi.WorkingDirectory = get-location; [System.Diagnostics.Process]::Start($psi); <# .SYNOPSIS Runs a programs with elevated privilages. .DESCRIPTION Runs a programs with elevated privilages. Just like good old sudo in Linux .INPUTS Any program needing admin privilages to run. .EXAMPLE RunElevated notepad temp.txt .EXAMPLE sudo notepad temp.txt .LINK http://splunk.net #> } ##Set a simplified alias to mimic the *nix world Set-Alias sudo RunElevated ##export module Export-ModuleMember -Function * -Alias * # SIG # Begin signature block # MIIbaQYJKoZIhvcNAQcCoIIbWjCCG1YCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU9UDGOyXgFwGmaaSpDr1L3LNg # yY2gghYbMIIDnzCCAoegAwIBAgIQeaKlhfnRFUIT2bg+9raN7TANBgkqhkiG9w0B # AQUFADBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xKzAp # BgNVBAMTIlZlcmlTaWduIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EwHhcNMTIw # NTAxMDAwMDAwWhcNMTIxMjMxMjM1OTU5WjBiMQswCQYDVQQGEwJVUzEdMBsGA1UE # ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xNDAyBgNVBAMTK1N5bWFudGVjIFRpbWUg # U3RhbXBpbmcgU2VydmljZXMg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gNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjErMCkGA1UEAxMiVmVy # aVNpZ24gVGltZSBTdGFtcGluZyBTZXJ2aWNlcyBDQQIQeaKlhfnRFUIT2bg+9raN # 7TAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG # 9w0BCQUxDxcNMTIxMDI3MDI0NzIxWjAjBgkqhkiG9w0BCQQxFgQUXnCk+bSu4yI4 # o9PxAfoni6sDiM0wDQYJKoZIhvcNAQEBBQAEgYCDsci8IWyhusLpwxebvqsETMgc # 7OR6l4Jtgzj5hrg/mOoePUfr25hZHQn3HeqE47IYuDUeEL61u8FHT6RmRAhK1Fnh # ys0jx1SXh7kMQkBgHvfNEoKIekGYzojUXC2XI+7kFnvbcvJrpx04Oi0ibVVd/Xi0 # N5OOiH7wuD9ONp0hrQ== # SIG # End signature block
PowerShellCorpus/GithubGist/posaunehm_3753947_raw_4eae963ad67a84d776ddb13acad79b5a961f1fc3_gistfile1.ps1
posaunehm_3753947_raw_4eae963ad67a84d776ddb13acad79b5a961f1fc3_gistfile1.ps1
ls *.bmp | sort -Property Length -Unique | % -begin{$i = 0} -process{ren $_ ("Image" + $i.ToString() + ".bmp");$i += 1 }
PowerShellCorpus/GithubGist/bradmurray_4723664_raw_6ef80d30c652593d4a112625ada6f91ac709b3a8_CopyToBitcasa.ps1
bradmurray_4723664_raw_6ef80d30c652593d4a112625ada6f91ac709b3a8_CopyToBitcasa.ps1
# Usage: CopyToBitcasa FileSpec [-move] [-dir=DestinationDirectory] # FileSpec: A file to copy/move (accepts wildcards) # -move: File(s) will be moved to the Bitcasa directory # -dir: The directory beneath $BitcasaDirectory that where the files(s) will go. If omitted copy will go to the root. This directory must exist on Bitcasa. # Created by: Brad Murray murraybrad+copytobitcasa@gmail.com $BitcasaDirectory = "I:\My Infinite" $BitcasaOutgoingDirectory = $home+"\AppData\Roaming\com.bitcasa.Bitcasa\Data\bks\outgoing" $MoveToBitcasa = "" function SmartFileSize([int64]$fileSize) { # Return file size at optimal scale If ($fileSize -lt 1KB) { return ($fileSize.ToString()) } ElseIf ($fileSize -lt 1MB) { return ([string]::Format("{0:N3} KB", $fileSize / 1KB)) } ElseIf ($fileSize -lt 1GB) { return ([string]::Format("{0:N3} MB", $fileSize / 1MB)) } ElseIf ($fileSize -lt 1TB) { return ([string]::Format("{0:N3} GB", $fileSize / 1GB)) } Else { return ($fileSize.ToString()) } } function WriteTime($timeIn) { If ($timeIn.Hours -gt 0) { return [string]::Format("{0}:{1:00}:{2:00}", $timeIn.Hours, $timeIn.Minutes, $timeIn.Seconds) } ElseIf ($timeIn.Minutes -gt 0) { return [string]::Format("{0}:{1:00}", $timeIn.Minutes, $timeIn.Seconds) } Else { return [string]::Format("{0} sec", $timeIn.Seconds) } } function GetBitcasaOutgoingDirSize() { try { [string]$root = $(resolve-path $BitcasaOutgoingDirectory) $cItem = Get-ChildItem -re $root -erroraction 'silentlycontinue' | ?{ -not $_.PSIsContainer } | measure-object -sum -property Length -erroraction 'silentlycontinue' [long]$dirSize = $cItem.sum return $dirSize } catch { return [long]-1 } } If (!(Test-Path $BitcasaDirectory -pathType container)) { Write-Host $BitcasaDirectory does not exist -ForegroundColor Red Exit } If (!(Test-Path $BitcasaOutgoingDirectory -pathType container)) { Write-Host $BitcasaOutgoingDirectory does not exist -ForegroundColor Red Exit } # Get any command-line arguments ForEach ($arg in $args) { Write-Host $arg Switch ($arg.ToLower().Split("=")[0]) { "-move" { $MoveToBitcasa = "/MOV" } "-dir" { $BitcasaDirectory = $BitcasaDirectory + "\" + $arg.Split("=")[1] Write-Host "NEWDIR " $BitcasaDirectory } } } Get-ChildItem $args[0] | ForEach-Object { Write-Host $_.FullName -ForegroundColor Cyan Write-Host "Mod Date:" $LastWriteDate -ForegroundColor Cyan Write-Host "Size:" (SmartFileSize($_.Length)) -ForegroundColor Cyan # Copy the show to Bitcasa If (Test-Path $BitcasaDirectory -pathType container) { [DateTime]$waitStart = Get-Date $dirSize = GetBitcasaOutgoingDirSize while(!($dirSize -eq 0)) { # Wait for Bitcasa outgoing queue to empty before adding another file $waitTime = (Get-Date) - $waitStart write-host $([string]::Format("Waiting since {0} {1} {2} ", $waitStart, (WriteTime($waitTime)), (SmartFileSize($dirSize)))) -nonewline -ForegroundColor White write-host $("`r") -nonewline Start-Sleep 10; $dirSize = GetBitcasaOutgoingDirSize } write-host "" & RoboCopy $_.DirectoryName $BitcasaDirectory $_.Name /W:10 /R:1 /NJH /NDL $MoveToBitcasa } Else { Write-Host $BitcasaDirectory does not exist -ForegroundColor Red break } }
PowerShellCorpus/GithubGist/jstangroome_3522474_raw_8229b7015c324491e53b73c89c0187e74ec767a4_LazyProperty.ps1
jstangroome_3522474_raw_8229b7015c324491e53b73c89c0187e74ec767a4_LazyProperty.ps1
function Add-LazyProperty { [CmdletBinding()] param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [PSObject] $InputObject, [Parameter(Mandatory=$true, Position=1)] [string] $Name, [Parameter(Mandatory=$true, Position=2)] [ScriptBlock] $Value, [switch] $PassThru ) process { $LazyValue = { $Result = & $Value Add-Member -InputObject $this -MemberType NoteProperty -Name $Name -Value $Result -Force $Result }.GetNewClosure() Add-Member -InputObject $InputObject -MemberType ScriptProperty -Name $Name -Value $LazyValue -PassThru:$PassThru } } function Test-LazyProperty { # get a boring object $TestObject = Get-Process -Id $PID # make sure it's a PSObject, this step is unnecessary in PowerShell v3 $TestObject = [PSObject]$TestObject # add a script property to return the current ticks $TestObject | Add-Member -MemberType ScriptProperty -Name Ticks -Value { (Get-Date).Ticks } # add a lazy property to return the current ticks $TestObject | Add-LazyProperty -Name LazyTicks -Value { (Get-Date).Ticks } # display the property members, notice they are both ScriptProperties $TestObject | Get-Member -Name *Ticks # display the property values once $TestObject | Select-Object -Property *Ticks # display the property members, notice LazyTicks is now a static NoteProperty $TestObject | Get-Member -Name *Ticks # display the property values again, notice LazyTicks hasn't changed $TestObject | Select-Object -Property *Ticks } Test-LazyProperty
PowerShellCorpus/GithubGist/mmdemirbas_5229315_raw_dda918f6778dfa67f4fee80287d855c86f61d235_set-ntfs-ro.ps1
mmdemirbas_5229315_raw_dda918f6778dfa67f4fee80287d855c86f61d235_set-ntfs-ro.ps1
######################################################################### # # # Script to set or clear read-only flag of an NTFS volume. # # # # Usage: .\set-ntfs-ro.ps1 set "MY DISK LABEL" # # .\set-ntfs-ro.ps1 clear "MY DISK LABEL" # # # # Author: Muhammed Demirbas, mmdemirbas at gmail dot com # # Date : 2013-03-23 # # # ######################################################################### param($setOrClear, $diskLabel) if( [string]::IsNullOrWhiteSpace($setOrClear) ) { $ScriptName = $MyInvocation.MyCommand.Name "usage: .\$ScriptName set ""MY DISK LABEL""" " .\$ScriptName clear ""MY DISK LABEL""" return } if( $setOrClear -ne "set" -and $setOrClear -ne "clear" ) { throw 'Valid actions are "set" and "clear"!' } if( [string]::IsNullOrWhiteSpace($diskLabel) ) { throw "Please specify a non-blank disk label!" } # Path of the temporary file to use as diskpart script $scriptFile = "$env:TMP\set-ntfs-ro-script.tmp" # Save "list volume" command to a temp-file "list volume" | Out-File -Encoding ascii $scriptFile # Execute diskpart providing the script, and select the involved line $matches = diskpart /s $scriptFile | Select-String $diskLabel if( $matches.Length -eq 0 ) { throw "No match for the label: $diskLabel" } elseif ( $matches.Length -ge 2 ) { throw "More than one match for the label: $diskLabel" } # Obtain volume number $words = $matches.Line.Trim().Split(" ") if( !$words -or $words.Length -le 1 ) { throw "Volume number couldn't be obtained for the volume:`n$line" } $volumeNum = $words.Get(1) # Save the command to modify read-only flag to a temp-file "select volume $volumeNum att vol $setOrClear readonly detail vol" | Out-File -Encoding ascii $scriptFile # Execute the command, and print details diskpart /s $scriptFile # Clean the waste del $scriptFile
PowerShellCorpus/GithubGist/gravejester_6bc472fcf60ca3f0eeef_raw_1314c8bd2fcb035d16820f92476a41fa73bb91fa_Show-Calendar.ps1
gravejester_6bc472fcf60ca3f0eeef_raw_1314c8bd2fcb035d16820f92476a41fa73bb91fa_Show-Calendar.ps1
function Show-Calendar { <# .SYNOPSIS Show calendar. .DESCRIPTION This function is a PowerShell version of the *NIX cal command and will show a calendar of the chosen month(s). The current day will be marked with a '*'. For best results, use together with the FormatPx module by Kirk Munro. .EXAMPLE Show-Calendar Will show a calendar view of the current month. .EXAMPLE Show-Calendar -InvariantCulture Will show a calendar view of the current month, using the Invariant Culture .EXAMPLE Show-Calendar -Culture 'de-DE' Will show a calendar view of the current month, using the de-DE (German) culture. .EXAMPLE Show-Calendar 1 2015 -m 3 Will show a calendar view of the first three months in 2015. .EXAMPLE Show-Calendar 12 -MarkDay 25 -Abbreviated Will show a calendar view of december and mark December 25, with abbreviated day names. .EXAMPLE Show-Calendar 1 2015 -m 12 -MarkDate (Get-Date -Year 2015 -Month 2 -Day 14) Will show a calendar view of 2015 and mark 14th of February. .LINK https://github.com/KirkMunro/FormatPx .NOTES Author: Øyvind Kallstad Date: 21.12.2014 Version: 1.1 22.12.2014 Added Alignment parameter Made the entire function culture aware Added support for abbreviated day names #> [CmdletBinding(DefaultParameterSetName = 'Culture')] param ( # The starting month number. Default is current month. [Parameter(Position = 0)] [Alias('Month')] [ValidateRange(1,12)] [int] $StartMonth = [DateTime]::Now.Month, # The starting year. Default is current year. [Parameter(Position = 1)] [Alias('Year')] [ValidateRange(1,9999)] [int32] $StartYear = [DateTime]::Now.Year, # How many months to show. Default is 1. [Parameter()] [Alias('m')] [ValidateRange(1,[int]::MaxValue)] [int32] $Months = 1, # Day to mark on the calendar. [Parameter()] [ValidateRange(1,31)] [int32] $MarkDay, # Date to mark on the calendar. [Parameter()] [datetime] $MarkDate, # Set alignment of the dates in the output. Default value is 'Right'. [Parameter()] [ValidateSet('Left','Right')] [string] $Alignment = 'Right', # Use the Invariant Culture (English). [Parameter(ParameterSetName = 'InvariantCulture')] [switch] $InvariantCulture, # Use this parameter to choose what culture to use. If this parameter is not used and # the InvariantCulture parameter is false, the current culture will be used instead. [Parameter(ParameterSetName = 'Culture')] [string] $Culture, # Use this parameter to use abbreviated day names. Default is to use the full name of days. [Parameter()] [switch] $AbbreviatedDayNames ) function New-DayOfWeekString { <# .SYNPSIS Output a culture aware string of a specified week day. .NOTES Author: Øyvind Kallstad #> [CmdletBinding()] [OutputType([String])] param ( # The day of week in Invariant Culture (English). [Parameter(Position = 0, Mandatory)] [System.DayOfWeek] $DayOfWeek, [Parameter(Position = 1, ValueFromPipeline)] [CultureInfo] $CultureInfo = [System.Globalization.CultureInfo]::CurrentCulture, # Show the week day in an abbreviated form. [Parameter()] [switch] $Abbreviated ) if ($Abbreviated) { Write-Output ($cultureInfo.TextInfo.ToTitleCase($cultureInfo.DateTimeFormat.GetAbbreviatedDayName([System.DayOfWeek]::$DayOfWeek))) } else { Write-Output ($cultureInfo.TextInfo.ToTitleCase($cultureInfo.DateTimeFormat.GetDayName([System.DayOfWeek]::$DayOfWeek))) } } function New-Week { <# .SYNOPSIS Returns an ordered dictionary representing a week. .NOTES Author: Øyvind Kallstad #> [CmdletBinding()] [OutputType([System.Collections.Specialized.OrderedDictionary])] param ( [Parameter(Position = 0, ValueFromPipeline)] [CultureInfo] $CultureInfo = [System.Globalization.CultureInfo]::CurrentCulture, # Show the week day in an abbreviated form. [Parameter()] [switch] $Abbreviated ) $propHash = @{ CultureInfo = $CultureInfo } if ($Abbreviated) { $propHash.Abbreviated = $true } # define week day names $monday = New-DayOfWeekString 'Monday' @propHash $tuesday = New-DayOfWeekString 'Tuesday' @propHash $wednesday = New-DayOfWeekString 'Wednesday' @propHash $thursday = New-DayOfWeekString 'Thursday' @propHash $friday = New-DayOfWeekString 'Friday' @propHash $saturday = New-DayOfWeekString 'Saturday' @propHash $sunday = New-DayOfWeekString 'Sunday' @propHash $week = [Ordered] @{ $tuesday = $null $wednesday = $null $thursday = $null $friday = $null $saturday = $null } if (($CultureInfo.DateTimeFormat.FirstDayOfWeek) -eq 'Monday') { $week.Insert(0, $monday, $null) $week.Add($sunday, $null) } else { $week.Insert(0, $sunday, $null) $week.Insert(1, $monday, $null) } Write-Output $week } # get a CultureInfo object based on user input # either with an Invariant Culture... if ($InvariantCulture) { $cultureInfo = [System.Globalization.CultureInfo]::InvariantCulture } # ... user defined culture... elseif ($Culture) { $cultureInfo = [System.Globalization.CultureInfo]::CreateSpecificCulture($Culture) } # ... or the current culture else { $cultureInfo = [System.Globalization.CultureInfo]::CurrentCulture } # supporting internationalization # add additional languages as needed switch ($cultureInfo.Name) { 'nb-NO' {$translate = @{Year = 'År'; Month = 'Måned'; Week = 'Uke'}} # Norwegian (Bokmål) 'da-DK' {$translate = @{Year = 'År'; Month = 'Måned'; Week = 'Uge'}} # Danish 'sv-SE' {$translate = @{Year = 'År'; Month = 'Månad'; Week = 'Vecka'}} # Swedish 'fi-FI' {$translate = @{Year = 'Vuosi'; Month = 'Kuukausi'; Week = 'Viikko'}} # Finnish 'de-DE' {$translate = @{Year = 'Jahr'; Month = 'Monat'; Week = 'Woche'}} # German 'de-AT' {$translate = @{Year = 'Jahr'; Month = 'Monat'; Week = 'Woche'}} # German (Austria) 'de-CH' {$translate = @{Year = 'Jahr'; Month = 'Monat'; Week = 'Woche'}} # German (Switzerland) 'nl-NL' {$translate = @{Year = 'Jaar'; Month = 'Maand'; Week = 'Week'}} # Dutch 'fr-FR' {$translate = @{Year = 'Année'; Month = 'Mois'; Week = 'Semaine'}} # French 'fr-CH' {$translate = @{Year = 'Année'; Month = 'Mois'; Week = 'Semaine'}} # French (Switzerland) 'fr-LU' {$translate = @{Year = 'Année'; Month = 'Mois'; Week = 'Semaine'}} # French (Luxembourg) 'it-IT' {$translate = @{Year = 'Anno'; Month = 'Mese'; Week = 'Settimana'}} # Italian 'es-ES' {$translate = @{Year = 'Año'; Month = 'Mes'; Week = 'Semana'}} # Spanish 'ru-RU' {$translate = @{Year = 'Год'; Month = 'Месяц'; Week = 'Неделя'}} # Russian 'cs-CZ' {$translate = @{Year = 'Rok'; Month = 'Měsíc'; Week = 'Týden'}} # Czech 'ms-MY' {$translate = @{Year = 'Tahun'; Month = 'Bulan'; Week = 'Minggu'}} # Malay 'ja-JP' {$translate = @{Year = '年'; Month = '月'; Week = '1週間'}} # Japanese 'is-IS' {$translate = @{Year = 'Ári'; Month = 'Mánuði'; Week = 'Viku'}} # Icelandic 'pl-PL' {$translate = @{Year = 'Rok'; Month = 'Miesiąc'; Week = 'Tydzień'}} # Polish 'cy-GB' {$translate = @{Year = 'Blwyddyn'; Month = 'Mis'; Week = 'Wythnos'}} # Welsh (United Kingdom) DEFAULT {$translate = @{Year = 'Year'; Month = 'Month'; Week = 'Week'}} # Invariant Culture (English) } $thisMonth = $StartMonth - 1 $thisYear = $StartYear $output = @() $weekProperties = @{} if ($AbbreviatedDayNames) { $weekProperties.Abbreviated = $true } # loop through the months for ($i = 1; $i -le $Months; $i++) { # increment month $thisMonth++ # when month is greater than 12, a new year is triggered, so reset month to 1 and increment year if ($thisMonth -gt 12) { $thisMonth = 1 $thisYear++ } # get the number of days in the month $daysInMonth = $cultureInfo.Calendar.GetDaysInMonth($thisYear,$thisMonth) # define new week $thisWeek = $cultureInfo | New-Week @weekProperties $thisWeek.Insert(0, $translate.Month, $null) $thisWeek.Insert(1, $translate.Year, $null) $thisWeek.Insert(2, $translate.Week, $null) # loop through each day in the month for ($y = 1; $y -lt ($daysInMonth + 1); $y++) { # get a datetime object of the current date $thisDate = New-Object -TypeName 'System.DateTime' -ArgumentList ($thisYear,$thisMonth,$y,$cultureInfo.Calendar) # if current date is the first day of a week (but not if it's the very first day of the month at the same time) if (($thisDate.DayOfWeek -eq ($cultureInfo.DateTimeFormat.FirstDayOfWeek)) -and ($y -gt 1)) { # add the week object to the output array $weekObject = New-Object -TypeName 'PSCustomObject' -Property $thisWeek $output += $weekObject # reset the week $thisWeek = $cultureInfo | New-Week @weekProperties $thisWeek.Insert(0, $translate.Month, $null) $thisWeek.Insert(1, $translate.Year, $null) $thisWeek.Insert(2, $translate.Week, $null) } # get string representation of the month and the current week number (if week number is 53, change to 1) $monthString = $cultureInfo.TextInfo.ToTitleCase($thisDate.ToString('MMMM',$cultureInfo)) $thisWeekNumber = $cultureInfo.calendar.GetWeekOfYear($thisDate,$cultureInfo.DateTimeFormat.CalendarWeekRule,$cultureInfo.DateTimeFormat.FirstDayOfWeek) if ($thisWeekNumber -eq 53) { $thisWeekNumber = 1 } # overload the ToString method of the datetime object $thisDate | Add-Member -MemberType ScriptMethod -Name 'ToString' -Value { # mark today with '*' if (($this.Date) -eq ([DateTime]::Now.Date)) { if($Alignment -eq 'Left') {$this.Day.ToString() + '*'} else {'*' + $this.Day.ToString()} } elseif ($MarkDay -eq $this.Day) { if($Alignment -eq 'Left') {$this.Day.ToString() + '!'} else {'!' + $this.Day.ToString()} } elseif ($MarkDate.Date -eq $this.Date) { if($Alignment -eq 'Left') {$this.Day.ToString() + '!'} else {'!' + $this.Day.ToString()} } else { $this.Day.ToString() } } -Force # update the week hashtable with the current day, week, month and year $thisWeek[($cultureInfo | New-DayOfWeekString ($thisDate.DayOfWeek) -Abbreviated:$AbbreviatedDayNames)] = $thisDate $thisWeek[$translate.Week] = $thisWeekNumber $thisWeek[$translate.Month] = $monthString $thisWeek[$translate.Year] = $thisYear } # add the final week to the output array $weekObject = New-Object -TypeName 'PSCustomObject' -Property $thisWeek $output += $weekObject } # translate day names $monday = $cultureInfo | New-DayOfWeekString 'Monday' -Abbreviated:$AbbreviatedDayNames $tuesday = $cultureInfo | New-DayOfWeekString 'Tuesday' -Abbreviated:$AbbreviatedDayNames $wednesday = $cultureInfo | New-DayOfWeekString 'Wednesday' -Abbreviated:$AbbreviatedDayNames $thursday = $cultureInfo | New-DayOfWeekString 'Thursday' -Abbreviated:$AbbreviatedDayNames $friday = $cultureInfo | New-DayOfWeekString 'Friday' -Abbreviated:$AbbreviatedDayNames $saturday = $cultureInfo | New-DayOfWeekString 'Saturday' -Abbreviated:$AbbreviatedDayNames $sunday = $cultureInfo | New-DayOfWeekString 'Sunday' -Abbreviated:$AbbreviatedDayNames # define a hashtable to hold format properties for the table output if (($cultureInfo.DateTimeFormat.FirstDayOfWeek) -eq 'Monday') { $formatProperties = @{ Property = "$($translate.Week)", @{Name = "$monday" ;Expression = {$_.$monday} ;Alignment = $Alignment}, @{Name = "$tuesday" ;Expression = {$_.$tuesday} ;Alignment = $Alignment}, @{Name = "$wednesday" ;Expression = {$_.$wednesday} ;Alignment = $Alignment}, @{Name = "$thursday" ;Expression = {$_.$thursday} ;Alignment = $Alignment}, @{Name = "$friday" ;Expression = {$_.$friday} ;Alignment = $Alignment}, @{Name = "$saturday" ;Expression = {$_.$saturday} ;Alignment = $Alignment}, @{Name = "$sunday" ;Expression = {$_.$sunday} ;Alignment = $Alignment} } } else { $formatProperties = @{ Property = "$($translate.Week)", @{Name = "$sunday" ;Expression = {$_.$sunday} ;Alignment = $Alignment}, @{Name = "$monday" ;Expression = {$_.$monday} ;Alignment = $Alignment}, @{Name = "$tuesday" ;Expression = {$_.$tuesday} ;Alignment = $Alignment}, @{Name = "$wednesday" ;Expression = {$_.$wednesday} ;Alignment = $Alignment}, @{Name = "$thursday" ;Expression = {$_.$thursday} ;Alignment = $Alignment}, @{Name = "$friday" ;Expression = {$_.$friday} ;Alignment = $Alignment}, @{Name = "$saturday" ;Expression = {$_.$saturday} ;Alignment = $Alignment} } } # if FormatPx is loaded, use it to format the output if (Get-Module -Name 'FormatPx') { Write-Output ($output | Format-Table @formatProperties -AutoSize -GroupBy @{Name = "$($translate.Month)";Expression = {"$($_.($translate.Month)) $($_.($translate.Year))"}} -PersistWhenOutput) } # else use default PowerShell formatting else { Write-Output ($output | Format-Table @formatProperties -AutoSize -GroupBy @{Name = "$($translate.Month)";Expression = {"$($_.($translate.Month)) $($_.($translate.Year))"}}) } } New-Alias -Name 'cal' -Value 'Show-Calendar' -Force
PowerShellCorpus/GithubGist/klumsy_1f84fea3fb1de7a2e75b_raw_1c6608e204bbf637660dce53092e67bae13a2fbc_PurgeRabbitQueues.ps1
klumsy_1f84fea3fb1de7a2e75b_raw_1c6608e204bbf637660dce53092e67bae13a2fbc_PurgeRabbitQueues.ps1
$rabbitserver = 'localhost:15672' $cred = Get-Credential iwr -ContentType 'application/json' -Method Get -Credential $cred "http://${rabbitserver}/api/queues" | % { ConvertFrom-Json $_.Content } | % { $_ } | ? { $_.messages -gt 0} | % { iwr -method DELETE -Credential $cred -uri $("http://${rabbitserver}/api/queues/{0}/{1}" -f [System.Web.HttpUtility]::UrlEncode($_.vhost), $_.name) } iwr -Cr $cred "http://${rabbitserver}/api/queues" | % { ConvertFrom-Json $_.Content } | % { $_ } | % {iwr -me DELETE -Cr $cred $("http://${rabbitserver}/api/queues/{0}/{1}" -f [System.Web.HttpUtility]::UrlEncode($_.vhost), $_.name)}
PowerShellCorpus/GithubGist/shiranGinige_3760691_raw_2b54199a759ab11c259987a5a629140cc24aa8b7_FindProjectsWithGivenReference.ps1
shiranGinige_3760691_raw_2b54199a759ab11c259987a5a629140cc24aa8b7_FindProjectsWithGivenReference.ps1
# Calling Convention # FindReference.ps1 "log4net" param([String]$ReferenceToFind ) $xmlns = "http://schemas.microsoft.com/developer/msbuild/2003" $projects = ls -r -i *.csproj foreach($projectPath in $projects) { $proj = [string](Get-Content $projectPath) $containsReference = $proj.ToLower().Contains($ReferenceToFind) if ($containsReference) { [System.Console]::WriteLine("{0}", $projectPath) } }
PowerShellCorpus/GithubGist/jstangroome_1715073_raw_b71180d1fb071d77a7f6b4d624e02909eb9025f6_Export-TfsBuildDefinition.ps1
jstangroome_1715073_raw_b71180d1fb071d77a7f6b4d624e02909eb9025f6_Export-TfsBuildDefinition.ps1
[CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidatePattern('^https?://')] [string] $CollectionUri, [string] $ProjectName = '*', [Alias('Name')] [string] $BuildDefinitionName = '*' ) function New-TypedObject ( [string] $TypeName, [hashtable] $Property ) { $o = New-Object -TypeName PSObject -Property $Property $o.PSObject.TypeNames.Insert(0, $TypeName) return $o } $script:ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest '', '.Client', '.Build.Client' | ForEach-Object { Add-Type -AssemblyName "Microsoft.TeamFoundation$_, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" } $Collection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($CollectionUri) $BuildServer = $Collection.GetService([Microsoft.TeamFoundation.Build.Client.IBuildServer]) $BuildServer.QueryBuildDefinitions($ProjectName) | Where-Object { $_.Name -like $BuildDefinitionName } | ForEach-Object { $Properties = @{ CollectionUri = $CollectionUri TeamProject = $_.TeamProject Name = $_.Name Description = $_.Description Enabled = $_.Enabled ContinuousIntegrationType = $_.ContinuousIntegrationType.ToString() BuildControllerName = $_.BuildController.Name DefaultDropLocation = $_.DefaultDropLocation Process = $_.Process.ServerPath ProcessParameters = $_.ProcessParameters } $Properties['WorkspaceMappings'] = @( $_.Workspace.Mappings | ForEach-Object { New-TypedObject -TypeName CodeAssassin.TeamBuild.WorkspaceMapping -Property @{ MappingType = $_.MappingType.ToString() ServerItem = $_.ServerItem LocalItem = $_.LocalItem Depth = $_.Depth.ToString() } } ) if ($_.ContinuousIntegrationType -eq 'Batch') { $Properties['ContinuousIntegrationQuietPeriod'] = $_.ContinuousIntegrationQuietPeriod } elseif ('Schedule', 'ScheduleForced' -contains $_.ContinuousIntegrationType) { $Properties['Schedules'] = @( $_.Schedules | ForEach-Object { New-TypedObject -TypeName CodeAssassin.TeamBuild.Schedule -Property @{ DaysToBuild = $_.DaysToBuild.ToString() StartTime = New-TimeSpan -Seconds $_.StartTime TimeZone = $_.TimeZone.Id Type = $_.Type } } ) } $Properties['RetentionPolicyList'] = @( $_.RetentionPolicyList | ForEach-Object { New-TypedObject -TypeName CodeAssassin.TeamBuild.RetentionPolicy -Property @{ BuildReason = $_.BuildReason.ToString() BuildStatus = $_.BuildStatus.ToString() NumberToKeep = $_.NumberToKeep DeleteOptions = $_.DeleteOptions.ToString() } } ) New-TypedObject -TypeName CodeAssassin.TeamBuild.BuildDefinition -Property $Properties }
PowerShellCorpus/GithubGist/hsteinhilber_914627_raw_f879b7a361268892ed45b6ab134a68a60da636de_profile.ps1
hsteinhilber_914627_raw_f879b7a361268892ed45b6ab134a68a60da636de_profile.ps1
Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent) $env:Path += ";c:\Git\cmd"; # Load posh-git module from current directory Import-Module posh-git # Adjust colors for git prompt $GitPromptSettings.BeforeForegroundColor = [ConsoleColor]::DarkCyan $GitPromptSettings.DelimForegroundColor = [ConsoleColor]::DarkCyan $GitPromptSettings.AfterForegroundColor = [ConsoleColor]::DarkCyan $GitPromptSettings.WorkingForegroundColor = [ConsoleColor]::Green function Print-Color([string]$left, [string]$text, [string]$right, [string]$bright_color) { $dark_color = ('Dark' + $bright_color) Write-Host ($left) -nonewline -foregroundcolor $dark_color Write-Host ($text) -nonewline -foregroundcolor $bright_color Write-Host ($right) -nonewline -foregroundcolor $dark_color } # Format working directory when it is a sub-folder of the user's profile function Get-CurrentLocation { $location = ($pwd).Path + "\" if ($location.StartsWith("$env:UserProfile\")) { return $location.Replace("$env:UserProfile\", "~\") } else { return $location } } # Test if the current user is running with administrator privileges function Test-Admin() { $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object Security.Principal.WindowsPrincipal($identity) return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } # Set up prompt consisting of a status line - user/machine {current-path} [git-status] function prompt { # Reset color, which can be messed up by Enable-GitColors $Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor $AdminColor = [ConsoleColor]::Red $AdminText = "$([char]0x0A7) " Write-Host("") if ( Test-Admin) { Write-Host($AdminText) -NoNewLine -ForegroundColor $AdminColor } Print-Color [ "$env:UserName@$env:ComputerName" ] Cyan Write-Host " - " -NoNewLine $path = Get-CurrentLocation Print-Color '{' "$path" '}' Yellow # Git Prompt $Global:GitStatus = Get-GitStatus Write-GitStatus $GitStatus # Place command prompt following status line Write-Host("") return "PS> " } $teBackup = 'posh-git_DefaultTabExpansion' if(!(Test-Path Function:\$teBackup)) { Rename-Item Function:\TabExpansion $teBackup } # Set up tab expansion and include git expansion function TabExpansion($line, $lastWord) { $lastBlock = [regex]::Split($line, '[|;]')[-1] switch -regex ($lastBlock) { # Execute git tab completion for all git-related commands 'git (.*)' { GitTabExpansion $lastBlock } # Fall back on existing tab expansion default { & $teBackup $line $lastWord } } } Enable-GitColors Pop-Location
PowerShellCorpus/GithubGist/ao-zkn_1a26a755d47148ed807e_raw_385e6e2c29554674369e0625d258e37102975c96_Copy-ImagesByDateTimeOriginal.ps1
ao-zkn_1a26a755d47148ed807e_raw_385e6e2c29554674369e0625d258e37102975c96_Copy-ImagesByDateTimeOriginal.ps1
# ------------------------------------------------------------------ # 画像ファイル(jpeg,jpg)を撮影日ごとにフォルダ分けする # 関数名:Copy-ImagesByDateTimeOriginal # 引数 :CopyFolderPath コピー元のフォルダパス # :DestFolderPath コピー先のフォルダパス # 戻り値:なし # ------------------------------------------------------------------ function Copy-ImagesByDateTimeOriginal([String]$CopyFolderPath, [String]$DestFolderPath){ # EXIFタグ一覧より撮影日時のIDを指定 $DateTimeOriginalId = "36867" # EXIFの撮影日時のフォーマット $DateTimeFormat = "yyyy:MM:dd HH:mm:ss`0" # コピー元の指定したフォルダのチェック if(-not(Test-Path $CopyFolderPath)){ Write-Host "指定したコピー元フォルダが存在しません" break } # コピー先の指定したフォルダが存在しない場合に作成 $destItem = New-Item $DestFolderPath -Type directory -Force # 拡張子(jpeg、jpg)のファイルのみ Get-ChildItem $CopyFolderPath -Recurse -Include *.jpeg ,*.jpg | ForEach-Object { # 画像ファイルを読み込み、撮影日時のオブジェクト取得 $image = [System.Drawing.Imaging.Metafile]::FromFile($_.FullName) $propertyItem = $image.PropertyItems | Where-Object {$_.Id -eq $DateTimeOriginalId} # 撮影日時が取得できない場合「unknown」フォルダを作成 if($propertyItem -ne $Null){ # EXIFの撮影日時のフォーマットが「YYYY:MM:DD HH:MM:SS」のため日付に変換 $value = $image.GetPropertyItem($DateTimeOriginalId).Value $DateTimeOriginal = [System.Text.Encoding]::ASCII.GetString($value) $date = [DateTime]::ParseExact($DateTimeOriginal,$DateTimeFormat,$Null).ToString("yyyyMMdd") }else{ $date = "unknown" } # フォルダを作成 $createFolderPath = Join-Path -Path $DestFolderPath -ChildPath $date $destFolderItem = New-Item $createFolderPath -Type directory -Force # 作成したフォルダに画像ファイルをコピー $destFilePath =  Join-Path -Path $createFolderPath -ChildPath $_.Name if(Test-Path $destFilePath){ Write-Host "すでに存在します。コピー先 : [$destFilePath]" return } $destFileItem = Copy-Item -Path $_.FullName -Destination $destFilePath # 閉じる $image.Dispose() } }
PowerShellCorpus/GithubGist/Wimpje_a796ba134d61552587a7_raw_81d15917859fed17f4bf3827ba20e5a7fafd9e7e_SplitXml.ps1
Wimpje_a796ba134d61552587a7_raw_81d15917859fed17f4bf3827ba20e5a7fafd9e7e_SplitXml.ps1
param( [string]$file = $(throw "file is required"), $matchesPerSplit = 50, $maxFiles = [Int32]::MaxValue, $splitOnNode = $(throw "splitOnNode is required"), $offset = 0 ) # with a little help of https://gist.github.com/awayken/5861923 $ErrorActionPreference = "Stop"; trap { $ErrorActionPreference = "Continue" write-error "Script failed: $_ \r\n $($_.ScriptStackTrace)" exit (1); } $file = (resolve-path $file).path $fileNameExt = [IO.Path]::GetExtension($file) $fileNameWithoutExt = [IO.Path]::GetFileNameWithoutExtension($file) $fileNameDirectory = [IO.Path]::GetDirectoryName($file) $reader = [System.Xml.XmlReader]::Create($file) $matchesCount = $idx = 0 try { "Splitting $from on node name='$splitOnNode', with a max of $matchesPerSplit matches per file. Max of $maxFiles files will be generated." do { $result = $reader.ReadToFollowing($splitOnNode) if ($result -and ($matchesCount -lt $matchesPerSplit)) { if($offset -gt $idx) { $idx++ continue } $to = [IO.Path]::Combine($fileNameDirectory, "$fileNameWithoutExt.$($idx -$offset)$fileNameExt") "Writing to $to" $toXml = New-Object System.Xml.XmlTextWriter($to, $null) $toXml.Formatting = 'Indented' $toXml.Indentation = 2 try { $toXml.WriteStartElement("split") $toXml.WriteAttributeString("cnt", $null, "$matchesCount") do { $toXml.WriteRaw($reader.ReadOuterXml()) $matchesCount++; } while($reader.ReadToNextSibling($splitOnNode) -and ($matchesCount -lt $matchesPerSplit)) $toXml.WriteEndElement(); } finally { $toXml.Flush() $toXml.Close() } $idx++ $matchesCount = 0; } } while ($idx -lt $maxFiles + $offset) } finally { $reader.Close() }
PowerShellCorpus/GithubGist/guitarrapc_3d1af4a26d023bb5c005_raw_6c1cbc31034902f1b23e63ce6fd773595f0f59dc_StringEvaluationItem.ps1
guitarrapc_3d1af4a26d023bb5c005_raw_6c1cbc31034902f1b23e63ce6fd773595f0f59dc_StringEvaluationItem.ps1
# 例 $hoge = @{hoge = "hoge"} $fuga = "fuga"
PowerShellCorpus/GithubGist/snapcase_b7dbd396951d1b7b6a78_raw_b79041910d668b7a83519dccf849cf73a8ceaa45_nauts-FixReplays.ps1
snapcase_b7dbd396951d1b7b6a78_raw_b79041910d668b7a83519dccf849cf73a8ceaa45_nauts-FixReplays.ps1
#REQUIRES -Version 2.0 <# .SYNOPSIS Convert non-ascii Replays.info files to ascii so that they can be read by the game .DESCRIPTION When you enter "Replays" from the main menu a file called "Replays.info" will be populated with data about replays. In the occurence of unicode or other non-ascii character it will fail to parse data and the replay will not show up in game. The solution is to remove these characters from individual replays in order for them to display properly. The purpose of this script is to automate this process. .NOTES This script needs to be put in the Data\Replays folder. Use at your own risk. Consider backing up you Replays-folder before running. .LINK www.awesomenauts.com #> # Determine path and set location $scriptpath = $MyInvocation.MyCommand.Path $dir = Split-Path $scriptpath Set-Location $dir # Are we in the right folder? if(-not(Test-Path -Path .\Replays.info)) { Read-Host 'Put me in the Replay folder!' | Out-Null exit } # All replays $replays = (Get-ChildItem | ?{ $_.PSIsContainer } | % {$_.Name}) # Working replays [xml]$xml = Get-Content .\Replays.info $xml_replays = ($xml.SelectNodes("/Replays/Replay") | % {$_.Filename}) # Loop over replays # If they do not show up in game, make a backup of the "Replays.info" file and create a new one. $i = 0 foreach ($replay in $replays) { $info = "$replay\Replays.info" if ($xml_replays -notcontains $replay -and (Test-Path -Path "$info")) { # make sure its an individual replay and not a backed up 'Replay'-folder $single = ([xml] (Get-Content "$info")).Replay if ($single) { # if user runs script twice before visiting the Replay menu if (Test-Path -Path "${info}.bak") { continue } Move-Item -Path "$info" -Destination "${info}.bak" Get-Content "${info}.bak" | Out-File -FilePath "$info" -Encoding ASCII $i++ } } } Read-Host "Fixed $i replay(s)" | Out-Null
PowerShellCorpus/GithubGist/seraphy_4674696_raw_e1173acd4ce75fd2cdb8462ecb45ae252a4fa793_sha1sum.ps1
seraphy_4674696_raw_e1173acd4ce75fd2cdb8462ecb45ae252a4fa793_sha1sum.ps1
# 第一引数として、対象となるファイルまたは親ディレクトリを指定する. # 省略時はカレントディレクトリ以下のすべてのファイルを対象とする. param($searchPath = $(pwd)) # バイト配列を16進数文字列に変換する. function ToHex([byte[]] $hashBytes) { $builder = New-Object System.Text.StringBuilder $hashBytes | %{ [void] $builder.Append($_.ToString("x2")) } $builder.ToString() } # 指定したフォルダ以下の全てのファイルを取得する. # (ファイルが指定された場合はファイル自身を返す) function GetFilesRecurse([string] $path) { Get-ChildItem $path -Recurse | Where-Object -FilterScript { # ディレクトリ以外のみ (ディレクトリのビットマスク値は16) ($_.Attributes -band 16) -eq 0 } } function MakeEntry { process { New-Object PSObject -Property @{ LastWriteTime = $_.LastWriteTime; Length = $_.Length; FullName = $_.FullName; } } } # パイプラインからのファイルのハッシュ情報を取得する. function MakeHashInfo([string] $algoName = $(throw "MD5, SHA1, SHA512などを指定します.")) { begin { $algo = [System.Security.Cryptography.HashAlgorithm]::Create($algoName) # ファイルのハッシュ値を計算するスクリプトブロック(Closure) function CalcurateHash([string] $path) { $inputStream = New-Object IO.StreamReader $path try { $algo.ComputeHash($inputStream.BaseStream) } finally { $inputStream.Close() } } } process { # パイプライン処理 $hashVal = ToHex(CalcurateHash $_.FullName) $_ | Add-Member -MemberType NoteProperty -Name $algoName -Value $hashVal return $_ } end { [void] $algo.Dispose # voidを指定しないと後続パイプラインにnullが渡される } } # 指定ディレクトリ下のすべてのファイルのSHA1, MD5をグリッドに表示する. GetFilesRecurse $searchPath | MakeEntry | MakeHashInfo "SHA1" | MakeHashInfo "MD5" | Out-GridView -Title "Hash Summary"
PowerShellCorpus/GithubGist/fimcookbook_5557196_raw_99b3b112f6bb33a26933d50913b750ed4ca7f37e_UnProtect-SecretWithMachineKey.ps1
fimcookbook_5557196_raw_99b3b112f6bb33a26933d50913b750ed4ca7f37e_UnProtect-SecretWithMachineKey.ps1
function unprotectSecretWithMachineKey { [CmdletBinding()] param( [Parameter(Mandatory=$True, ValueFromPipeline=$True)] [string] $secret ) BEGIN{ Add-Type -AssemblyName System.Web $utf8Encoder = New-Object System.Text.UTF8Encoding } PROCESS { $protectedSecretBytes = [Convert]::FromBase64String($secret) $unprotectedPasswordBytes = [System.Web.Security.MachineKey]::Unprotect($protectedSecretBytes) Write-Output $utf8Encoder.GetString($unprotectedPasswordBytes) } END{} } # unprotectSecretWithMachineKey "H7QfZMlLPeYkvR2bGQV9xh3yx5B6LRVbiK53+joVPKlsYiLp0kLVmTRMJ6acES+NFJtsf5469FX6ctBnNDqLbQ=="
PowerShellCorpus/GithubGist/vinyar_311c78091e7e1d1f86ff_raw_734fa69ed67c5a478ad525ffdc5bbea5ec9741ae_HKLM%20auditpolicy.ps1
vinyar_311c78091e7e1d1f86ff_raw_734fa69ed67c5a478ad525ffdc5bbea5ec9741ae_HKLM%20auditpolicy.ps1
# $sddl = 'O:BAG:SYD:PAI(A;CI;KA;;;CO)(A;CI;KA;;;SY)(A;CI;KA;;;BA)(A;CI;KR;;;BU)(A;CI;KR;;;AC)S:AI(AU;CISA;KA;;;WD)' # alternative just in case $acl = get-acl HKLM:\\SOFTWARE -audit $audit = "Everyone","FullControl","containerinherit","none","Fail" $rule = new-object system.security.accesscontrol.registryauditrule $audit $acl.SetAuditRule($rule) # $acl.SetSecurityDescriptorSddlForm($sddl) # alternative just in case set-acl -Path HKLM:\\SOFTWARE -AclObject $acl
PowerShellCorpus/GithubGist/tanaka-takayoshi_6567570_raw_742090f181cfb4a95ee41700e556acb11d57158b_Add-Routing.ps1
tanaka-takayoshi_6567570_raw_742090f181cfb4a95ee41700e556acb11d57158b_Add-Routing.ps1
Install-WindowsFeature RemoteAccess -IncludeManagementTools Add-WindowsFeature -name Routing -IncludeManagementTools Restart-Computer
PowerShellCorpus/GithubGist/Novakov_5487789_raw_94951ad6041520701754fcbcaf45c662c0fc5cd1_merge.ps1
Novakov_5487789_raw_94951ad6041520701754fcbcaf45c662c0fc5cd1_merge.ps1
param([string]$repo, [string]$source,[string]$dest) $base = "$/MAPS Onboard/Dev/$repo" set-alias tf 'C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\TF.exe' tf get /recursive "$base/$source" tf merge /recursive "$base/$source" "$base/$dest" tf checkin /comment:"merge $source -> $dest"
PowerShellCorpus/GithubGist/zachbonham_5082482_raw_1d7736a0f8586127ac581486549a032590899519_hello.ps1
zachbonham_5082482_raw_1d7736a0f8586127ac581486549a032590899519_hello.ps1
write-host "machine $($env:computername)" write-host "hello, $($env:computername) "
PowerShellCorpus/GithubGist/belotn_8418024_raw_54a85031f0a5ab90b774de89e928982beeedc6e1_list_session.ps1
belotn_8418024_raw_54a85031f0a5ab90b774de89e928982beeedc6e1_list_session.ps1
get-xaserver -FolderPAth $FOLDERPATH |% { $sv = $_.ServerName; quser /SERVER:$($_.serverNAme) |% { $arrT = @( $_ -Split ' ' |? { $_ -ne ' '-and $_.length -gt 0 } ); new-object PSobject -property @{"Session" = $arrT[1]; "Inact" = $arrT[6]; "ServerName" = $sv} } } |? { $_.Session -ne 'SESSION' } | sort Inact
PowerShellCorpus/GithubGist/rysstad_10370591_raw_1f3278116a3a9f5caad57aa189fe467b7fd563f5_Set-PowershellWindowProperties.ps1
rysstad_10370591_raw_1f3278116a3a9f5caad57aa189fe467b7fd563f5_Set-PowershellWindowProperties.ps1
# Create object reference to Get-Host $pshost = get-host # create reference to the console’s UI.RawUI child object $pswindow = $pshost.ui.rawui # Adjust the buffer first: $newsize = $pswindow.buffersize $newsize.height = 9999 $newsize.width = 200 $pswindow.buffersize = $newsize # Adjust the Window size $newsize = $pswindow.windowsize $newsize.height = 60 $newsize.width = 200 $pswindow.windowsize = $newsize
PowerShellCorpus/GithubGist/guitarrapc_bfdaee4a9c368c869f96_raw_8e85a032087750c8002585106d1b23e7f004b04e_ACLTest.ps1
guitarrapc_bfdaee4a9c368c869f96_raw_8e85a032087750c8002585106d1b23e7f004b04e_ACLTest.ps1
configuration ACLTest { Import-DscResource -ModuleName GraniResource $path = "D:\Test" File test { DestinationPath = $path Ensure = "Present" Type = "Directory" } cACL test { Path = $path Account = "everyone" Rights = "FullControl" Ensure = "Present" DependsOn = "[File]test" } }
PowerShellCorpus/GithubGist/jbarber_464354_raw_1478714a9bffa8721d95eed78a022cba23ecf8bf_have_ballooned.ps1
jbarber_464354_raw_1478714a9bffa8721d95eed78a022cba23ecf8bf_have_ballooned.ps1
# Find all of the VMs that have experienced ballooning in the last day function ballooned? ($vm) { $d = Get-Stat -memory -entity $vm -start (Get-Date).AddDays(-1) | ?{ $_.MetricId -eq 'mem.vmmemctl.average' } | ?{ $_.value -ne 0 } return $d.count -ne 0 } connect-viserver -server virtualcenter -credential (Get-Credential (Get-Item env:username).value) $vms = get-view -viewtype virtualmachine $vms | ?{ ballooned?( get-viobjectbyviview -moref $_.moref ) } | %{ $_.name }
PowerShellCorpus/GithubGist/roberto-reale_9b3c601dcfe7acef5f0c_raw_35b9a0e30236c49ad09ac60f60b1a774c35c11cb_trabb_pardo_knuth.ps1
roberto-reale_9b3c601dcfe7acef5f0c_raw_35b9a0e30236c49ad09ac60f60b1a774c35c11cb_trabb_pardo_knuth.ps1
# # Trabb Pardo–Knuth algorithm # # see http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm # function TPK_function($x) { return [math]::pow([math]::abs($x), .5) + 5 * [math]::pow($x, 3) } function TPK([string] $f) { [double[]] $values # ask for 11 numbers to be read into a sequence S Write-Host "Please enter 11 numbers" 1..11 |% { $values += @(Read-Host $_) } # for each item in sequence S 1..11 |% { # reverse sequence S $v = $values[11-$_] # result := call a function to do an operation $result = Invoke-Expression "$f $v" if ($result -gt 400) { # if result overflows alert user! Write-Error "Result too large!" } else { # print result Write-Host "f($v) = $result" } } } TPK "TPK_function"
PowerShellCorpus/GithubGist/707cf2eeb1_11185851_raw_5e262bd56d9e6704f405f5a94dd8f3506c16c88e_gistfile1.ps1
707cf2eeb1_11185851_raw_5e262bd56d9e6704f405f5a94dd8f3506c16c88e_gistfile1.ps1
Get-Mailbox | Search-Mailbox -SearchQuery кому:. -DeleteContent -SearchDumpstersOnly
PowerShellCorpus/GithubGist/nlarkin_6357491_raw_7f070c4b8ec78166f1c4ad3adbac45cbdab750ab_gettaxonomyterm.ps1
nlarkin_6357491_raw_7f070c4b8ec78166f1c4ad3adbac45cbdab750ab_gettaxonomyterm.ps1
Function GetTaxonomyTerm($spsite, $field, $label) { Write-Host "Getting term for $($label)..." $taxonomySession = Get-SPTaxonomySession -Site $spsite $taxonomyField = $spsite.RootWeb.Fields.GetField($field) $termStoreID = $taxonomyField.SspId $termStore = $taxonomySession.TermStores[$termStoreID] $termsetID = $taxonomyField.TermSetId $termset = $termStore.GetTermSet($termsetID) $term = $termset.GetTerms( $label, $true) return [string] $term[0].Name +"|"+$term[0].Id }
PowerShellCorpus/GithubGist/mwrock_5130865_raw_a81f0f70648db3e9da1683dffa48a030c56f6152_gistfile1.ps1
mwrock_5130865_raw_a81f0f70648db3e9da1683dffa48a030c56f6152_gistfile1.ps1
#Get Boxstarter on RemotePC CINST Boxstarter.Chocolatey Import-Module Boxstarter.Chocolatey #Create minimal nuspec and chocolateyInstall New-BoxstarterPackage MyPackage #Edit Install script Notepad Join-Path $Boxstarter.LocalRepo "tools\ChocolateyInstall.ps1" #Pack nupkg Invoke-BoxstarterBuild MyPackage #share Repo Set-BoxstarterShare #on new bare os \\RemotePC\Boxstarter\Boxstarter Mypackage #Enter password when prompted and come back later to new box
PowerShellCorpus/GithubGist/taomaree_7213105_raw_8c3ffca5c6b5532deac1995bcb4fe34a510fe0e0_backup-mssql.ps1
taomaree_7213105_raw_8c3ffca5c6b5532deac1995bcb4fe34a510fe0e0_backup-mssql.ps1
# run first by administrator : # set-executionpolicy remotesigned $timestr=get-date -uformat "%Y-%m-%d-%H-%M-%S" $tsql="" $prefix="D:\sqlbackup\" $filepath=$prefix + $timestr + "\" if (! ( Test-Path $filepath)) {mkdir $filepath } #if (! (Test-Path D:\sqlbackuptsql) ) {mkdir D:\sqlbackuptsql } function backup_mssql($dbname) { $tsql += "BACKUP DATABASE " + $dbname +" TO DISK = N'" + $filepath + $dbname + "_FULL_" + $timestr+".bak' WITH CHECKSUM, COMPRESSION, BUFFERCOUNT = 50, MAXTRANSFERSIZE = 4194304;" #$tsql >> ("D:\sqlbackuptsql\" + $timestr + ".sql") sqlcmd -Q $tsql return $tsql } $array="[DB1]","[DB2]","[DB3]","[DB4]","[DB5]","[DB6]","[DB7]" foreach ($n in $array) { backup_mssql($n) }
PowerShellCorpus/GithubGist/JeremySkinner_411950_raw_bb103fe04fe3fe257a900d178070cdcee0b1fb47_Profile.ps1
JeremySkinner_411950_raw_bb103fe04fe3fe257a900d178070cdcee0b1fb47_Profile.ps1
# First you'll need to download posh-hg from one of the following locations: # http://github.com/JeremySkinner/posh-hg # http://poshhg.codeplex.com # Add the following code to your profile.ps1 (usually in C:\Users\User\Documents\WindowsPowershell) # Import the posh-hg module from wherever it is saved Import-Module "Path\To\posh-hg" # Override the default prompt behaviour: # text that appears before branch name $global:HgPromptSettings.BeforeText = ' on ' # Colour of text before branch name $global:HgPromptSettings.BeforeForegroundColor = [ConsoleColor]::White # Include a new line after the repository information... #...followed by the text "hg" to identify it as a mercurial repo $global:HgPromptSettings.AfterText = " `nhg" # Text that appears before tag list $global:HgPromptSettings.BeforeTagText = ' at ' # ...and you also need to include a custom prompt function: function prompt { # Display current path before mercurial prompt write-host "$pwd" -NoNewLine -foregroundcolor green # Display the Mercurial prompt Write-HgStatus # prompt arrows write-host "»" -NoNewLine -ForegroundColor green # display path in console title $Host.UI.RawUI.WindowTitle = $pwd return ' ' } #If you want tab expansion for hg commands: if(-not (Test-Path Function:\DefaultTabExpansion)) { Rename-Item Function:\TabExpansion DefaultTabExpansion } function TabExpansion($line, $lastWord) { $LineBlocks = [regex]::Split($line, '[|;]') $lastBlock = $LineBlocks[-1] switch -regex ($lastBlock) { '(hg|hgtk) (.*)' { HgTabExpansion($lastBlock) } # Fall back on existing tab expansion default { DefaultTabExpansion $line $lastWord } } }
PowerShellCorpus/GithubGist/racingcow_3e099ee7dc4ad3e4c8ae_raw_8deb68d366928696bc7ac940214cae931c8beb5a_salesmachine.ps1
racingcow_3e099ee7dc4ad3e4c8ae_raw_8deb68d366928696bc7ac940214cae931c8beb5a_salesmachine.ps1
############################################################ # Join domain ############################################################ #Rename-Computer -NewName devmachine -LocalCredential admin #Add-Computer -DomainName CT -Credential CT\dmiller ############################################################ # Boxstarter options ############################################################ $Boxstarter.RebootOk=$true # Allow reboots? $Boxstarter.NoPassword=$false # Is this a machine with no login password? $Boxstarter.AutoLogin=$true # Save my password securely and auto-login after a reboot ############################################################ #basic setup ############################################################ Update-ExecutionPolicy Unrestricted Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions Enable-RemoteDesktop Disable-InternetExplorerESC Disable-UAC Set-TaskbarSmall Write-BoxstarterMessage "Setting time zone to Central Standard Time" & C:\Windows\system32\tzutil /s "Central Standard Time" cinst Microsoft-Hyper-V-All -source windowsFeatures cinst DotNet3.5 cinst DotNet4.5.1 if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # Update Windows and reboot if necessary ############################################################ Install-WindowsUpdate -AcceptEula if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # utils, plugins, frameworks, and other miscellany ############################################################ cinst javaruntime cinst webpi cinst adobereader cinst flashplayeractivex cinst flashplayerplugin cinst AdobeAIR cinst 7zip cinst zoomit cinst PDFCreator cinst lockhunter cinst windirstat cinst teamviewer cinst ransack if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # communications ############################################################ # cinst HipChat # <- seems to be old adobe air version cinst skype if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # text editors ############################################################ cinst evernote cinst notepadplusplus.install if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # browsers ############################################################ cinst GoogleChrome cinst Firefox if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # to the cloud! ############################################################ cinst dropbox if (Test-PendingReboot) { Invoke-Reboot } cinst ShrewSoftVpn if (Test-PendingReboot) { Invoke-Reboot }
PowerShellCorpus/GithubGist/nonprofittechy_1f8123f79166241575fa_raw_3a0e21487c37dcee4be981d2051cdfe45bb85d22_gistfile1.ps1
nonprofittechy_1f8123f79166241575fa_raw_3a0e21487c37dcee4be981d2051cdfe45bb85d22_gistfile1.ps1
$ipath = "C:\PATH_TO_THUMBNAILS" $images = gci -Path $ipath $jpgBytes = $null foreach ($image in $images) { $jpgBytes = $null $jpgBytes = [byte[]]$jpg = Get-Content ($image.fullName) -encoding byte set-aduser -id $image.BaseName -replace @{thumbnailPhoto = $jpgBytes} }
PowerShellCorpus/GithubGist/BlueManiac_8e989e6defee486ec560_raw_764371d700c32164843f3cb7d88c809e737d7aec_Restore%20database%20backup%20to%20localdb.ps1
BlueManiac_8e989e6defee486ec560_raw_764371d700c32164843f3cb7d88c809e737d7aec_Restore%20database%20backup%20to%20localdb.ps1
$backupFilePath = "..." $backupDataName = "..." $backupLogName = "..." $databaseInstanceName = "v11.0" $databaseName = '...' $databaseFolderLocation = "C:\Databases" $databaseFileName = "${databaseName}" $tempInstanceName = "temp" $tempDatabaseName = "temp" sqllocaldb create $tempInstanceName -s # Create the database files. $sql = @" CREATE DATABASE ${tempDatabaseName} GO RESTORE DATABASE ${tempDatabaseName} FROM DISK = N'${backupFilePath}' WITH REPLACE, RECOVERY, MOVE N'${backupDataName}' TO N'${databaseFolderLocation}\${databaseFileName}.mdf', MOVE N'${backupLogName}' TO N'${databaseFolderLocation}\${databaseFileName}.ldf', NOUNLOAD, STATS = 5 "@ sqlcmd -S "(localdb)\$tempInstanceName" -Q $sql # The temporary database will be stuck in the restoring state after the restore. # See https://connect.microsoft.com/SQLServer/feedback/details/789845/localdb-cannot-restore-a-backup-whose-original-data-and-log-files-are-in-different-folders # Just stop and delete the temporary database instance to unlock the database files. sqllocaldb stop $tempInstanceName sqllocaldb delete $tempInstanceName # Create the real database with the created database files as base. $sql = @" CREATE DATABASE ${databaseName} ON (Name = '${backupDataName}', Filename ='${databaseFolderLocation}\${databaseFileName}.mdf') LOG ON (Name ='${backupLogName}', Filename ='${databaseFolderLocation}\${databaseFileName}.ldf') FOR ATTACH; GO "@ sqlcmd -S "(localdb)\${databaseInstanceName}" -Q $sql
PowerShellCorpus/GithubGist/jeremybeavon_1872f1ffc39f2944c6c0_raw_231480aa5a924ff03e02817870df9ee4e522988e_join-object.ps1
jeremybeavon_1872f1ffc39f2944c6c0_raw_231480aa5a924ff03e02817870df9ee4e522988e_join-object.ps1
function AddItemProperties($item, $properties, $output) { if($item -ne $null) { foreach($property in $properties) { $propertyHash =$property -as [hashtable] if($propertyHash -ne $null) { $hashName=$propertyHash["name"] -as [string] if($hashName -eq $null) { throw "there should be a string Name" } $expression=$propertyHash["expression"] -as [scriptblock] if($expression -eq $null) { throw "there should be a ScriptBlock Expression" } $_=$item $expressionValue=& $expression $output | add-member -MemberType "NoteProperty" -Name $hashName -Value $expressionValue } else { # .psobject.Properties allows you to list the properties of any object, also known as "reflection" foreach($itemProperty in $item.psobject.Properties) { if ($itemProperty.Name -like $property) { $output | add-member -MemberType "NoteProperty" -Name $itemProperty.Name -Value $itemProperty.Value } } } } } } function WriteJoinObjectOutput($leftItem, $rightItem, $leftProperties, $rightProperties, $Type) { $output = new-object psobject if($Type -eq "AllInRight") { # This mix of rightItem with LeftProperties and vice versa is due to # the switch of Left and Right arguments for AllInRight AddItemProperties $rightItem $leftProperties $output AddItemProperties $leftItem $rightProperties $output } else { AddItemProperties $leftItem $leftProperties $output AddItemProperties $rightItem $rightProperties $output } $output } <# .Synopsis Joins two lists of objects .DESCRIPTION Joins two lists of objects .EXAMPLE Join-Object $a $b "Id" ("Name","Salary") #> function Join-Object { [CmdletBinding()] [OutputType([int])] Param ( # List to join with $Right [Parameter(Mandatory=$true, Position=0)] [object[]] $Left, # List to join with $Left [Parameter(Mandatory=$true, Position=1)] [object[]] $Right, # Condition in which an item in the left matches an item in the right # typically something like: {$args[0].Id -eq $args[1].Id} [Parameter(Mandatory=$true, Position=2)] [scriptblock] $Where, # Properties from $Left we want in the output. # Each property can: # - Be a plain property name like "Name" # - Contain wildcards like "*" # - Be a hashtable like @{Name="Product Name";Expression={$_.Name}}. Name is the output property name # and Expression is the property value. The same syntax is available in select-object and it is # important for join-object because joined lists could have a property with the same name [Parameter(Mandatory=$true, Position=3)] [object[]] $LeftProperties, # Properties from $Right we want in the output. # Like LeftProperties, each can be a plain name, wildcard or hashtable. See the LeftProperties comments. [Parameter(Mandatory=$true, Position=4)] [object[]] $RightProperties, # Type of join. # AllInLeft will have all elements from Left at least once in the output, and might appear more than once # if the where clause is true for more than one element in right, Left elements with matches in Right are # preceded by elements with no matches. This is equivalent to an outer left join (or simply left join) # SQL statement. # AllInRight is similar to AllInLeft. # OnlyIfInBoth will cause all elements from Left to be placed in the output, only if there is at least one # match in Right. This is equivalent to a SQL inner join (or simply join) statement. # AllInBoth will have all entries in right and left in the output. Specifically, it will have all entries # in right with at least one match in left, followed by all entries in Right with no matches in left, # followed by all entries in Left with no matches in Right.This is equivallent to a SQL full join. [Parameter(Mandatory=$false, Position=5)] [ValidateSet("AllInLeft","OnlyIfInBoth","AllInBoth", "AllInRight")] [string] $Type="OnlyIfInBoth" ) Begin { # a list of the matches in right for each object in left $leftMatchesInRight = new-object System.Collections.ArrayList # the count for all matches $rightMatchesCount = New-Object "object[]" $Right.Count for($i=0;$i -lt $Right.Count;$i++) { $rightMatchesCount[$i]=0 } } Process { if($Type -eq "AllInRight") { # for AllInRight we just switch Left and Right $aux = $Left $Left = $Right $Right = $aux } # go over items in $Left and produce the list of matches foreach($leftItem in $Left) { $leftItemMatchesInRight = new-object System.Collections.ArrayList $null = $leftMatchesInRight.Add($leftItemMatchesInRight) for($i=0; $i -lt $right.Count;$i++) { $rightItem=$right[$i] if($Type -eq "AllInRight") { # For AllInRight, we want $args[0] to refer to the left and $args[1] to refer to right, # but since we switched left and right, we have to switch the where arguments $whereLeft = $rightItem $whereRight = $leftItem } else { $whereLeft = $leftItem $whereRight = $rightItem } if(Invoke-Command -ScriptBlock $where -ArgumentList $whereLeft,$whereRight) { $null = $leftItemMatchesInRight.Add($rightItem) $rightMatchesCount[$i]++ } } } # go over the list of matches and produce output for($i=0; $i -lt $left.Count;$i++) { $leftItemMatchesInRight=$leftMatchesInRight[$i] $leftItem=$left[$i] if($leftItemMatchesInRight.Count -eq 0) { if($Type -ne "OnlyIfInBoth") { WriteJoinObjectOutput $leftItem $null $LeftProperties $RightProperties $Type } continue } foreach($leftItemMatchInRight in $leftItemMatchesInRight) { WriteJoinObjectOutput $leftItem $leftItemMatchInRight $LeftProperties $RightProperties $Type } } } End { #produce final output for members of right with no matches for the AllInBoth option if($Type -eq "AllInBoth") { for($i=0; $i -lt $right.Count;$i++) { $rightMatchCount=$rightMatchesCount[$i] if($rightMatchCount -eq 0) { $rightItem=$Right[$i] WriteJoinObjectOutput $null $rightItem $LeftProperties $RightProperties $Type } } } } }
PowerShellCorpus/GithubGist/gschizas_4958672_raw_2d6e656024dadc473400fd0a044ad0c8881b7f72_FixVirtualNetworkAdapters.ps1
gschizas_4958672_raw_2d6e656024dadc473400fd0a044ad0c8881b7f72_FixVirtualNetworkAdapters.ps1
# see http://msdn2.microsoft.com/en-us/library/bb201634.aspx # # *NdisDeviceType # # The type of the device. The default value is zero, which indicates a standard # networking device that connects to a network. # # Set *NdisDeviceType to NDIS_DEVICE_TYPE_ENDPOINT (1) if this device is an # endpoint device and is not a true network interface that connects to a network. # For example, you must specify NDIS_DEVICE_TYPE_ENDPOINT for devices such as # smart phones that use a networking infrastructure to communicate to the local # computer system but do not provide connectivity to an external network. # # Usage: run in an elevated shell (vista/longhorn) or as adminstrator (xp/2003). # # PS> .\fix-vmnet-adapters.ps1 # boilerplate elevation check $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = new-object Security.Principal.WindowsPrincipal $identity $elevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $elevated) { $error = "Sorry, you need to run this script" if ([System.Environment]::OSVersion.Version.Major -gt 5) { $error += " in an elevated shell." } else { $error += " as Administrator." } throw $error } function confirm { $host.ui.PromptForChoice("Continue", "Process adapter?", [Management.Automation.Host.ChoiceDescription[]]@("&No", "&Yes"), 1) -eq $true } # adapters key pushd 'hklm:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}' # ignore and continue on error dir -ea 0 | % { $node = $_.pspath $desc = gp $node -name driverdesc # Write-Host $desc if ($desc -like "*vmware*" -or $desc -like "*VirtualBox*" -or $desc -like "*TAP-Win32*" -or $desc -like "*Hyper-V*") { Write-Host ("Found adapter: {0} " -f $desc.driverdesc) if (confirm) { new-itemproperty $node -name '*NdisDeviceType' -propertytype dword -value 1 } } } popd # disable/enable network adapters gwmi win32_networkadapter | ? {$_.name -like "*vmware*" -or $_.name -like "*VirtualBox*" -or $_.name -like "*TAP-Win32*"} | % { # disable write-host -nonew "Disabling $($_.name) ... " $result = $_.Disable() if ($result.ReturnValue -eq -0) { write-host " success." } else { write-host " failed." } # enable write-host -nonew "Enabling $($_.name) ... " $result = $_.Enable() if ($result.ReturnValue -eq -0) { write-host " success." } else { write-host " failed." } }
PowerShellCorpus/GithubGist/rberrelleza_5870412_raw_25c3965e00ee9a09e0fe6e257ae6fef0655e4e7f_add-users.ps1
rberrelleza_5870412_raw_25c3965e00ee9a09e0fe6e257ae6fef0655e4e7f_add-users.ps1
$domain = (get-addomain).distinguishedname $location = "OU=Engineering,$domain" $domain_email = 'yourdomain.com' $i = 0 Get-Content .\names.csv.txt | ForEach { $i++ $names = $_.Split() $first = $names[0] $last = $names[1] $username = "$first" + "." + "$last" $email = "$username" + $domain_email $password = ConvertTo-SecureString -AsPlainText "somethingG00D!" -force $sam = $first + '.' + $last New-ADUser $sam -AccountPassword $password -EmailAddress $email -UserPrincipalName $email -Enabled $true -GivenName $first -Surname $last $dn = (Get-ADUser $sam).DistinguishedName Move-ADObject -Identity $dn -TargetPath $location $i.ToString() + ") Name: " + $dn }
PowerShellCorpus/GithubGist/janegilring_5736378_raw_76b29cbf20afa01868683d6ac3fa9541a228247a_2013SGEvent6BeginnerSample.ps1
janegilring_5736378_raw_76b29cbf20afa01868683d6ac3fa9541a228247a_2013SGEvent6BeginnerSample.ps1
# Requires -Version 3.0   <# .SYNOPSIS     This script is used to perform basic configuration tasks on one or many Server 2012 core installations. .DESCRIPTION     New-CoreVMConfig is a script that will import a list of MAC addresses located at C:\Mac.txt by default and then query the DHCP server using the DhcpServer module     introduced in PowerShell 3.0 and Server 2012 to determine its associated dynamically assigned IP address.  When these results have been gathered we will process     each IP address one at a time, joining the machine to the domain.  During the join operation we will also be renaming the machine to SERVER(count) as well as     restarting the machine after the join is completed.  This operation will force the join and will not propmt the user for confirmation as defined by the event 6     rules to minimize user interaction.  Any non-terminating errors will be genereated in a more friendly manner by using Write-Warning and the exception message     returned for troubleshooting.  Successful operations will continue to move foward in the script. .EXAMPLE     .\New-CoreVMConfig.ps1 .NOTES     2013 PowerShell Scripting Games - Beginner Event 6 .NOTES     Thanks to everyone for the feedback both good and bad in this years PowerShell Games.      This was my first go at the games and I'd like to think I've learned alot during the last 6 weeks. #>   # Test for the DhcpServer PowerShell Module that is required for operation   if (-not(Get-Module -Name DhcpServer)) {     if (Get-Module -ListAvailable | Where-Object { $_.Name -eq 'DhcpServer' }) {         Import-Module -Name DhcpServer     }     else {         throw "The DhcpServer PowerShell Module is required and is not available."     }       }   # Assigning our static variables   $ipAddrs = @() $macAddrs = Get-Content -Path 'C:\Mac.txt' $domainCreds = Get-Credential -Credential "COMPANY\Administrator" $localCreds = Get-Credential -Credential "Administrator"   # Begin our foreach loop for processing of the MAC addresses and querying DHCP    foreach ($macAddr in $macAddrs) {     try     {         $ipAddrs += Get-DhcpServerv4Lease -ComputerName DCHP1.COMPANY.LOCAL -ScopeId 10.0.0.0 -ClientId $macAddr -ErrorAction Stop               }     catch [System.Exception]     {         Write-Warning -Message "$($_.Exception.Message)"     } }   # Begin our foreach loop for processing of the IP Addreses and joining the machine to the domain   foreach ($ip in $ipAddrs) {     try {         $serverCount = 1         Add-Computer -ComputerName $($ip.IPAddress.IPAddressToString) -Credential $domainCreds -LocalCredential $localCreds -DomainName COMPANY.LOCAL -NewName $("SERVER" + $serverCount++) -Restart -Force -ErrorAction Stop     }       catch [System.Exception] {         Write-Warning -Message "$($_.Exception.Message)"     } }
PowerShellCorpus/GithubGist/mnzk_8893975_raw_8dd4c763572d3534b7666caaf2cb5d0639a65789_method_pipeline.ps1
mnzk_8893975_raw_8dd4c763572d3534b7666caaf2cb5d0639a65789_method_pipeline.ps1
# 追加したメソッドをパイプラインで使いたい $foo = "abc" | Add-Member ScriptMethod Repeat{ param($n) $this * $n } -PassThru #Helper で対応 filter Invoke-Method($method){ $method.Invoke($_) } Set-Alias im Invoke-Method 5 | im $foo.Repeat #=> abcabcabcabcabc
PowerShellCorpus/GithubGist/zhujo01_be1cc2995ed228a4280e_raw_435c859f5493b22d530be00e9ad6dbe725ba7633_openstack-amazon.ps1
zhujo01_be1cc2995ed228a4280e_raw_435c859f5493b22d530be00e9ad6dbe725ba7633_openstack-amazon.ps1
######################################################################## # Openstack Bootstrapping Script # Supported OS: # - Windows 2008 Server R2 SP1 (TESTED) # - Windows 2008 Server (TO BE TESTED) # - Windows 2012 Server (TO BE TESTED) # Image Transformation Target Cloud # - Amazon EC2 # # Coppyright (c) 2014, CliQr Technologies, Inc. All rights reserved. ########################################################################
PowerShellCorpus/GithubGist/janikvonrotz_7823549_raw_ad7a17f08a8825c93a5fb28146c14b49d0f23a8a_Write-ProgressExample.ps1
janikvonrotz_7823549_raw_ad7a17f08a8825c93a5fb28146c14b49d0f23a8a_Write-ProgressExample.ps1
Write-Progress -Activity "Update settings" -status $($Mailbox.Name) -percentComplete ([Int32](([Array]::IndexOf($Mailboxes, $Mailbox)/($Mailboxes.count))*100))
PowerShellCorpus/GithubGist/taddev_3962920_raw_8f9f7db56879811aef2fcb524ce11e9cb9e7a37c_AddCert.ps1
taddev_3962920_raw_8f9f7db56879811aef2fcb524ce11e9cb9e7a37c_AddCert.ps1
# # Author: Tad DeVries # Email: taddevries@gmail.com # FileName: AddCert.ps1 # # Description: Allow a simple method to sign code. # # Copyright (C) 2010 Tad DeVries # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # License Info: http://www.gnu.org/licenses/gpl-2.0.html # param([string] $FilePath=$(throw "Please specify a filename.")) $cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] Set-AuthenticodeSignature -FilePath $FilePath -Certificate $cert -TimestampServer "http://timestamp.verisign.com/scripts/timestamp.dll" # SIG # Begin signature block # MIIbaQYJKoZIhvcNAQcCoIIbWjCCG1YCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgW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2/iVIXn8Uru0pzQEjTIsRHT+eyq7vkL2PO0xM # KvmyczutjvPOarU0n74LpofCwalL4FN99jHX0D9GN56GJw/Dm9tdYjwkppO1wilJ # bOjMgdHEeup66ReMr0MSvs8YWCqRW2rIT0Mz+FGAwBPS+Z6Jn591su07Ns5fhyKV # uw4Q8Dt3OZdP4zmnAjeUFjJrWWVO9VOB9p1CDhrhOcDwUYr2T8o00s98uAXxCh7y # th8UAhCMRgsoHG6GjnoHdfmnxlzoD+emryh7Yh1ra6STGHsBKFauSBtdFMMJoaVp # vlJTxRbgN3HlPCf9xuUNmOQttZ2IytmtYwXFUwV0J+N0oaSQi2C9NwrEvxZr9M0h # cmZmB31NL6Hje6GCAX8wggF7BgkqhkiG9w0BCQYxggFsMIIBaAIBATBnMFMxCzAJ # BgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjErMCkGA1UEAxMiVmVy # aVNpZ24gVGltZSBTdGFtcGluZyBTZXJ2aWNlcyBDQQIQeaKlhfnRFUIT2bg+9raN # 7TAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG # 9w0BCQUxDxcNMTIxMDI3MDI0NDQ2WjAjBgkqhkiG9w0BCQQxFgQU4g+MwBaLaaIA # UY+15zrmJivl9qAwDQYJKoZIhvcNAQEBBQAEgYAh0k/aCyXSVffJwIU1tOtg3VVH # LCUeXFNM6Tdkon8XosjSRaWyraH1gzmtzslzm7Ou7iPYW/x124mPJs58IF8pGsTo # uDErTYJXt8zoFb8nVcAIoKkmgRs2wuzOpTGqEvj3/w+ewXX8tmZ8V/OspaNqisFN # K36sGR1D3xaSpDf6VQ== # SIG # End signature block
PowerShellCorpus/GithubGist/pkskelly_7e814b634f18b652f1e2_raw_f3b429481f12fa280e657458b59ed3f6f0a9de6d_RemoveSiteOrphans.ps1
pkskelly_7e814b634f18b652f1e2_raw_f3b429481f12fa280e657458b59ed3f6f0a9de6d_RemoveSiteOrphans.ps1
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue" cls Set-Alias -Name stsadm -Value $env:CommonProgramFiles”\Microsoft Shared\Web Server Extensions\15\BIN\STSADM.EXE” function RemoveOrphanedSites([string]$WebAppUrl, [switch]$ReportOnly) { $configDB = Get-SPDatabase | where {$_.typename -eq "Configuration Database"} $contentDBs = Get-SPWebApplication -IncludeCentralAdministration | Get-SPContentDatabase foreach($contentDB in $contentDBs) { if ($WebAppUrl -ne "" -and $contentDB.WebApplication.Url.StartsWith($WebAppUrl) -eq $false) { continue } $webApplicationUrl = $contentDB.WebApplication.Url Write-Host "webApplicationUrl=" $webApplicationUrl [xml]$allwebs = stsadm -o enumallwebs -databasename $contentDB.Name #$allwebs.OuterXML $OrphanedSites = $allwebs.Databases.Database.site | ?{$_.insitemap -match "false"} Foreach($site in $OrphanedSites) { if ($ReportOnly) { Write-Host "orphaned site, id=" $site.Id ", Url=" $site.Url ", not in sitemap" } else { Write-Host "orphaned site, id=" $site.Id ", Url=" $site.Url ", is removed from " $contentDB.Name $contentDB.ForceDeleteSite($site.Id, $false, $false) } } } } Start-SPAssignment -Global #RemoveOrphanedSites "http://spserver.local" –ReportOnly RemoveOrphanedSites "https://win12r2.tinman.local" Stop-SPAssignment -Global Write-Host "" Write-Host "Finished! Press enter key to exit." -ForegroundColor Green #Read-Host
PowerShellCorpus/GithubGist/bmccormack_1877128_raw_89090b996f9303acec5586f0340eca57f655e67c_churnQueue.ps1
bmccormack_1877128_raw_89090b996f9303acec5586f0340eca57f655e67c_churnQueue.ps1
function get-queueLength(){ try { $s = (New-Object net.webclient).DownloadString('http://localhost:56785/stats.json') } catch { return "queue length unavailable" } $queueLength = $s -split (',') | foreach{if ($_ | select-string "queueLength" -quiet){ ($_ -split ":")[1]}} return $queueLength } function churn-queue(){ pushd cd "C:\Program Files\Kiln\queue" # We want to stop the Kiln Queuing Service because we're going to be running it # manually. write "---------------- Stopping Queuing Service ----------------" sc.exe stop "Kiln Queuing Service" $continue = $true $restartKss = $false # We're going to loop until we're out of work for the queue service. while ($continue){ if ($restartKss) { # With the QueueService hammering Redis, this can cause Redis to fail at the # network level. This causes the Queuing Service to fail. Restarting the # Kiln Storage Service restarts Redis so that the Queuing Service can continue. $restartKss = $false write "---------------- Restart Kiln Storage Service ----------------" sc.exe stop "KilnStorageService" sc.exe start "KilnStorageService" } $getQueueLength = $true # The following code is going to process the Queue Service manually, printing the # output. Powershell is then piping the output as a stream, which is tested for # various conditions to determine if the process is working. write "---------------- Churn Through Kiln Queue ----------------" . .\QueueService.exe /verbose /noservice | out-string -stream | foreach{ if ($getQueueLength) { # We'll use get-queueLength (defined above) to query the queue service # stats to see how many items we have left in the queue. This number # should go down over time. We'll query it once each time we start the # Queue Service. $getQueueLength = $false $queueLength = get-queueLength write "---------------- Get Kiln Queue Length ----------------" write "KILN QUEUE LENGTH: $queueLength" } write $_ if($_ | select-string "no work" -quiet){ # If there are no items left for the Queue, we'll see a message that says "no work", # at which point we'll want to exit the entire loop. write "---------------- No more Work in the Queue ----------------" $continue = $false continue } if($_ | select-string "Exception" -quiet){ # If we see the word "Exception", this almost certainly means that Redis has crashed. # We're going set a flag to restart the Kiln Storage Service, then continue to # restart the current loop. The Storage Service will get restarted at the top of # the loop. write "---------------- Exception While Processing the Queue ----------------" $restartKss = $true continue } } } popd }
PowerShellCorpus/GithubGist/roberto-reale_c5db18c5d912e3802461_raw_25dfa13bd41cf2e48437fe7f82104672a1fa4a59_ps_ping_host_list.ps1
roberto-reale_c5db18c5d912e3802461_raw_25dfa13bd41cf2e48437fe7f82104672a1fa4a59_ps_ping_host_list.ps1
# # ping-host-list # # ping a list of hosts # $Host_List_Path = ".\hostlist.txt" # ping a single host Function Ping-Host { param($InputObject = $null) BEGIN {$status = $False} PROCESS { $processObject = $(if ($InputObject) {$InputObject} else {$_}) if( (Test-Connection $processObject -Quiet -count 1)) { $status = $True } else { $status = $False } } END {return $status} } # ping a list of hosts Function Ping-HostList { param($InputObject = $null) PROCESS { Get-Content $InputObject | %{ if (Ping-Host $_) { Write-Host -ForegroundColor green $_ ; } else { Write-Host -ForegroundColor red $_ ; } } } } Ping-HostList $Host_List_Path
PowerShellCorpus/GithubGist/tkmtmkt_2326853_raw_322be0e5fc52c9d4fc332129e7eabc44137a1131_gistfile1.ps1
tkmtmkt_2326853_raw_322be0e5fc52c9d4fc332129e7eabc44137a1131_gistfile1.ps1
Get-Credential | %{ $user = $_.UserName $pass = ConvertFrom-SecureString $_.Password @" <# .SYNOPSIS command with credential #> `$user = "$user" `$pass = ConvertTo-SecureString "$pass" `$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList `$user,`$pass `$cmd = "cmd" `$args = "/?" Start-Process `$cmd `$args -Credential `$cred # vim: set ft=ps1 ts=4 sw=4 et: "@ } | Out-File CommandTemplate.ps1 -Encoding OEM
PowerShellCorpus/GithubGist/racingcow_30b01c5cac47fa0e2f5e_raw_e3e4f7221b26467b8c3aaebfc39d2065148eae96_devmachine.ps1
racingcow_30b01c5cac47fa0e2f5e_raw_e3e4f7221b26467b8c3aaebfc39d2065148eae96_devmachine.ps1
############################################################ # Join domain ############################################################ #Rename-Computer -NewName devmachine -LocalCredential admin #Add-Computer -DomainName CT -Credential CT\dmiller ############################################################ # Boxstarter options ############################################################ $Boxstarter.RebootOk=$true # Allow reboots? $Boxstarter.NoPassword=$false # Is this a machine with no login password? $Boxstarter.AutoLogin=$true # Save my password securely and auto-login after a reboot ############################################################ #basic setup ############################################################ Update-ExecutionPolicy Unrestricted Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions Enable-RemoteDesktop Disable-InternetExplorerESC Disable-UAC Set-TaskbarSmall Write-BoxstarterMessage "Setting time zone to Central Standard Time" & C:\Windows\system32\tzutil /s "Central Standard Time" cinst Microsoft-Hyper-V-All -source windowsFeatures cinst IIS-WebServerRole -source windowsfeatures cinst IIS-HttpCompressionDynamic -source windowsfeatures cinst IIS-WindowsAuthentication -source windowsfeatures cinst DotNet3.5 cinst f.lux if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # Update Windows and reboot if necessary ############################################################ Install-WindowsUpdate -AcceptEula if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # utils, plugins, frameworks, and other miscellany ############################################################ cinst javaruntime cinst webpi cinst mousewithoutborders cinst adobereader cinst flashplayeractivex cinst flashplayerplugin cinst AdobeAIR cinst 7zip cinst zoomit cinst PDFCreator cinst lockhunter cinst windirstat cinst teamviewer cinst ransack if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # communications ############################################################ # cinst HipChat # <- seems to be old adobe air version cinst skype if (Test-PendingReboot) { Invoke-Reboot } cinst tweetdeck ############################################################ # graphics ############################################################ cinst gimp cinst paint.net cinst greenfishiconeditor cinst IrfanView cinst InkScape if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # design ############################################################ cinst freemind if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # development ############################################################ cinst VisualStudio2013Premium -InstallArguments "/Features:'Blend OfficeDeveloperTools WebTools Win8SDK WindowsPhone80'" if (Test-PendingReboot) { Invoke-Reboot } cinst DotNet3.5 # Not automatically installed with VS 2013. Includes .NET 2.0. Uses Windows Features to install. if (Test-PendingReboot) { Invoke-Reboot } cinst resharper if (Test-PendingReboot) { Invoke-Reboot } cinst MsSqlServerManagementStudio2014Express if (Test-PendingReboot) { Invoke-Reboot } cinst NugetPackageExplorer cinst nodejs.install cinst mongodb cinst PhantomJS cinst fiddler4 cinst SublimeText3 cinst Brackets cinst Brackets.Theseus cinst IntelliJIDEA cinst githubforwindows if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # text editors ############################################################ cinst evernote cinst notepadplusplus.install if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # fun! ############################################################ cinst spotify cinst steam if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # browsers ############################################################ cinst GoogleChrome cinst GoogleChrome.Canary cinst Firefox cinst Opera cinst safari cinst lastpass if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # to the cloud! ############################################################ cinst dropbox if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # Items pinned to taskbar ############################################################ Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles86)\Google\Chrome\Application\chrome.exe" Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" if (Test-PendingReboot) { Invoke-Reboot }
PowerShellCorpus/GithubGist/schlarpc_02cf9a2543f7f1df596b_raw_753b584b0b7b333b9e7191577c72c07a7d6ee846_Microsoft.PowerShell_profile.ps1
schlarpc_02cf9a2543f7f1df596b_raw_753b584b0b7b333b9e7191577c72c07a7d6ee846_Microsoft.PowerShell_profile.ps1
(Get-Host).UI.RawUI.WindowTitle = "Windows PowerShell" function Get-DirAlias ([string]$loc) { return $loc.Replace($env:homedrive + $env:homepath, "~") } function prompt { Write-Host "$env:username@$env:computername" -NoNewLine -ForegroundColor Green Write-Host ":" -NoNewLine Write-Host "$(Get-DirAlias($(Get-Location)))" -NoNewLine -ForegroundColor Cyan return "$ " }
PowerShellCorpus/GithubGist/aflyen_10836851_raw_322681446cff7322b57be2fd77feb8ba9b59a9a1_AutoFollowSitesInSharePoint2013.ps1
aflyen_10836851_raw_322681446cff7322b57be2fd77feb8ba9b59a9a1_AutoFollowSitesInSharePoint2013.ps1
# Get UserProfile Manager $site = Get-SPSite -Limit 1 $serviceContext = Get-SPServiceContext($site) $profileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext) $profiles = $profileManager.GetEnumerator() # Iterates through all the user profiles foreach ($profile in $profiles) { $followingManager = New-Object Microsoft.Office.Server.Social.SPSocialFollowingManager($profile) # Create a new social actor object for the site to follow $socialActor = New-Object Microsoft.Office.Server.Social.SPSocialActorInfo $socialActor.ContentUri = "http://intranet/sites/important-news-from-corp" # REPLACE THIS WITH YOUR SITE $socialActor.ActorType = [Microsoft.Office.Server.Social.SPSocialActorType]::Site # Follow the mandatory site if (!$followingManager.IsFollowed($socialActor)) { $followingManager.Follow($socialActor) } }
PowerShellCorpus/GithubGist/jrothmanshore_2346495_raw_0ffc6eb0fb4e669247adde3f858e7a92e48ee356_gistfile1.ps1
jrothmanshore_2346495_raw_0ffc6eb0fb4e669247adde3f858e7a92e48ee356_gistfile1.ps1
# param( [string] $command = $(throw "command is required. example .\memdata.ps1 ""get SOMEKEYNAME""") ) # function readResponse($stream) { $encoding = new-object System.Text.AsciiEncoding $buffer = new-object System.Byte[] 1024 while ($stream.DataAvailable) { $read = $stream.Read($buffer, 0, 1024) Write-Output ($encoding.GetString($buffer, 0, $read)) } } # function callport($remoteHost, $port = 11211) { try { $socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port) if ($socket -eq $null) { return; } $stream = $socket.GetStream() $writer = new-object System.IO.StreamWriter($stream) $writer.WriteLine($command) $writer.Flush() start-sleep -m 500 readResponse $stream } catch [Exception] { $ex = $_.Exception Write-Output ("Error: {0}" -f $ex.Message) } } # all servers in the cluster $servers = @( "SERVER1", "SERVER2", "SERVER3") $servers |% { $remoteHost = [string]$_ Write-Output $remoteHost # change value below to your memcached port if not the default of 11211 # and call callport as callport $remoteHost YourPortNumber callport $remoteHost } # script end
PowerShellCorpus/GithubGist/turp_4007485_raw_3fd222e7e3a156a8ad3bda1cc724a10ca3951b53_downloadBuildVideos.ps1
turp_4007485_raw_3fd222e7e3a156a8ad3bda1cc724a10ca3951b53_downloadBuildVideos.ps1
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath $rss = (new-object net.webclient) #Set the username for windows auth proxy #$rss.proxy.credentials=[system.net.credentialcache]::defaultnetworkcredentials $a = ([xml]$rss.downloadstring("http://channel9.msdn.com/Events/Build/2012/RSS/wmvhigh")) $a.rss.channel.item | foreach{ $url = New-Object System.Uri($_.enclosure.url) $file = $_.creator + "-" + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-") + ".wmv" if (!(test-path $file)) { $file $wc = (New-Object System.Net.WebClient) #Set the username for windows auth proxy #$wc.proxy.credentials=[system.net.credentialcache]::defaultnetworkcredentials $wc.DownloadFile($url, $file) } }
PowerShellCorpus/GithubGist/egomesbrandao_952260_raw_833defc7c1acee47d6e85f557696df5fe1f930e3_RunGallioTestsPS.ps1
egomesbrandao_952260_raw_833defc7c1acee47d6e85f557696df5fe1f930e3_RunGallioTestsPS.ps1
if ( (Get-PSSnapin -Name Gallio -ErrorAction SilentlyContinue) -eq $null ) { Add-PsSnapin Gallio } $result = Run-Gallio "c:\[CAMINHO]\Test.dll" -ReportDirectory "c:[CAMINHO]\TestReports" -ReportTypes "Html" -ShowReports -Filter Type:@args[0] if ($result.Statistics.FailedCount -gt 0) { Write-Warning "Some unit tests have failed." }
PowerShellCorpus/GithubGist/jangeador_b9f46f113fc48c56bddb_raw_dc88acab9237d30842ca2d3244b68af74e4d4dbf_LimitSentMessages.ps1
jangeador_b9f46f113fc48c56bddb_raw_dc88acab9237d30842ca2d3244b68af74e4d4dbf_LimitSentMessages.ps1
# To create a new policy where the users can send to 30 recipients a day # and no more than 1 message per minute, you would use this command: New-ThrottlingPolicy -Name LimitMessagesSent -RecipientRateLimit 30 -MessageRateLimit 1 # To assign it to a user, use this command: Set-Mailbox -Identity user_alias -ThrottlingPolicy LimitMessagesSent
PowerShellCorpus/GithubGist/jmoberly_6394984_raw_55bf27f701dcd5f1afe725004d1371a649f92a87_ProgressBarExample.ps1
jmoberly_6394984_raw_55bf27f701dcd5f1afe725004d1371a649f92a87_ProgressBarExample.ps1
$thingsArray = 0,1,2,3,4,5,6,7,8,9 $i = 0 foreach($thing in $thingsArray) { Start-Sleep -s 1 $i++ $complete = $i / $thingsArray.Length * 100 Write-Progress -activity "Retrieving things..." -status "Percent found: " -PercentComplete $complete }
PowerShellCorpus/GithubGist/sneal_de23df76382708b132ce_raw_553835e9d6c660ad820a7c1f340e17b1b5dce471_instal-chef.ps1
sneal_de23df76382708b132ce_raw_553835e9d6c660ad820a7c1f340e17b1b5dce471_instal-chef.ps1
$download_url = 'https://opscode-omnibus-packages.s3.amazonaws.com/windows/2008r2/x86_64/chef-client-11.12.4-1.windows.msi' (New-Object System.Net.WebClient).DownloadFile($download_url, 'C:\\Windows\\Temp\\chef.msi') Start-Process 'msiexec' -ArgumentList '/qb /i C:\\Windows\\Temp\\chef.msi' -NoNewWindow -Wait
PowerShellCorpus/GithubGist/mopsusm_9dfd3972f3670d33752c_raw_e9506f21f4098558c2e6454621de4ac6ebe8c9d7_BasicBox.ps1
mopsusm_9dfd3972f3670d33752c_raw_e9506f21f4098558c2e6454621de4ac6ebe8c9d7_BasicBox.ps1
# To Start http://boxstarter.org/package/url?Raw-Gist-URL cinst chocolatey cinst boxstarter #try { # Install AV cinst MicrosoftSecurityEssentials # Always install Updates Install-WindowsUpdate -AcceptEula if (Test-PendingReboot) { Invoke-Reboot } # Windows 8 options # Set-StartScreenOptions -EnableBootToDesktop -DisableDesktopBackgroundOnStart -DisableSearchEverywhereInAppsView # Set-CornerNavigationOptions -DisableUpperRightCornerShowCharms -DisableUpperLeftCornerSwitchApps -EnableUsePowerShellOnWinX # Configure basic system settings (win 7 & 8) Update-ExecutionPolicy RemoteSigned Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions Set-TaskbarOptions -Size Small -Lock #-Dock Right Enable-RemoteDesktop & C:\Windows\system32\tzutil /s "Eastern Standard Time" cinst TelnetClient -source windowsFeatures # Install MS Programs $MSProgs = ("powershell4", "pscx", "psget", "PSWindowsUpdate", "microsoft-message-analyzer") foreach ($ms in $MSProgs){ cinst $ms } # Install 3rd Party Apps $3rdPartyApps = ("7zip", "bleachbit", "filezilla", "putty", "sysinternals", "waterfox", "google-chrome-x64") foreach ($3rd in $3rdPartyApps) { cinst $3rd } <# Write-ChocolateySuccess 'boxstarter.desktop' } catch { Write-ChocolateyFailure 'boxstarter.desktop' $($_.Exception.Message) throw } #>
PowerShellCorpus/GithubGist/Sakuramochi_5245292_raw_36d46b55be3697896a3380b7b06ea607912ceef0_excel_macro_run.ps1
Sakuramochi_5245292_raw_36d46b55be3697896a3380b7b06ea607912ceef0_excel_macro_run.ps1
############################################################ # 動作未確認 動くかわからん # this script do not work # 手元にexcelないからテストできませんでした。 ############################################################ # excelのマクロを実行するスクリプト # 言語 # Windows Powershell # 書式 # excel_macro_run # オプション # $file_name_A excelファイルA # $sheet_name_A ファイルAのシート名 # start_col_A start_row_A A左上行列番号 # end_col_A end_row_A A右下行列番号 # $file_name_B excelファイルB # $sheet_name_B ファイルBのシート名 # start_col_B start_row_B B左上行列番号 # end_col_B end_row_B B右下行列番号 # $macro_name マクロ名 # 概要 # ファイルAの内容をBへコピーして、Bのマクロを実行する param( $file_name_A = ".\file_A.xls", $sheet_name_A = "Sheet1", ` [int] $start_row_A = 1, [int] $start_col_A = 1, ` [int] $end_row_A = 10, [int] $end_col_A = 2, ` $file_name_B = ".\file_B.xls", $sheet_name_B = "Sheet2", ` [int] $start_row_B = 2, [int] $start_col_B = 1, ` [int] $end_row_B = 11, [int] $end_col_B = 2, ` $macro_name = "macro1" ) # デバッグ出力設定 #$DebugPreference = "Continue" $DebugPreference = "SilentlyContinue" # ======================================================= # # excel用のオブジェクト生成 $excel = New-Object -ComObject Excel.Application # 非表示モード $excel.Visible = $false <# # ファイルA操作 #> if( !(Test-Path $file_name_A) ) { Write-Host "$file_name_A not exits." exit } $file_name_A = Convert-Path $file_name_A # ファイルAを読み取り専用で開く $book_A = $excel.workbooks.Open( $file_name_A, 0, $true ) $sheet_A = $book_A.worksheets.Item( $sheet_name_A ) # ファイルA データ取得 $data_A = New-Object "object[,]" ` ($end_row_A - $start_row_A + 1),($end_col_A - $start_col_A + 1) $ar_row = 0 For( $row_cnt=$start_row_A; $row_cnt -le $end_row_A; $row_cnt++ ) { $ar_col = 0 For( $col_cnt=$start_col_A; $col_cnt -le $end_col_A; $col_cnt++ ) { $data_A[$ar_row,$ar_col] = $sheet_A.Cells.Item( $row_cnt, $col_cnt ).Text $ar_col++ } $ar_row++ } # ファイルAを閉じる 保存しないで終了 $book_A.Close($false) $book_A = $Null <# # ファイルB操作 #> if( !(Test-Path $file_name_B) ) { Write-Host "$file_name_B not exits." exit } $file_name_B = Convert-Path $file_name_B # ファイルBを開く $book_B = $excel.workbooks.Open( $file_name_B ) $sheet_B = $book_B.worksheets.Item( $sheet_name_B ) # ファイルAデータをファイルBへペースト $ar_row = 0 For( $row_cnt=$start_row_B; $row_cnt -le $end_row_B; $row_cnt++ ) { $ar_col = 0 For( $col_cnt=$start_col_B; $col_cnt -le $end_col_B; $col_cnt++ ) { $sheet_B.Cells.Item( $row_cnt, $col_cnt ) = $data_A[$ar_row,$ar_col] $ar_col++ } $ar_row++ } # マクロ実行 $ret = $sheet_B.Active $excel.run( $macro_name ) #$excel.run( $macro_name, "パラメタ1", "パラメタ2" ) # 保存して終了 $book_B.Save() $book_B.Close() $book_B = $Null # excel終了 $excel.quit() trap{ # close file & exit if( $book_A -ne $Null ) { $book_A.Close } if( $book_B -ne $Null ) { $book_B.Close } $excel.quit() }
PowerShellCorpus/GithubGist/josheinstein_3171994_raw_912c78b3a99799127151bf8f63e9b2139921f3ab_expand-numbers.ps1
josheinstein_3171994_raw_912c78b3a99799127151bf8f63e9b2139921f3ab_expand-numbers.ps1
Set-Location ~\Dropbox\Work\Journal\201207 Import-CSV numbers.csv -Header From,To | %{ if ($_.From -match '^\d+$') { [Int64]$From = $_.From [Int64]$To = $(if ($_.To) { $_.To } else { $From }) [Int64]$i = $From while ($i -le $To) { Write-Output $i $i += 1 } } } | Sort | sc numbers.txt
PowerShellCorpus/GithubGist/taddev_3962957_raw_250a9853155415f9afa7b3074abe14b641ab2d2a_InputTest.ps1
taddev_3962957_raw_250a9853155415f9afa7b3074abe14b641ab2d2a_InputTest.ps1
param( [switch]$parent, [switch]$child, [switch]$help, [string]$template ); function displayHelp() { echo "Input is piped in from the command line.`nThis script will process some stuff"; echo "Parameters:`n"; echo "`t-child`tProcess the child nodes"; echo "`t-parent`tProcess the parent nodes"; echo "`nExample:"; echo "`t1,2,3|.\InputTest.ps1 -child -parent"; } $count = @($input).Count; $input.Reset(); if( ( !$parent -and !$child ) -or $help -or ( $count -eq 0 ) -or ( $template.CompareTo("") -eq 0 ) ) { displayHelp; break; } else { if( $parent ) { echo "You selected Parent"; } if( $child ) { echo "You selected Child"; } echo $template"\_child"; echo "You piped $count values."; foreach( $numb in $input ) { echo "Input was: $numb"; } } # SIG # Begin signature block # MIIbaQYJKoZIhvcNAQcCoIIbWjCCG1YCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUzk/jO+iw3dAX9bmQ9rQvQ2+3 # kWugghYbMIIDnzCCAoegAwIBAgIQeaKlhfnRFUIT2bg+9raN7TANBgkqhkiG9w0B # AQUFADBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xKzAp # BgNVBAMTIlZlcmlTaWduIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EwHhcNMTIw # NTAxMDAwMDAwWhcNMTIxMjMxMjM1OTU5WjBiMQswCQYDVQQGEwJVUzEdMBsGA1UE # ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xNDAyBgNVBAMTK1N5bWFudGVjIFRpbWUg # U3RhbXBpbmcgU2VydmljZXMgU2lnbmVyIC0gRzMwgZ8wDQYJKoZIhvcNAQEBBQAD # gY0AMIGJAoGBAKlZZnTaPYp9etj89YBEe/5HahRVTlBHC+zT7c72OPdPabmx8LZ4 # ggqMdhZn4gKttw2livYD/GbT/AgtzLVzWXuJ3DNuZlpeUje0YtGSWTUUi0WsWbJN # JKKYlGhCcp86aOJri54iLfSYTprGr7PkoKs8KL8j4ddypPIQU2eud69RAgMBAAGj # geMwgeAwDAYDVR0TAQH/BAIwADAzBgNVHR8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DQYJKoZIhvcNAQEBBQAEgYAbGxImvpw349CQWR1526Org2En # f6/A0o4GpALQWXDmCWoH0Br7D1/nfStcsgl7zLquWEGQWFQf4HBRh5vI7UqNLRsR # haBhXjqZeVBYXTIL+QKTRPNiHPR46pcz7u3b/5phIxSzy82wCsIqV0JS2dM7rixw # Pk1//fQCyg+7LP3CXQ== # SIG # End signature block
PowerShellCorpus/GithubGist/MikaelSmith_d885c72dd87e61e3f969_raw_bd01c6502e6699185ff0886afffc52b58695c7be_build_cfacter_win.ps1
MikaelSmith_d885c72dd87e61e3f969_raw_bd01c6502e6699185ff0886afffc52b58695c7be_build_cfacter_win.ps1
# Starting from a base Windows Server 2008r2 or 2012r2 installation, install required tools, setup the PATH, and download and build software. # This script can be run directly from the web using "iex ((new-object net.webclient).DownloadString('<url_to_raw>'))" ### Configuration ## Setup the working directory $sourceDir=$pwd ## Set the number of cores to use for parallel builds $cores=2 ## Choose whether to download pre-built libraries or build from source $buildSource=$FALSE ## Choose 32 or 64-bit build $arch=64 $mingwVerNum = "4.8.3" $mingwVerChoco = "${mingwVerNum}.20141208" $mingwThreads = "posix" if ($arch -eq 64) { $mingwExceptions = "seh" $mingwArch = "x86_64" } else { $mingwExceptions = "dwarf" $mingwArch = "i686" } $mingwVer = "${mingwArch}_mingw-w64_${mingwVerNum}_${mingwThreads}_${mingwExceptions}" $boostVerNum = "1.55.0" $boostVer = "boost_$(${boostVerNum}.Replace('.', '_'))" $boostPkg = "${boostVer}-${mingwVer}" $yamlCppVerNum = "0.5.1" $yamlCppVer = "yaml-cpp-${yamlCppVerNum}" $yamlPkg = "${yamlCppVer}-${mingwVer}" ### Setup, build, and install ## Install Chocolatey, then use it to install required tools. iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) choco install 7zip.commandline cmake git ruby python doxygen.install choco install mingw -Version "${mingwVerChoco}" $env:PATH = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") cd $sourceDir ## Download cfacter and setup build directories git clone --recursive https://github.com/puppetlabs/cfacter mkdir -Force cfacter\release\ext cd cfacter\release $buildDir=$pwd cd ext $toolsDir=$pwd if ($buildSource) { ## Download, build, and install Boost (New-Object net.webclient).DownloadFile("http://iweb.dl.sourceforge.net/project/boost/boost/$boostVerNum/$boostVer.7z", "$toolsDir\$boostVer.7z") & 7za x "${boostVer}.7z" | FIND /V "ing " cd $boostVer .\bootstrap mingw $args = @( 'toolset=gcc', "--build-type=minimal", "install", "--with-program_options", "--with-system", "--with-filesystem", "--with-date_time", "--with-thread", "--with-regex", "--with-log", "--with-locale", "--prefix=`"$toolsDir\$boostPkg`"", "boost.locale.iconv=off" "-j$cores" ) .\b2 $args cd $toolsDir ## Download, build, and install yaml-cpp (New-Object net.webclient).DownloadFile("https://yaml-cpp.googlecode.com/files/${yamlCppVer}.tar.gz", "$toolsDir\${yamlCppVer}.tar.gz") & 7za x "${yamlCppVer}.tar.gz" & 7za x "${yamlCppVer}.tar" | FIND /V "ing " cd $yamlCppVer mkdir build cd build $args = @( '-G', "MinGW Makefiles", "-DBOOST_ROOT=`"$toolsDir\$boostPkg`"", "-DCMAKE_INSTALL_PREFIX=`"$toolsDir\$yamlPkg`"", ".." ) cmake $args mingw32-make install -j $cores cd $toolsDir } else { ## Download and unpack Boost from a pre-built package in S3 (New-Object net.webclient).DownloadFile("https://s3.amazonaws.com/kylo-pl-bucket/${boostPkg}.7z", "$toolsDir\${boostPkg}.7z") & 7za x "${boostPkg}.7z" | FIND /V "ing " ## Download and unpack yaml-cpp from a pre-built package in S3 (New-Object net.webclient).DownloadFile("https://s3.amazonaws.com/kylo-pl-bucket/${yamlPkg}.7z", "$toolsDir\${yamlPkg}.7z") & 7za x "${yamlPkg}.7z" | FIND /V "ing " } ## Build CFacter cd $buildDir $args = @( '-G', "MinGW Makefiles", "-DBOOST_ROOT=`"$toolsDir\$boostPkg`"", "-DYAMLCPP_ROOT=`"$toolsDir\$yamlPkg`"", "-DBOOST_STATIC=ON", ".." ) cmake $args mingw32-make -j $cores
PowerShellCorpus/GithubGist/sunnyc7_9278563_raw_85c7faf65d3d2d460794af4bfe8550c4138a69fe_roger-params.ps1
sunnyc7_9278563_raw_85c7faf65d3d2d460794af4bfe8550c4138a69fe_roger-params.ps1
$s = New-PSSession -ComputerName servermaame #I am using PID 0,4, assigned to System and Idle for testing, as they are always available. $pid1 = 4 $processId = 0 # CASE: Remote session variable, but no argument list to pass. # This wont work, because there is no argument list assignment to pass to the scriptblock Invoke-Command -Session $s -Script { param($processId) Get-Process -Id $processId } # CASE: Local Variable passed to remote session. # This works. $pid1 (local variable), is passed to $processid in remote computer # Pass by Reference Invoke-Command -Session $s -Script { param($processId) Get-Process -Id $processId } -Args $pid1 # CASE: Remote Session variable only. We cant guess which remote processid is active. # This works. Scriptblock is using $PID system variabe assigned to the powershell HOST. # There is no local to remote session variable passing. # Passed Remotely *only* Invoke-Command -Session $s -Script { Get-Process -Id $pid} # CASE: Remote Session variable only. We cant guess which remote processid is active. # This doesnt work on my system, as no process id 7808 exists remotely. # $pid 7808 is defined locally, and is being passed by Value. # Pass by Value Invoke-Command -Session $s -Script { Get-Process -Id $args[0]} -Args $pid # CASE: Remote Session variable passed using $args[0]. # This works. # Passed by Reference. Invoke-Command -Session $s -Script { Get-Process -Id $args[0]} -Args $pid1
PowerShellCorpus/GithubGist/rhysgodfrey_0285a5e816e5f64fdfca_raw_6bf8eed7a93363798d4dbc1042a0b5f36a4785c5_aws-quick-start-demo-prerequisites.ps1
rhysgodfrey_0285a5e816e5f64fdfca_raw_6bf8eed7a93363798d4dbc1042a0b5f36a4785c5_aws-quick-start-demo-prerequisites.ps1
Set-AWSCredentials -AccessKey ACCESS-KEY -SecretKey SECRET-KEY -StoreAs AWSQuickStartDemo Initialize-AWSDefaults -ProfileName AWSQuickStartDemo -Region eu-west-1
PowerShellCorpus/GithubGist/jgable_884312_raw_16747896e8cb2de9a789fbc889d31f4ab7e644e0_Gist4u2.ps1
jgable_884312_raw_16747896e8cb2de9a789fbc889d31f4ab7e644e0_Gist4u2.ps1
# Serializer loader $extAssembly = [Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") $serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer # Url's formatted $gistUserListUrlForm = "http://gist.github.com/api/v1/json/gists/{0}"; $gistInfoUrlForm = "http://gist.github.com/api/v1/json/{0}"; $gistContentsUrlForm = "http://gist.github.com/raw/{0}/{1}"; # Json downloader $webClient = New-Object System.Net.WebClient # Json Parser function parseJson([string]$json, [bool]$throwError = $true) { try { $result = $serializer.DeserializeObject( $json ); return $result; } catch { if($throwError) { throw "ERROR: Parsing Error"} else { return $null } } } function downloadString([string]$stringUrl) { try { return $webClient.DownloadString($stringUrl) } catch { throw "ERROR: Problem downloading from $stringUrl" } } function parseUrl([string]$url) { return parseJson(downloadString($url)); } function downloadUserGists([string]$userName) { return parseUrl([string]::Format($gistUserListUrlForm, $userName)) } function downloadGistInfo([string]$gistId) { return parseUrl([string]::Format($gistInfoUrlForm, $gistId)) } function downloadGistFile([string]$gid, [string]$fname) { return downloadString([string]::Format($gistContentsUrlForm, $gid, $fname)) } function List-Gists { param ([string]$user = '') if([string]::IsNullOrEmpty($user)) { 'ERROR: Must Specify User' } else { $userGists = downloadUserGists($user) if($userGists -eq $null) { 'ERROR: Nothing Found' } else { $userGists.gists | % { $names = '' $_.files | % { $names = "$names, $_" } [string]::Format("Id({0}): Files[{1}]", $_.repo, $names.SubString(2)) } } } } function Gist-Info { param ([string]$gistId = '') if([string]::IsNullOrEmpty($gistId)) { "ERROR: Must Provide Gist Id" return; } $gist = downloadGistInfo($gistId) if($gist -eq $null -or $gist.gists -eq $null -or $gist.gists.Length -lt 1) { "ERROR: Gist Not Found with Id $gistId" return; } $g = $gist.gists[0] $repo = $g.repo $owner = $g.owner $created_at = $g.created_at $description = $g.description " Id: $repo" " Owner: $owner" " Created: $created_at" "Description: $description" " Files: " $g.files | % { " - $_" } } function Gist-Contents { param ([string]$gistId = '', [string]$fileName = '') if([string]::IsNullOrEmpty($gistId)) { "ERROR: Must provide Gist Id" return; } elseif([string]::IsNullOrEmpty($fileName)) { "ERROR: Must provide file name" return; } $file = downloadGistFile $gistId $fileName return $file } function Gist-Insert { param ([string]$gistId = '', [string]$fileName = '') if([string]::IsNullOrEmpty($gistId)) { "ERROR: Must provide Gist Id" return; } elseif([string]::IsNullOrEmpty($fileName)) { $gist = downloadGistInfo($gistId) if($gist -eq $null -or $gist.gists -eq $null -or $gist.gists.Length -lt 1) { "ERROR: Gist Not Found with Id $gistId" return; } $fileName = $gist.gists[0].files[0] "WARN: No file name provided, defaulting to first file [$fileName]" } $contents = Gist-Contents $gistId $fileName if($dte -eq $null -or $dte.ActiveDocument -eq $null -or $dte.ActiveDocument.Selection -eq $null) { "ERROR: Cannot Insert into Document, make sure a document is open and the cursor is where you want the file inserted." return; } $tempName = [System.IO.Path]::GetTempFileName() Set-Content $tempName $contents $dte.ActiveDocument.Selection.InsertFromFile($tempName) $dte.ActiveDocument.Selection.SelectAll() $dte.ActiveDocument.Selection.SmartFormat() del $tempName }
PowerShellCorpus/GithubGist/Gunslap_223ada0870c3d5ce89c9_raw_33eae28a20dbb4b7407eac39baf8b344715c3afe_AccountDisablerFunction.ps1
Gunslap_223ada0870c3d5ce89c9_raw_33eae28a20dbb4b7407eac39baf8b344715c3afe_AccountDisablerFunction.ps1
<# .SYNOPSIS This function disables accounts that are older than a certain threshhold. .DESCRIPTION Searches active directory for users based on an inputted searchbase for users that haven't logged in since a certain threshhold or haven't logged in ever and were created before that threshhold and disables them and marks in their description when and why they were disabled. .PARAMETER $SearchBase This is where to search in Active Directory. Must be in DN form: "ou=x,ou=x,dc=x,dc=x". .PARAMETER NbDays This is the number of days a user must be inactive for to require disabling .PARAMETER LogFile The location of the logfile. If a file is not present in that location, it will attempt to make it. .PARAMETER emailTo The email address to send general results to (never as thorough as logging) .PARAMETER server The AD Domain Controller to search from. .EXAMPLE FindAndDisable-Accounts -SearchBase "ou=Students,dc=Contoso,dc=com" -nbDays 100 -LogFile "\\Contososerver\scriptlogs$\DisabledStudentsLog.txt" -Verbose This will search in the OU Students in the Contoso.com domain, that are inactive for 100 days, and verbosely log to the logfile specified. #> function FindAndDisable-Accounts { [CmdLetBinding()] Param( [string]$SearchBase = "Nothing", [string]$NbDays = 365, [string]$LogFile, [string]$emailTo = "help@spiritsd.ca", [string]$server = "ACDC" ) #Create the Log File if it doesn't already exist if (-not (Test-Path $LogFile)) { New-Item $LogFile -ItemType file } #Get the current date #Convert the local time to UTC format (because all dates are expressed in UTC [GMT] format in Active Directory) $CurrentDate = (Get-Date).ToUniversalTime() #Calculate the time stamp in Large Integer format using the $NbDays specified above #LastLogonThreshhold holds the cutoff time for disabling $LastLogonThreshhold = ($CurrentDate.AddDays(- $NbDays)).ToFileTimeUtc() #Initialize the string for the body of the email report #Write out the header information to the log file $EmailBody = "Disabling Accounts Output`r`n" + $CurrentDate.Date + "`r`n*************************************`r`n" $EmailBody >> $LogFile $EmailBody += "For more information see the logfile at $LogFile" #Get all users to work with $Users = get-aduser -server $server -Filter * -SearchBase $SearchBase -Properties * #Get all the properties that we need for those users $Users = $Users | Select-Object -Property SamAccountName,Name,CN,DisplayName,lastLogonTimestamp,DistinguishedName,whenCreated,Enabled foreach ($user in $Users) { #initialize output and get the lastlogontimestamp for readability later $Output = "" $LastLogonTimeStamp = $user.lastLogonTimeStamp #set the LastLogonTimeStamp to when the user was created if it is null. This occurs when the user hasn't logged in. if($LastLogonTimeStamp -eq $null) { $LastLogonTimeStamp = ($user.whenCreated).toFileTime() } #set readable values for printing of the lastLogonTimeStamp and Threshhold #these are used in logging only, and 1600 years must be added to make them the proper year $ReadableLastLogonTimeStamp = ([System.Datetime]$LastLogonTimeStamp).AddYears(1600) $ReadableLastLogonThreshold = ([System.Datetime]$LastLogonThreshhold).AddYears(1600) #Bypass any users that are disabled or are in the _Disabled OU if (($user.Enabled -eq $false) -or ($user.DistinguishedName -match "OU=_DISABLED")) { $Output = "Bypassing " + $user.DisplayName + " as it is already disabled." #4>&1 pipes VERBOSE output into standard output, and >> pipes standard output to append to the specified destination Write-Verbose $Output 4>&1 >> $LogFile #$EmailBody += $Output } #if any of the name fields start with an underscore, that denotes an account we do not want changed elseif ( ($user.Name -like "_*") -or ($user.CN -like "_*") -or ($user.DisplayName -like "_*") ) { $Output = "Skipping " + $user.DisplayName + " (" + $user.SamAccountName + ") for one of it's names starting with an underscore." Write-Verbose $Output 4>&1 >> $LogFile #$EmailBody += $Output } #compare the lastlogontimestamp to the threshhold value (determined earlier by nbDays) #in the case the user hasn't logged in, lastLogonTimeStamp will have been set to the date their account was created elseif ($LastLogonTimeStamp -lt $lastLogonThreshhold) { #at this point, it meets the criteria of being disabled $Output = "Changing " + $user.DisplayName + " (" + $user.SamAccountName + "). Last Logon is " + $ReadableLastLogonTimeStamp + ". Threshhold is $ReadableLastLogonThreshold" Write-Output $Output >> $LogFile $EmailBody += $Output Disable-Account -UserToDisable $user -LogFileLocation $LogFile -IsStudent $isStudent.IsPresent -friendlyDate $ReadableLastLogonTimeStamp } #this case does not meet the disabling criteria so there is no need to change it. else { $Output = "Not Changing " + $user.DisplayName + " (" + $user.SamAccountName + "). Last logon is " + $ReadableLastLogonTimeStamp + ". Threshhold is $ReadableLastLogonThreshold" Write-Verbose $Output 4>&1 >> $LogFile #Shouldn't need to email this part. #$EmailBody += $Output } } #Email list of changes made to the helpdesk: $emailFrom = "no-reply@contoso.com" $subject = "Disabled Users Report for - $CurrentDate" $smtpServer = "smtp.contoso.com" $smtp = new-object Net.Mail.SmtpClient($smtpServer) $smtp.Send($emailFrom, $emailTo, $subject, $Emailbody) } function Disable-Account { param( $UserToDisable, $LogFileLocation, $isStudent, $friendlyDate ) #get the current date $CurrentDate = Get-Date #get the user speicifed and set their account to disabled and their description to indicate the dates Get-ADUser $UserToDisable.SamAccountName | Set-ADUser -Enabled $False -Description "DISABLED: $CurrentDate - LAST LOGON: $friendlyDate" #-WhatIf #move their documents to the _old_user_accounts folder on their server Move-Documents -UserToDisable $UserToDisable -LogFileLocation $LogFileLocation -isStudent $isStudent } function Move-Documents { param( $UserToDisable, $LogFileLocation, ) #get the nsid $samAccountName = $UserToDisable.SamAccountName $profile_folders = "\\$Server\ProfilesShare$" $home_folders = "\\$Server\HomeShare$" #make a hashtable of the folders needed $array_folders = ($profile_folders,$home_folders) foreach ($folder in $array_folders) { Write-Host "Scanning $folder..." #get the folder itself $MainFolders = Get-ChildItem -Path $folder -Force foreach ($SubFolder in $MainFolders) { #if the account name matches the foldername and the folder isn't in the old_user_accounts folder already if (($samAccountName | Select-String -Pattern $SubFolder) -and ($SubFolder -notlike "*_Old_user_accounts*")) { #move and log the move Write-Host "The user's folder: $SubFolder exists in: $folder" $Output = "--> Moving the folder $folder\$SubFolder to _Old_user_accounts folder `r" Write-Host $Output Write-Output $Output >> $LogFileLocation #Make sure the _Old_user_accounts folder exists: if (-not (Test-Path $folder\_Old_user_accounts)) { New-Item ("$folder\_Old_user_accounts") -type directory } Move-Item -Path $folder\$SubFolder $folder\_Old_user_accounts\$samAccountName\ -Force #-WhatIf } } } } #Sample Run: #FindAndDisable-Accounts -SearchBase "ou=Users,dc=contoso,dc=com" -nbDays 365 -LogFile "\\ContosoServer\e$\_Logs\DisabledUserssLog.txt" #-Verbose
PowerShellCorpus/GithubGist/ctrlbold_63e3d97042f7185b2bc7_raw_373b094c9ae9a8b3f3bb75279a7afbfc949e3b82_advanced-datatable.ps1
ctrlbold_63e3d97042f7185b2bc7_raw_373b094c9ae9a8b3f3bb75279a7afbfc949e3b82_advanced-datatable.ps1
# Create Basic Datatable $datatable = New-Object System.Data.Datatable [void]$datatable.Columns.Add("name") [void]$datatable.Columns.Add("directory") [void]$datatable.Columns.Add("bytes", [double]) # Add data [void]$datatable.Rows.Add("locate","C:",1.0) [void]$datatable.Rows.Add("Backup","C:\locate",1.0) [void]$datatable.Rows.Add("Invoke-Locate.ps1","C:\locate",39630.0) [void]$datatable.Rows.Add("System.Data.SQLite.dll","C:\locate",1122304.0) [void]$datatable.Rows.Add("install.png","C:\locate\Backup",22151.0) [void]$datatable.Rows.Add("Installandsearch.png","C:\locate\Backup", 34596.0) [void]$datatable.Rows.Add("invoke-locate-directory.png","C:\locate\Backup",47251.0) [void]$datatable.Rows.Add("Invoke-Locate-install-search.png","C:\locate\Backup",34596.0) [void]$datatable.Rows.Add("Invoke-Locate.ps1","C:\locate\Backup",9797.0) [void]$datatable.Rows.Add("locate.sqlite","C:\locate\Backup",0278144.0) [void]$datatable.Rows.Add("locate.xml","C:\locate\Backup",3534.0) [void]$datatable.Rows.Add("measure.png","C:\locate\Backup",10603.0) [void]$datatable.Rows.Add("sctask-output.txt","C:\locate\Backup",57.0) [void]$datatable.Rows.Add("search-verbose.png","C:\locate\Backup",34987.0) [void]$datatable.Rows.Add("search.png","C:\locate\Backup",31919.0) [void]$datatable.Rows.Add("System.Data.SQLite.dll","C:\locate\Backup",1122304.0) [void]$datatable.Rows.Add("Update-LocateDB.ps1","C:\locate\Backup",73.0) # Transform $fullname = $datatable.Columns.Add("fullname") $fullname.Expression = ("directory+'\'+name") $kb = $datatable.Columns.Add("kb",[double]) $kb.Expression = "bytes / 1024" $mb = $datatable.Columns.Add("mb",[double]) $mb.Expression = "kb / 1024" $gb = $datatable.Columns.Add("gb",[double]) $gb.Expression = "mb / 1024" # Get totals [void]$datatable.Columns.Add("totalkb",[int64]) [void]$datatable.Columns.Add("totalmb",[int64]) [void]$datatable.Columns.Add("totalgb",[int64]) foreach ($row in $datatable.rows) { try { $fullname = $row.fullname $where = "fullname like '$fullname\*' or fullname = '$fullname'" $row["totalkb"] = ($datatable.Compute("sum(kb)",$where)) $row["totalmb"] = ($datatable.Compute("sum(mb)",$where)) $row["totalgb"] = ($datatable.Compute("sum(gb)",$where)) } catch { Write-Warning "Could not parse $fullname info." } } # Make totals pretty $totalsize = $datatable.Columns.Add("totalsize") $totalsize.Expression = "IIF(totalkb<1025, totalkb + 'K', IIF(totalmb<1025, totalmb + 'M', totalgb + 'G'))" # Select, and display $datatable | Select totalsize, fullname | Sort-Object fullname | Format-Table -Auto -HideTableHeaders
PowerShellCorpus/GithubGist/dillo_5571126_raw_513632d3e6537d002908764b2342c880115360fb_gistfile1.ps1
dillo_5571126_raw_513632d3e6537d002908764b2342c880115360fb_gistfile1.ps1
#!/bin/sh # # unicorn - this script starts and stops the unicorn processes for Rentals.com # # chkconfig: - 85 15 # description: Unicorn init script # config: /var/www/rl/shared/system/unicorn.rb # pidfile: /var/www/rl/shared/pids/unicorn.pid # Source function library. . /etc/rc.d/init.d/functions unicorn="cd /var/www/webapp/current; bundle exec unicorn" prog="unicorn" env="qa" UNICORN_CONF_FILE="/var/www/rl/shared/system/unicorn.rb" start() { [ -f $UNICORN_CONF_FILE ] || exit 6 echo -n $"Starting unicorn for rl: " daemon --user=deploy $unicorn -c $UNICORN_CONF_FILE -E $env -D retval=$? echo return $retval } stop() { echo -n $"Stopping $prog: " killproc $prog retval=$? echo return $retval } rh_status() { status $prog } rh_status_q() { rh_status >/dev/null 2>&1 } #restart(){ # killall unicorn >& /dev/null && sleep 5 # rm "/var/www/rl/shared/pids/unicorn.pid" >& /dev/null # start #} #orig_restart() { restart() { local pidfile="/var/www/rl/shared/pids/unicorn.pid" local oldbin_pidfile="/var/www/rl/shared/pids/unicorn.pid.oldbin" echo -n $"Starting new master $prog: " if killproc $unicorn -p $pidfile -USR2 -v; then echo sleep 1 if [[ -f ${oldbin_pidfile} && -f ${pidfile} ]]; then echo -n $"Killing old $prog: with pid: `cat ${oldbin_pidfile}`" killproc -p ${oldbin_pidfile} -QUIT retval=$? echo return 0 else echo $"Neither PID file was found. Issuing stop start." stop start fi else echo "Could not kill Unicorn with $pidfile with -USR2" fi } case "$1" in start) rh_status_q && exit 0 $1 ;; stop) rh_status_q || exit 0 $1 ;; restart) $1 ;; status) rh_$1 ;; *) echo $"Usage: $0 {start|stop|restart|status}" exit 2 esac
PowerShellCorpus/GithubGist/janikvonrotz_7806446_raw_c6f666d4e24c6d856db4aa16a587e04532965003_GetSPFarmBuildVersion.ps1
janikvonrotz_7806446_raw_c6f666d4e24c6d856db4aa16a587e04532965003_GetSPFarmBuildVersion.ps1
get-spfarm | select BuildVersion
PowerShellCorpus/GithubGist/ziembor_5267304_raw_f0a630eb549db60b387e882fa2b81750f2af99ef_get-ADUsersWithManagerGroupMemberShips.ps1
ziembor_5267304_raw_f0a630eb549db60b387e882fa2b81750f2af99ef_get-ADUsersWithManagerGroupMemberShips.ps1
$users = get-ADUser -Filter * -Properties manager | where {$_.manager -ne $null} foreach ($user in $users) { $userSAM = $user.SamAccountName $plik = "info_$userSAM.txt" $user | out-file -Append $plik Get-ADPrincipalGroupMembership $user.DistinguishedName | out-file -Append $plik }
PowerShellCorpus/GithubGist/xoner_3891317_raw_aed0d2c2b809d3221d82bdc86095a8206349307a_ChangeExtension.ps1
xoner_3891317_raw_aed0d2c2b809d3221d82bdc86095a8206349307a_ChangeExtension.ps1
foreach ($itFile in ls *.markdown) { if ($itFile -match '(.*)\.(\w+)') { Write-Host 'Renaming ' $itFile $destFile = $Matches[1] + '.md' mv $itFile $destFile } }
PowerShellCorpus/GithubGist/rhb21_6508805_raw_c8b85a88e9914e24b05d57b2ed9ed9d7257d3816_Create-PluginInstaller.ps1
rhb21_6508805_raw_c8b85a88e9914e24b05d57b2ed9ed9d7257d3816_Create-PluginInstaller.ps1
############################ # # Expected plugin directory structure: # $pluginDir # |-<org_0> # ||-<plugin_0> # |||-<plugin_files> # ||-<plugin_1> # |||-<plugin_files> # ||-<plugin_2> # |||-<plugin_files> # |-<org_1> # ||-<plugin_0> # |||-<plugin_files> # etc. # # other files below $plugins directory will be included, eg READMEs # ############################ param( $plugins = ("{0}\\Plugins" -f (get-location)), $out = "SamplePlugin.msi", $wix = "C:\\Program Files\\Windows Installer XML", $loc = "$wix\\WixUI_en-us.wxl", $lib = "$wix\\WixUI.wixlib", $ui_ref = "WixUI_Mondo", $title = "UserPlugins", $manufacturer = "Default Manufacturer", $description = "XenCenter Plugins", $product_version = "1.0.0", $upgrade_code = "8282b90a-cb51-4c02-a1c1-ecfcff9861bf", $product_code = ([System.Guid]::NewGuid().ToString()), $version_short = "1.0", $icon, [switch]$debug, [switch]$help ); if($help) { write-host @" PluginInstaller Creator: Create-PluginInstalller [-plugins] <top folder path> [-out] <name of output msi> [-wix <location of wix binaries>] [-loc <location of wix strings>] [-lib <wix ui description library>] [-ui_ref <Wix UI reference>] [-title <name of installation>] [-manufacturer <plugin manufacturer>] [-description <description of plugins>] [-product_version <plugin version>] [-upgrade_code <guid for upgrading>] [-product_code <guid of product>] [-version_short <two number version>] [-icon <path to add/remove programs icon>] [-debug] [-help] "@ return; } #$wix_template = "{0}\\InstallerTemplate.wxs" -f (get-location); ########################################## # # Template for .wxs file # $template = @" <?xml version="1.0" encoding="UTF-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2003/01/wi"> <?define ProductVersion="<?version-long>" ?> <?define UpgradeCode="{8282b90a-cb51-4c02-a1c1-ecfcff9861bf}"?> <?define ProductCode="{67d68e4a-82d2-4a7d-a909-cfce92dbe71a}"?> <?define VersionShort="<?version-short>" ?> <Product Id='`$(var.ProductCode)' Name="UserPlugins" Language="1033" Version='`$(var.ProductVersion)' Manufacturer="Default Manufacturer" UpgradeCode='`$(var.UpgradeCode)'> <Package Id="????????-????-????-????-????????????" Description="XenCenter Plugins" InstallerVersion="200" Compressed="yes" /> <Media Id="1" Cabinet="UserPlugins.cab" EmbedCab="yes" /> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="ProgramFilesFolder"> <Directory Id="Citrix" Name="Citrix"> <Directory Id="INSTALLDIR" Name="XenCente" LongName="XenCenter"> <Directory Id="XCPlugins" Name="Plugins" /> </Directory> </Directory> </Directory> <Directory Id='ProgramMenuFolder' /> <Directory Id='DesktopFolder' /> </Directory> <UIRef Id="WixUI_ErrorProgressText" /> <Property Id="Install_All" Value="0" /> <Property Id='INSTALLDIR'> <RegistrySearch Id='XenCenterRegistryLM' Type='raw' Root='HKLM' Key='Software\Citrix\XenCenter' Name='InstallDir' /> <RegistrySearch Id='XenCenterRegistryCU' Type='raw' Root='HKCU' Key='Software\Citrix\XenCenter' Name='InstallDir' /> </Property> <Property Id="WIXUI_INSTALLDIR" Value="INSTALLDIR" /> <Property Id='FRAMEWORK20'> <RegistrySearch Id='Framework20Registry' Type='raw' Root='HKLM' Key='Software\Microsoft\NET Framework Setup\NDP\v2.0.50727' Name='Install' /> </Property> <Property Id='POWERSHELL10'> <RegistrySearch Id='PowerShell10Registry' Type='raw' Root='HKLM' Key='Software\Microsoft\PowerShell\1' Name='Install' /> </Property> <Property Id="ARPPRODUCTICON" Value="XenCenterICO" /> <Upgrade Id='`$(var.UpgradeCode)'> <UpgradeVersion Property='UPGRADEFOUND' ExcludeLanguages='yes' Minimum='0.0.0' IncludeMinimum='yes' Maximum='`$(var.ProductVersion)' IncludeMaximum='yes' /> <UpgradeVersion OnlyDetect='yes' ExcludeLanguages='yes' Property='NEWERPRODUCTFOUND' Minimum='`$(var.ProductVersion)' IncludeMinimum='no' /> </Upgrade> <CustomAction Id="PreventDowngrading" Error="There is a newer product already installed" /> <Condition Message='.NET Framework 2.0 is not present on the computer.'> FRAMEWORK20 = "#1" </Condition> <Condition Message='Microsoft PowerShell 1.0 is not present on the computer.'> POWERSHELL10 = "#1" </Condition> <InstallUISequence> <FindRelatedProducts Sequence="1100" /> <ExecuteAction Sequence="1102" /> </InstallUISequence> <InstallExecuteSequence> <AppSearch Sequence="50" /> <LaunchConditions Sequence="100" /> <ValidateProductID Sequence="700" /> <CostInitialize Sequence="800" /> <FileCost Sequence="900" /> <CostFinalize Sequence="1000" /> <FindRelatedProducts Sequence="1100" /> <Custom Action="PreventDowngrading" Sequence="1101">NEWERPRODUCTFOUND</Custom> <MigrateFeatureStates Sequence="1200" /> <InstallValidate Sequence="1400" /> <InstallInitialize Sequence="1500" /> <RemoveExistingProducts Sequence="1502" /> <ProcessComponents Sequence="1600" /> <UnpublishFeatures Sequence="1800" /> <RemoveRegistryValues Sequence="2600" /> <RemoveShortcuts Sequence="3200" /> <RemoveFiles Sequence="3500" /> <InstallFiles Sequence="4000" /> <CreateShortcuts Sequence="4500" /> <WriteRegistryValues Sequence="5000" /> <RegisterUser Sequence="6000" /> <RegisterProduct Sequence="6100" /> <PublishFeatures Sequence="6300" /> <PublishProduct Sequence="6400" /> <InstallFinalize Sequence="6600" /> </InstallExecuteSequence> </Product> </Wix> "@ ########################################## $plugins_element_xpath = "/*/*/*/*/*/*/*"; $product_element_xpath = "/*/*"; $media_element_xpath = "/*/*/"; $wix_ns = "http://schemas.microsoft.com/wix/2003/01/wi" $r = new-object System.Random; $candle_format = "& '{0}\\candle.exe' {1}.wxs -nologo"; $light_format = "& '{0}\\light.exe' -out {1}.msi {1}.wixobj '{2}' -loc '{3}' -nologo" $wxs_file = ("{0}\\{1}.wxs" -f (get-location), ($out).Replace(".msi", "")) $default_title = "UserPlugins"; $default_manufacturer = "Default Manufacturer"; $default_description = "XenCenter Plugins"; $default_product_version = "<?version-long>"; $default_upgrade_code = "8282b90a-cb51-4c02-a1c1-ecfcff9861bf"; $default_product_code = "67d68e4a-82d2-4a7d-a909-cfce92dbe71a"; $default_version_short = "<?version-short>"; function main { function generate-wxs { function get-folder-location { if($plugins -ne $null) { return new-object System.IO.DirectoryInfo $plugins; } $plugins = (read-host -prompt "Path of plugins folder"); return new-object System.IO.DirectoryInfo $plugins; } function get-msiname { if($out -ne $null) { return $out; } return (read-host -prompt "Output MSI name"); } function get-folders([string]$filepath) { $folder_paths = @(); $folders = get-childitem $filepath; foreach($folder in $folders) { if($folder.attributes -contains "Directory") { $folder_paths += $folder; } } return $folder_paths; } function get-files([string]$filepath) { $file_paths = @(); $files = get-childitem $filepath; foreach($file in $files) { if($file.attributes -notcontains "Directory") { $file_paths += $file; } } return $file_paths; } function prep-template { #$contents = [System.String]::Join([System.Environment]::NewLine, (get-content $wix_template)); $contents = $template.ToString() $contents = $contents.Replace($default_title, $title); $contents = $contents.Replace($default_manufacturer, $manufacturer); $contents = $contents.Replace($default_description, $description); $contents = $contents.Replace($default_product_version, $product_version); $contents = $contents.Replace($default_upgrade_code, $upgrade_code); $contents = $contents.Replace($default_product_code, $product_code); $contents = $contents.Replace($default_version_short, $ersion_short); set-content $wxs_file $contents; } function load-template { prep-template; $xml_doc = new-object System.Xml.XmlDocument $xml_doc.Load($wxs_file); return $xml_doc; } function save-template([System.Xml.XmlDocument]$doc, [string]$wxs_path) { $doc.Save($wxs_path); } function gen-id([System.Xml.XmlElement]$node, [string]$name) { $id = $name.Replace(" ", "_") + "_"; for($i=0; $i -le 10; $i++) { $id += ([char]$r.Next(97,122)).ToString(); } $node.SetAttribute("Id", $id); return $id } function gen-name([System.Xml.XmlElement]$node, [string]$name) { if($name.length -gt 8) { $name = $name.Substring(0,8) } $node.SetAttribute("Name", $name.Replace(" ","_")); } function gen-longname([System.Xml.XmlElement]$node, [string]$name) { if($name.length -le 8) { return } $node.SetAttribute("LongName", $name); } function gen-diskid([System.Xml.XmlElement]$node) { $node.SetAttribute("DiskId", "1"); } function gen-source([System.Xml.XmlElement]$node, [string]$path) { $node.SetAttribute("Source", $path); } function gen-vital([System.Xml.XmlElement]$node) { $node.SetAttribute("Vital", "yes"); } function add-icon([System.Xml.XmlDocument]$doc, [System.Xml.XmlNode]$parent_node) { if($icon -eq $null) { return; } $icon_node = [System.Xml.XmlElement]$doc.CreateNode([System.Xml.XmlNodeType]::Element,"Icon",$wix_ns); $foo = gen-id $icon_node "icon"; $icon_node.SetAttribute("SourceFile", $icon); $foo = $parent_node.AppendChild($icon_node); } function add-ui-ref([System.Xml.XmlDocument]$doc, [System.Xml.XmlNode]$parent_node) { $ui_node = [System.Xml.XmlElement]$doc.CreateNode([System.Xml.XmlNodeType]::Element,"UIRef",$wix_ns); $ui_node.SetAttribute("Id", $ui_ref); $foo = $parent_node.AppendChild($ui_node); } function add-file([System.Xml.XmlDocument]$doc, [System.Xml.XmlNode]$component_node, [System.IO.FileSystemInfo]$file) { $file_node = [System.Xml.XmlElement]$doc.CreateNode([System.Xml.XmlNodeType]::Element,"File",$wix_ns); $foo = gen-id $file_node $file.ToString(); gen-name $file_node $file.ToString(); gen-longname $file_node $file.ToString(); gen-diskid $file_node; gen-source $file_node $file.fullname; gen-vital $file_node; $foo = $component_node.AppendChild($file_node); } function gen-guid([System.Xml.XmlElement]$node) { $node.SetAttribute("Guid", [System.Guid]::NewGuid().ToString()); } function remove-id([string]$id) { if($id.Contains("component_")) { return $id.Replace($id.Substring($id.length - 13, 11), "") } else { return $id; } } function add-folder([System.Xml.XmlDocument]$doc, [System.Xml.XmlNode]$parent_node, [System.IO.FileSystemInfo]$folder, [int] $depth) { if($depth -eq 1) { $org_name = $folder.ToString(); $features[$org_name] = @{ "<toplevel>" = @{} }; } elseif($depth -eq 2) { $plugin_name = $folder.ToString(); $features[$org_name].Add($plugin_name,@{}); } if($folder -eq $null) { return; } $folder_node = $null; if($parent_node -eq $null) { $folder_node = $doc.SelectSingleNode($plugins_element_xpath) } else { $folder_node = [System.Xml.XmlElement]$doc.CreateNode([System.Xml.XmlNodeType]::Element,"Directory",$wix_ns); $foo = gen-id $folder_node $folder.ToString(); gen-name $folder_node $folder.ToString(); gen-longname $folder_node $folder.ToString(); } $files = get-files $folder.fullname; $id = $null if(([System.Object[]]$files).length -gt 0) { # add a new component... we need to keep track of these per plugin $component_node = [System.Xml.XmlElement]$doc.CreateNode([System.Xml.XmlNodeType]::Element,"Component",$wix_ns); $id = gen-id $component_node ($folder.Name + "component"); gen-guid $component_node foreach($file in $files) { add-file $doc $component_node $file } $foo = $folder_node.AppendChild($component_node) } if($id -ne $null) { if($org_name -eq $null) { $features["<toplevel>"]["<toplevel>"].Add($id,@{}); } elseif($plugin_name -eq $null) { $features[$org_name]["<toplevel>"].Add($id,@{}); } else { $features[$org_name][$plugin_name].Add($id,@{}); } } $folders = get-folders $folder.fullname; foreach($subfolder in $folders) { add-folder $doc $folder_node $subfolder ($depth +1) } if($parent_node -ne $null) { $foo = $parent_node.AppendChild($folder_node) } } function add-features([System.Xml.XmlDocument]$doc, [System.Xml.XmlNode]$parent_node, [System.Collections.Hashtable]$table, [int]$depth) { if($table -eq @{}) { return } foreach($key in $table.Keys) { if($depth -gt 2) { $component_node = [System.Xml.XmlElement]$doc.CreateNode([System.Xml.XmlNodeType]::Element,"ComponentRef",$wix_ns); $component_node.SetAttribute("Id", $key); $foo = $parent_node.AppendChild($component_node); } elseif(!$key.StartsWith("<toplevel>")) { $name = (remove-id $key) $feature_node = [System.Xml.XmlElement]$doc.CreateNode([System.Xml.XmlNodeType]::Element,"Feature",$wix_ns); $foo = gen-id $feature_node $name; $feature_node.SetAttribute("Title", $name); $feature_node.SetAttribute("Description", "XenCenter plugin provided by {0}" -f $name); $feature_node.SetAttribute("Display", "expand"); $feature_node.SetAttribute("Level", "1"); $feature_node.SetAttribute("ConfigurableDirectory", "INSTALLDIR"); $feature_node.SetAttribute("AllowAdvertise", "no"); $feature_node.SetAttribute("InstallDefault", "local"); $feature_node.SetAttribute("Absent", "allow"); add-features $doc $feature_node $table[$key] ($depth + 1); $foo = $parent_node.AppendChild($feature_node) } else { add-features $doc $parent_node $table[$key] ($depth + 1); } } } $features = @{"<toplevel>" = @{"<toplevel>" = @{}}}; $location = (get-folder-location); $doc = [System.Xml.XmlDocument](load-template); add-icon $doc ($doc.SelectSingleNode($product_element_xpath)); add-ui-ref $doc ($doc.SelectSingleNode($product_element_xpath)); add-folder $doc $null $location 0; add-features $doc ($doc.SelectSingleNode($product_element_xpath)) @{"$title" = $features} 0 save-template $doc $wxs_file; } function build-msi { if(![System.IO.Directory]::Exists($wix)) { write-host ("Could not find default WiX binaries folder at '{0}'" -f $wix) -foregroundcolor Yellow; $wix = read-host "Specify directory containing WiX binaries"; build-msi; return; } $candle_exe = $candle_format -f $wix, $out.Replace(".msi", "") invoke-expression $candle_exe $light_exe = $light_format -f $wix, $out.Replace(".msi", ""), $lib, $loc invoke-expression $light_exe } function clean { remove-item ("{0}.wxs" -f $out.Replace(".msi", "")); remove-item ("{0}.wixobj" -f $out.Replace(".msi", "")); } generate-wxs; build-msi; if(!$debug) { clean } } main;
PowerShellCorpus/GithubGist/lamw_9928202_raw_c15c78de20e0dbf7a3b5a6beeff992bb829a4f49_gistfile1.ps1
lamw_9928202_raw_c15c78de20e0dbf7a3b5a6beeff992bb829a4f49_gistfile1.ps1
$json = @" {"A": {"property1": "value1", "property2": "value2"}, "B": {"property1": "value3", "property2": "value4"}} "@ $parsed = $json | ConvertFrom-Json foreach ($line in $parsed | Get-Member) { echo $parsed.$($line.Name).property1 echo $parsed.$($line.Name).property2 }
PowerShellCorpus/GithubGist/wormeyman_c180a73f221469fc88e2_raw_5c9a5949fb8e7e5fce4f821ccecb5e58552a8cd4_windowsLiveStreamer.ps1
wormeyman_c180a73f221469fc88e2_raw_5c9a5949fb8e7e5fce4f821ccecb5e58552a8cd4_windowsLiveStreamer.ps1
# livestreamer --verbose-player --player "'C:\Program Files (x86)\VideoLAN\VLC\vlc.exe' --file-caching=5000" --default-stream best THEURL # PowerShell -ExecutionPolicy Bypass -File windowsLiveStreamer.ps1 $video = Read-Host 'What is the video url?' # Update LiveStream Write-Host -ForegroundColor Green "Updating livestreamer" pip install --upgrade livestreamer clear # Watch the Stream livestreamer --verbose-player --player "'C:\Program Files (x86)\VideoLAN\VLC\vlc.exe' --file-caching=5000" --default-stream best $video
PowerShellCorpus/GithubGist/stephengodbold_5279081_raw_e03dee00f841c927b636342e39d41ed1b437a19f_Install-BuildMonitor.ps1
stephengodbold_5279081_raw_e03dee00f841c927b636342e39d41ed1b437a19f_Install-BuildMonitor.ps1
param( [parameter()] [string] $repositoryRoot, [parameter()] [string] $installRoot = $env:ProgramFiles ) function Get-MsBuildPath { $registryLocation = 'HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0\' $registryEntry = Get-ItemProperty $registryLocation -Name 'MSBuildToolsPath' return $registryEntry.MSBuildToolsPath } function Test-Service { $service = Get-Service TfsBuildMonitor -ErrorAction 'SilentlyContinue' return $service -ne $null } function Install-Service { param( [Parameter(Mandatory=$true)] [string] $installPath ) $serviceExists = Test-Service if ($serviceExists) { Stop-Service $applicationName } $outputPath = Join-Path $repositoryRoot 'BuildMonitor.Service\bin\Release' if (-not (Test-Path $installPath)) { New-Item $installPath -Type Directory } Get-ChildItem $outputPath | foreach { Copy-Item $_.FullName $installPath } if (-not $serviceExists) { $executablePath = Join-Path $installPath 'BuildMonitor.Service.exe' New-Service ` -Name $applicationName ` -BinaryPathName $executablePath ` -StartupType Automatic ` -Credential (Get-Credential) ` -DisplayName $applicationName ` -Description 'A build monitor service to indicate success/failure of a build via a Delcomm light' } } function Expand-Zip($SourcePath, $TargetPath) { #Unzip code modified from http://bit.ly/fwGjfY $UnzipShell = new-object -com shell.application $ZipPackage = $UnzipShell.NameSpace($SourcePath) $DestinationFolder = $UnzipShell.NameSpace($TargetPath) $DestinationFolder.CopyHere($ZipPackage.Items()) } function Get-OSVersion { if ([System.IntPtr]::Size -eq 8) { return '64' } return '' } function Unzip-DelcomDependency { param( [Parameter(Mandatory=$true)] [string] $repositoryRoot, [Parameter(Mandatory=$true)] [string] $installPath ) $OSVersion = Get-OSVersion $archiveName = "DelcomDLL$OSVersion.zip" $archivePath = Join-Path $repositoryRoot $archiveName Expand-Zip $archivePath $installPath } if ($repositoryRoot -eq '') { $repositoryRoot = Get-Location } $applicationName = 'TfsBuildMonitor' $installPath = Join-Path $installRoot $applicationName Unzip-DelcomDependency $repositoryRoot $installPath Install-Service $installPath Start-Service $applicationName
PowerShellCorpus/GithubGist/ao-zkn_4ef4432bf8cc833f36fa_raw_defae0a87ae49271d7541317142ffbfa50051e8e_Select-ExcelByWorkSheet.ps1
ao-zkn_4ef4432bf8cc833f36fa_raw_defae0a87ae49271d7541317142ffbfa50051e8e_Select-ExcelByWorkSheet.ps1
# ------------------------------------------------------------------ # Excelファイルをシート単位で検索 # 関数名:Select-ExcelByWorkSheet # 引数 :ExcelFilePath 検索対象のExcelファイル # :Target 検索対象項目 # 戻り値:検索結果 # ------------------------------------------------------------------ function Select-ExcelByWorkSheet([String]$ExcelFilePath, [String]$Target){ # 検索結果 $result = @() # Excel のインスタンスを作成 $excel = New-Object -comobject Excel.Application # Excelファイルを開かない $excel.Visible = $False # 確認メッセージを非表示 $excel.DisplayAlerts = $False # ワークブックを開く $workBook = $excel.Workbooks.Open($excelFilePath) # ワークシート分ループ foreach($workSheet In $workBook.workSheets){ # 検索対象が存在するか確認 if($workSheet.UsedRange.Find($Target) -ne $Null){ # オブジェクト作成 $value = New-Object PSCustomObject -Property @{ # Excelファイル名(フルパス) ExcelFilePath = $excelFilePath # ワークシート名 WorkSheet = $workSheet.Name } $result += $value } } $workBook.Close() [void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($workBook) $excel.Quit() [void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($excel) return $result }
PowerShellCorpus/GithubGist/agross_6178123_raw_77962a7c5e45ead40a8e9e841322becf504ec225_deploy.ps1
agross_6178123_raw_77962a7c5e45ead40a8e9e841322becf504ec225_deploy.ps1
$ErrorActionPreference = 'Stop' $scriptPath = Split-Path -parent $MyInvocation.MyCommand.Definition Import-Module "$scriptPath\tools\deployment-tools" Import-Module "$scriptPath\bin\NServiceBus.PowerShell.dll" $permissions = @{ '' = @{ "FullControl" = @( $(ConvertTo-UserName([System.Security.Principal.WellKnownSidType]::BuiltinAdministratorsSid)), $(ConvertTo-UserName([System.Security.Principal.WellKnownSidType]::LocalSystemSid)) ) } 'bin' = @{ "ReadAndExecute" = @( $(ConvertTo-UserName([System.Security.Principal.WellKnownSidType]::NetworkServiceSid)) ) } 'logs' = @{ "Modify" = @( $(ConvertTo-UserName([System.Security.Principal.WellKnownSidType]::NetworkServiceSid)) ) } } $serviceName = "GROSSWEBER development Ops" $endpointName = "GROSSWEBER.development.ops" # Convert-ToUserName would translate to German here, the following works on German and English systems. $serviceIdentity = "NT AUTHORITY\NetworkService" $physicalPath = "$scriptPath\bin" function Install { Set-Permissions -RootPath $scriptPath -Permissions $permissions Exec { & $scriptPath\tools\WebPlatformInstaller\WebpiCmd.exe /Install "/Products:NETFramework4" /SuppressReboot /AcceptEula } Exec { & $physicalPath\NServiceBus.Host.exe /uninstall /serviceName:$serviceName } Install-NServiceBusDTC Install-NServiceBusMSMQ -Confirm:$false Install-NServiceBusPerformanceCounters -Confirm:$false Install-NServiceBusRavenDB Exec { & $physicalPath\NServiceBus.Host.exe /install /serviceName:$serviceName /endpointName:$endpointName /username:$serviceIdentity /password:`"`" } $service = Get-Service -Name $serviceName $dependencies = $service.ServicesDependedOn | ForEach-Object { $_.ServiceName } $dependencies = (@() + $dependencies + "RavenDB" + "MSMQ") -Join "/" Exec { sc.exe config $service.ServiceName depend= $dependencies } $service.Start() Write-Host "Done" } function Uninstall {} # Runs all command line arguments as functions. $args | ForEach-Object { & $_ }
PowerShellCorpus/GithubGist/giseongeom_fe2b0d90409b484dc15b_raw_2b51a90e43158ae52dff17a909bdff76ca35fb38_get-koalra-files.ps1
giseongeom_fe2b0d90409b484dc15b_raw_2b51a90e43158ae52dff17a909bdff76ca35fb38_get-koalra-files.ps1
# get-koalra-files.ps1 # Retrieve .pptx files from Koalra Server # # Author : GiSeong Eom <jurist@kldp.org> # Created: 2012-06-22 # Updated: 2013-03-16 # ChangeLog # v0.2 Updated for SC2012 LAB files # v0.1 Originally written # Global Variables $ErrorActionPreference = "silentlyContinue" $strKoalra_home = "https://content.koalra.com" $strKoalra_download_URL = "https://content.koalra.com" # Check PowerShell version if ($Host.Version.Major -ne 3) { Write-Output "Warning: PowerShell v3 is the only supported platform." Break } # Get Authentication Info. $cred = Get-Credential # Get index.html $SiteIndex = (Invoke-WebRequest -Credential $cred -uri $strKoalra_download_URL) # Get files' uri list $FileList = ($SiteIndex | ForEach-Object Links | Where-Object { $_.innerText -ne "web.config" } | ForEach-Object Href) # Download...... Foreach ( $myFile in $FileList ) { Start-BitsTransfer -source $strKoalra_home$myFile -Credential $cred -Authentication Basic -Destination $PWD } Write-Host "Download completed. Check $PWD" # EOL
PowerShellCorpus/GithubGist/ecampidoglio_3905035_raw_498bcfbc8d6fe01fc03ec098319a0a1a22ca136e_Import-PSSnapin.ps1
ecampidoglio_3905035_raw_498bcfbc8d6fe01fc03ec098319a0a1a22ca136e_Import-PSSnapin.ps1
function Import-PSSnapin { <# .Synopsis Adds a Windows PowerShell snap-in with the specified name to the current session. This cmdlet will not throw an exception if the specified snap-in is already present in the session. .Description Helper function to safely add a Windows PowerShell snap-in with the specified name to the current session. .Parameter Name The name of the snap-in to import. #> [CmdletBinding()] param( [Parameter(Position=1)] [string]$Name ) $snapinIsNotInSession = -Not (Get-PSSnapin $Name -ErrorAction SilentlyContinue) if ($snapinIsNotInSession) { Add-PSSnapin $Name } }
PowerShellCorpus/GithubGist/usami-k_1686889_raw_8153e633e271d4d793342f782b1ba59782f5d4ce_powershell_history.ps1
usami-k_1686889_raw_8153e633e271d4d793342f782b1ba59782f5d4ce_powershell_history.ps1
# Add this code to your PowerShell Profile (see $Profile) # history file name $HistoryFile = Join-Path (Split-Path $Profile -Parent) history.csv # save history on exit Register-EngineEvent PowerShell.Exiting -SupportEvent -Action { Get-History -Count $MaximumHistoryCount | Export-Csv $HistoryFile } # load history if (Test-Path $HistoryFile) { Import-Csv $HistoryFile | Add-History }
PowerShellCorpus/GithubGist/obscuresec_b6c97b423fedc4500c10_raw_3a0eedb1dcda946f015486737c1d45315be63517_gistfile1.ps1
obscuresec_b6c97b423fedc4500c10_raw_3a0eedb1dcda946f015486737c1d45315be63517_gistfile1.ps1
$LdapFilter = #Query Goes Here ([adsisearcher]"$LdapFilter").Findall()
PowerShellCorpus/GithubGist/sunnyone_7875591_raw_f58a560a57b9786668577a96cd9aa1fd42ab9cff_ShowStackDump.ps1
sunnyone_7875591_raw_f58a560a57b9786668577a96cd9aa1fd42ab9cff_ShowStackDump.ps1
param($Dump) New-DbgSession -dump $Dump -sos Invoke-DbgCommand "~*e !clrstack" Exit-DbgSession
PowerShellCorpus/GithubGist/ao-zkn_c54d71f4d0873faffad3_raw_5f3ad9c9789882ff0952de25d99afa10cd99c44f_Copy-Folder.ps1
ao-zkn_c54d71f4d0873faffad3_raw_5f3ad9c9789882ff0952de25d99afa10cd99c44f_Copy-Folder.ps1
# ------------------------------------------------------------------ # コピー元のフォルダ構成をコピー先にコピーする # 関数名:Copy-Folder # 引数  :CopyFolderPath コピー元のフォルダフルパス # DestFolderPath コピー先のフォルダフルパス # 戻り値:なし # ------------------------------------------------------------------ function Copy-Folder([String]$CopyFolderPath, [String]$DestFolderPath){ # コピー元の指定したフォルダのチェック if(-not(Test-Path $CopyFolderPath)){ Write-Host "指定したコピー元フォルダが存在しません" break } # コピー先の指定したフォルダが存在しない場合は作成 $destItem = New-Item $DestFolderPath -Type directory -Force # コピー元配下のフォルダをコピー Get-ChildItem $CopyFolderPath -Recurse | Where { $_.mode -match "d" } | ForEach-Object { # フォルダ名の大文字小文字を区別しないので小文字に統一して作成 $destFullName = $_.FullName.ToLower().Replace($CopyFolderPath.ToLower(), $DestFolderPath) $destItem = New-Item $destFullName -Type directory -Force } }
PowerShellCorpus/GithubGist/yetanotherchris_0f1d763e6d539fc61857_raw_99d50cc315a77a5954c690f6eca35472822d1131_AppveyorChrome.ps1
yetanotherchris_0f1d763e6d539fc61857_raw_99d50cc315a77a5954c690f6eca35472822d1131_AppveyorChrome.ps1
# Project->Settings->Environment->Install script iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) cinst GoogleChrome cinst gb.MongoDB
PowerShellCorpus/GithubGist/guitarrapc_ae3d60e9517587abda71_raw_37af628a58d96206c9728d887970e3653d3a44b9_SetLCM.ps1
guitarrapc_ae3d60e9517587abda71_raw_37af628a58d96206c9728d887970e3653d3a44b9_SetLCM.ps1
Set-DscLocalConfigurationManager -Path test
PowerShellCorpus/GithubGist/Haemoglobin_2205505_raw_dfe1a6ac784f41a848bed2a3f94935e4bba35875_add-source-headers.ps1
Haemoglobin_2205505_raw_dfe1a6ac784f41a848bed2a3f94935e4bba35875_add-source-headers.ps1
#requires -version 2 <# #> param( [Parameter(Mandatory = $true)] [string] $sourceRoot, [Parameter(Mandatory = $true)] [string] $versionNumber ) function CorrectPathBackslash { param([string] $path) if (![String]::IsNullOrEmpty($path)) { if (!$path.EndsWith("\")) { $path += "\" } } return $path } $sourceRoot = CorrectPathBackslash $sourceRoot #Change any ..\.. etc to proper path for path length usage later $sourceRoot = [IO.Path]::GetFullPath($sourceRoot) $today = Get-Date -format g $visitedFiles = @{} $projects = Get-ChildItem $sourceRoot -Filter *.csproj -Recurse foreach($project in $projects) { Write-Verbose "Processing $($project.Name)..." $projectXml = New-Object XML $projectXml.Load($project.FullName) if ($projectXml.Project.PropertyGroup.Length -lt 1) { Write-Verbose "No default property group for $($project.FullName)" continue } $assemblyName = $projectXml.Project.PropertyGroup[0].AssemblyName $sourceFiles = Get-ChildItem $project.Directory -Filter *.cs -Recurse foreach($sourceFile in $sourceFiles) { if ($visitedFiles.Contains($sourceFile.FullName)) { continue } $visitedFiles[$sourceFile.FullName]=1 $content = Get-Content $sourceFile.FullName Write-Verbose "Processing source file: $sourceFile.FullName" if($content[0].StartsWith("// YourLibrary SDK")) { for($i = 0; $i -lt 8; $i++) { $content[$i] = $null } } $relativeFilename = $sourceFile.FullName.Remove(0, $sourceRoot.Length) $preface = "// YourLibrary SDK`n" + ` "// $relativeFilename`n" + ` "// $assemblyName, Version $versionNumber, Published $today`n" + ` "// (c) Copyright YourCompany`n" + ` "// --------------------------------------------------------------------------------`n" + ` "`n" + ` "`n" Set-Content $sourceFile.FullName -value $preface, $content } }
PowerShellCorpus/GithubGist/zippy1981_1586729_raw_7e46e3e35428757ce9a9a88bbdd42662ea6e3f85_integerDivision.test.ps1
zippy1981_1586729_raw_7e46e3e35428757ce9a9a88bbdd42662ea6e3f85_integerDivision.test.ps1
<# In which I prove that that the terser [int][Math]::Floor($a/$b) gives the same results as the technet recommended [Math]::Floor([int]$a / [int]$b) Said technet recomendation is available at: http://technet.microsoft.com/en-us/library/ee176879.aspx One extra cast is probably slower too. #> 1.. 1000 | ForEach-Object { Foreach ($divisor in 2,3,5,7) { $a = [int][Math]::Floor($_ / $divisor) $b = [Math]::Floor([int]$_ / [int]$divisor) if ($a -ne $b) { "$($a) <> $($b) : $($a)/$($b)" } } }
PowerShellCorpus/GithubGist/bedecarroll_7405639_raw_e8d779cbdbb9167d25ed9066438471091a2d7ae0_gistfile1.ps1
bedecarroll_7405639_raw_e8d779cbdbb9167d25ed9066438471091a2d7ae0_gistfile1.ps1
Get-CimInstance Win32_WinSAT | Format-List @{Label="Base Score";Expression={$_.WinSPRLevel}},@{Label="Processor";Expression={$_.CPUScore}},@{Label="Memory (RAM)";Expression={$_.MemoryScore}},@{Label="Graphics";Expression={$_.GraphicsScore}},@{Label="Gaming graphics";Expression={$_.D3DScore}},@{Label="Primary hard disk";Expression={$_.DiskScore}}
PowerShellCorpus/GithubGist/RhysC_850863_raw_8a732b72cf81e8d53d5171259e6fe4a2e95dc653_GetProjectSummarys.ps1
RhysC_850863_raw_8a732b72cf81e8d53d5171259e6fe4a2e95dc653_GetProjectSummarys.ps1
$projectSummarys = @{} Get-ChildItem -exclude '*Test*' -Recurse -Include *.csproj | Where-Object {$_.Attributes -ne "Directory"} | %{ $filename = $_.FullName $proj = [xml](get-Content $filename); $projectSummarys[$filename] = ($proj.Project.PropertyGroup)|select -Skip 1 -First 1 | select WarningLevel, CodeAnalysisRuleSet, RunCodeAnalysis, TreatWarningsAsErrors } $WarningLevelNotvalid = @{} $CodeAnalysisRuleSetNotvalid = @{} $RunCodeAnalysis = @{} $TreatWarningsAsErrors = @{} $projectSummarys.GetEnumerator() | %{ if($_.Value.WarningLevel -ne 4) { $WarningLevelNotvalid[$_.Name] = $_.Value.WarningLevel } if($_.Value.CodeAnalysisRuleSet -eq $null -or $_.Value.CodeAnalysisRuleSet.Contains("Alpha.ruleset") -eq $false) { $CodeAnalysisRuleSetNotvalid[$_.Name] = $_.Value.CodeAnalysisRuleSet } if($_.Value.RunCodeAnalysis -eq $null -or $_.Value.RunCodeAnalysis.Contains("true") -eq $false) { $RunCodeAnalysis[$_.Name] = $_.Value.RunCodeAnalysis } if($_.Value.TreatWarningsAsErrors -eq $null -or $_.Value.TreatWarningsAsErrors.Contains("true") -eq $false) { $TreatWarningsAsErrors[$_.Name] = $_.Value.TreatWarningsAsErrors } } #report results Write-Host "Projects without warning level at 4" -ForegroundColor Yellow $WarningLevelNotvalid.GetEnumerator() | % {Write-Host $_.Name} Write-Host "Projects with incorrect CodeAnalysisRuleSet" -ForegroundColor Yellow $CodeAnalysisRuleSetNotvalid.GetEnumerator() | % {Write-Host $_.Name} Write-Host "Projects without RunCodeAnalysis" -ForegroundColor Yellow $RunCodeAnalysis.GetEnumerator() | % {Write-Host $_.Name} Write-Host "Projects without TreatWarningsAsErrors" -ForegroundColor Yellow $TreatWarningsAsErrors.GetEnumerator() | % {Write-Host $_.Name} $reportfile = "report.txt" "Projects without warning level at 4" > $reportfile $WarningLevelNotvalid.GetEnumerator() | % {$_.Name >> $reportfile} "`r`nProjects with incorrect CodeAnalysisRuleSet" >> $reportfile $CodeAnalysisRuleSetNotvalid.GetEnumerator() | % {$_.Name >> $reportfile} "`r`nProjects without RunCodeAnalysis" >> $reportfile $RunCodeAnalysis.GetEnumerator() | % {$_.Name >> $reportfile} "`r`nProjects without TreatWarningsAsErrors" >> $reportfile $TreatWarningsAsErrors.GetEnumerator() | % {$_.Name >> $reportfile}
PowerShellCorpus/GithubGist/randyburden_7666678_raw_3a808ebfee87fc360319c7c2a324aced6a7378ac_install.ps1
randyburden_7666678_raw_3a808ebfee87fc360319c7c2a324aced6a7378ac_install.ps1
param($installPath, $toolsPath, $package, $project) # open splash page on package install # don't open if it is installed as a dependency # attribution: Modified from: https://github.com/JamesNK/Newtonsoft.Json/blob/master/Build/install.ps1 try { $url = "http://randyburden.com/Slapper.AutoMapper/" $packageName = "slapper.automapper" $dte2 = Get-Interface $dte ([EnvDTE80.DTE2]) if ($dte2.ActiveWindow.Caption -eq "Package Manager Console") { # user is installing from VS NuGet console # get reference to the window, the console host and the input history # show webpage if "install-package YourPackageName" was last input $consoleWindow = $(Get-VSComponentModel).GetService([NuGetConsole.IPowerConsoleWindow]) $props = $consoleWindow.GetType().GetProperties([System.Reflection.BindingFlags]::Instance -bor ` [System.Reflection.BindingFlags]::NonPublic) $prop = $props | ? { $_.Name -eq "ActiveHostInfo" } | select -first 1 if ($prop -eq $null) { return } $hostInfo = $prop.GetValue($consoleWindow) if ($hostInfo -eq $null) { return } $history = $hostInfo.WpfConsole.InputHistory.History $lastCommand = $history | select -last 1 if ($lastCommand) { $lastCommand = $lastCommand.Trim().ToLower() if ($lastCommand.StartsWith("install-package") -and $lastCommand.Contains($packageName)) { $dte2.ItemOperations.Navigate($url) | Out-Null } } } else { # user is installing from VS NuGet dialog # get reference to the window, then smart output console provider # show webpage if messages in buffered console contains "installing...YourPackageName" in last operation $instanceField = [NuGet.Dialog.PackageManagerWindow].GetField("CurrentInstance", [System.Reflection.BindingFlags]::Static -bor ` [System.Reflection.BindingFlags]::NonPublic) $consoleField = [NuGet.Dialog.PackageManagerWindow].GetField("_smartOutputConsoleProvider", [System.Reflection.BindingFlags]::Instance -bor ` [System.Reflection.BindingFlags]::NonPublic) if ($instanceField -eq $null -or $consoleField -eq $null) { return } $instance = $instanceField.GetValue($null) if ($instance -eq $null) { return } $consoleProvider = $consoleField.GetValue($instance) if ($consoleProvider -eq $null) { return } $console = $consoleProvider.CreateOutputConsole($false) $messagesField = $console.GetType().GetField("_messages", [System.Reflection.BindingFlags]::Instance -bor ` [System.Reflection.BindingFlags]::NonPublic) if ($messagesField -eq $null) { return } $messages = $messagesField.GetValue($console) if ($messages -eq $null) { return } $operations = $messages -split "==============================" $lastOperation = $operations | select -last 1 if ($lastOperation) { $lastOperation = $lastOperation.ToLower() $lines = $lastOperation -split "`r`n" $installMatch = $lines | ? { $_.StartsWith("------- installing..." + $packageName) } | select -first 1 if ($installMatch) { $dte2.ItemOperations.Navigate($url) | Out-Null } } } } catch { # stop potential errors from bubbling up # worst case the splash page won't open }
PowerShellCorpus/GithubGist/aciniform_4998671_raw_4fa6dfa7984ca9428fe1f05d83e9994fd07df784_Send-PwdExpirationNotice.ps1
aciniform_4998671_raw_4fa6dfa7984ca9428fe1f05d83e9994fd07df784_Send-PwdExpirationNotice.ps1
[CmdletBinding()] param( [switch] $WhatIf, [switch] $ReportOnly ) ############################################################################### # Configuration Parameters # ############################################################################### # Number of days in advance to notify the user. For example, change to @(7, 1) # to notify users one week before and again one day before their password is # going to expire. $DAYS_IN_ADVANCE = @(14, 7, 3, 2, 1) # AD group that should receive notifications. Set to $null to include everyone. $PASSWORD_NOTIFICATION_GROUP = "Password_Notifications" # Search base within which to look for users $SEARCH_BASE = "DC=EXAMPLE,DC=ORG" # Your email server $MAIL_SERVER = "mail.example.org" # From address for notification emails $NOTIFICATION_EMAIL_FROM = "helpdesk@example.org" # Sysadmin to send reports to $NOTIFICATION_EMAIL_REPORT = "helpdesk@example.org" # Subject for notification emails. Use '{0}' where you want the number of days # till the password expires. $NOTIFICATION_EMAIL_SUBJECT = @" Password Reminder: Your password will expire in {0} days "@ # Message to send users. Use '{0}' where you want the number of days till the # password expires $NOTIFICATION_EMAIL_CONTENTS = @" <p> <strong> Your password will expire in {0} day(s). </strong> </p> "@ ############################################################################### Import-Module ActiveDirectory -ErrorAction Stop function Test-EffectiveGroupMembership { param( [parameter(Mandatory = $true)] [string] $AccountName, [parameter(Mandatory = $true)] [string] $GroupName ) $ADSIObject = [adsi]"LDAP://$((Get-ADUser $AccountName).DistinguishedName)" # Retrieve tokenGroups attribute of principal (not retrieved by default) $ADSIObject.psbase.RefreshCache("tokenGroups") $GroupTokens = $ADSIObject.psbase.Properties.Item("tokenGroups") $group_found = $false foreach ($GroupToken in $GroupTokens) { # Change group tokens -> group SIDs -> group names $GroupSID = New-Object System.Security.Principal.SecurityIdentifier $GroupToken, 0 $Group = $GroupSID.Translate([System.Security.Principal.NTAccount]) $Group = $Group.Value.Split("\")[1] if ($Group -eq $GroupName) { $group_found = $true break } } $group_found } # Get max password age $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $domain = [ADSI]"LDAP://$($domain)" # Throw if max password age not set ($max_pw_age comes out as a negative value) if ($domain.max_pw_age -eq $null) { throw "Max password age not set for the domain" } $max_pw_age_ticks = $domain.ConvertLargeIntegerToInt64($domain.maxPwdAge.Value) $max_pw_age = [System.Timespan]::FromTicks($max_pw_age_ticks) # Get enabled users without password never exipres set... $users = Get-ADUser -Properties MemberOf,PasswordLastSet,mail ` -SearchBase $SEARCH_BASE -Filter { (Enabled -eq $true) -and (PasswordNeverExpires -eq $false) } Write-Verbose "Enabled users in search base where password will expire:" Write-Verbose "Count: $($users.Count)" # ...who are members of the password notifications group if ($PASSWORD_NOTIFICATION_GROUP -ne $null) { $tmp_list = @() foreach ($user in $users) { if (Test-EffectiveGroupMembership -AccountName $user.sAMAccountName ` -GroupName $PASSWORD_NOTIFICATION_GROUP) { $tmp_list += $user } } $users = $tmp_list } Write-Verbose "Users who are also members of the password reset group" Write-Verbose "Count: $($users.Count)" $admin_report = $null foreach ($user in $users) { $pw_set = $user.PasswordLastSet if ($pw_set -eq "" -or $pw_set -eq $null) { Write-Warning "$($user.Name) ($($user.SamAccountName)) has never had their password set" $admin_report += "<p>$($user.Name) ($($user.SamAccountName)) has never had their password set.</p>" continue } if ($user.mail -eq $null) { Write-Warning "$($user.Name) ($($user.SamAccountName)) has no email address" $admin_report += "<p>$($user.Name) ($($user.SamAccountName)) has no email address.</p>" continue } $time_left = ($pw_set - $max_pw_age) - (Get-Date) $days_left = $time_left.Days if ($DAYS_IN_ADVANCE -contains $days_left) { if ($WhatIf) { "What if: Sending email to $($user.Name) ($($user.SamAccountName)) at $($user.mail). " + ` "$days_left days until expiration." } elseif ($ReportOnly) { } else { Send-MailMessage -BodyAsHtml ` -From $NOTIFICATION_EMAIL_FROM ` -To $user.mail ` -Subject ([string]::Format($NOTIFICATION_EMAIL_SUBJECT, $days_left)) ` -Body ([string]::Format($NOTIFICATION_EMAIL_CONTENTS, $days_left)) ` -SmtpServer $MAIL_SERVER } $admin_report += "<p>Password reminder has been sent to ` $($user.Name) ` $([string]::Format(": {0} days left", $days_left))</p>" } } if ($admin_report -ne $null) { if ($WhatIf) { "What if: Sending admin report to $($NOTIFICATION_EMAIL_REPORT)" } else { $subject = "User password notifications" if ($ReportOnly) { $subject = "Report Only: User password notifications" } Send-MailMessage -BodyAsHtml ` -From $NOTIFICATION_EMAIL_FROM ` -To $NOTIFICATION_EMAIL_REPORT ` -Subject $subject ` -Body $admin_report ` -SmtpServer $MAIL_SERVER } }
PowerShellCorpus/GithubGist/seriema_7431598_raw_6e8b963898f81549efb85e2656c7ab3d6d40b8a4_boxstarter.ps1
seriema_7431598_raw_6e8b963898f81549efb85e2656c7ab3d6d40b8a4_boxstarter.ps1
try { # Dev cinst VisualStudio2013Ultimate -InstallArguments "/Features:'Blend WebTools'" cinst VS2013.1 cinst VS2013.2 cinst VS2013.3 cinst visualstudio2013-webessentials.vsix cinst resharper cinst git cinst githubforwindows cinst fiddler4 cinst sysinternals cinst windbg cinst dotPeek # Tools cinst ccleaner cinst Paint.net cinst Console2 cinst sublime cinst GoogleChrome cinst Firefox # Setup Install-ChocolateyFileAssociation ".txt" "$env:programfiles\Sublime Text 2\sublime_text.exe" if(!(Test-Path("$sublimeDir\data"))){mkdir "$sublimeDir\data"} copy-item (Join-Path (Get-PackageRoot($MyInvocation)) 'sublime\*') -Force -Recurse "$sublimeDir\data" move-item "$sublimeDir\data\Pristine Packages\*" -Force "$sublimeDir\Pristine Packages" copy-item (Join-Path (Get-PackageRoot($MyInvocation)) 'console.xml') -Force $env:appdata\console\console.xml # Basic windows stuff Install-WindowsUpdate -AcceptEula Update-ExecutionPolicy Unrestricted Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions Set-TaskbarSmall Enable-RemoteDesktop Write-ChocolateySuccess 'JPDev installed' } catch { Write-ChocolateyFailure 'JPDev' $($_.Exception.Message) throw }
PowerShellCorpus/GithubGist/sclarson_1a2deecc8ca4592e1ef1_raw_45958421ee5155e221bbe75e11821e2a36ffe88b_sensitiveCd.ps1
sclarson_1a2deecc8ca4592e1ef1_raw_45958421ee5155e221bbe75e11821e2a36ffe88b_sensitiveCd.ps1
function GetCaseSensitivePath{ param($pathName) $pathExists = Test-Path($pathName) if (-Not $pathExists){ return $pathName } $directoryInfo = New-Object IO.DirectoryInfo($pathName) if ($directoryInfo.Parent -ne $null){ $parentPath = GetCaseSensitivePath($directoryInfo.Parent.FullName) $childPath = $directoryInfo.Parent.GetFileSystemInfos($directoryInfo.Name)[0].Name return(Join-Path $parentPath $childpath -resolv) }else{ return $directoryInfo.Name } } $executionContext.SessionState.InvokeCommand.PostCommandLookupAction = { param($CommandName, $CommandLookupEventArgs) #Only hook cd if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -eq "cd"){ $CommandLookupEventArgs.CommandScriptBlock = { $x = Resolve-Path($args) $x = GetCaseSensitivePath($x) Set-Location $x } $CommandLookupEventArgs.StopSearch = $true } }
PowerShellCorpus/GithubGist/mgreenegit_891dddc6de8d7be5dfd2_raw_561ca66c7f86894dca8a0e54687eb1f1b1afe2b0_HydrateAllPublicResKitodulesOnPOCPullServer.ps1
mgreenegit_891dddc6de8d7be5dfd2_raw_561ca66c7f86894dca8a0e54687eb1f1b1afe2b0_HydrateAllPublicResKitodulesOnPOCPullServer.ps1
$AllModules = 'https://gallery.technet.microsoft.com/scriptcenter/DSC-Resource-Kit-All-c449312d/file/131371/1/DSC%20Resource%20Kit%20Wave%209%2012172014.zip' $Folder = 'C:\AllModules' $PullServerModules = 'C:\DscWebService\Modules' if (!(Test-Path "$Folder\Archives")) {mkdir "$Folder\Archives" | out-null} Invoke-WebRequest -Uri $AllModules -OutFile "$Folder\AllModules.zip" Expand-Archive -Path "$Folder\AllModules.zip" -DestinationPath "$Folder\Extract" -Force foreach ($ResourceFolder in (Get-ChildItem "$Folder\Extract\All Resources")) { $ModuleData = Test-ModuleManifest "$($ResourceFolder.FullName)\$($ResourceFolder.Name).PSD1" $File = "$($ModuleData.Name)_$($ModuleData.Version).zip" Compress-Archive -Path $($ResourceFolder.FullName) -DestinationPath "$Folder\Archives\$File" } New-DSCCheckSum -ConfigurationPath "$Folder\Archives" -OutPath "$Folder\Archives" Copy-Item -Recurse "$Folder\Archives\" $PullServerModules -Verbose