full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/micdenny_264c5d02f31b246f475c_raw_3195da8afc32e82ee94aa8306a4ea144cb6d10eb_download-entries.ps1
micdenny_264c5d02f31b246f475c_raw_3195da8afc32e82ee94aa8306a4ea144cb6d10eb_download-entries.ps1
# --- settings --- $feedUrlBase = "https://www.nuget.org/api/v2/" # the rest will be params when converting to funclet $latest = $true $overwrite = $false $top = 5000 #use $top = $null to grab all $destinationDirectory = join-path ([Environment]::GetFolderPath("MyDocuments")) "NuGetLocal" # --- locals --- $webClient = New-Object System.Net.WebClient # --- functions --- # download entries on a page, recursively called for page continuations function DownloadEntries { param ([string]$feedUrl) $feed = [xml]$webClient.DownloadString($feedUrl) $entries = $feed.feed.entry $progress = 0 foreach ($entry in $entries) { $url = $entry.content.src $fileName = $entry.title."#text" + "." + $entry.properties.version + ".nupkg" $saveFileName = join-path $destinationDirectory $fileName $pagepercent = ((++$progress)/$entries.Length*100) if ((-not $overwrite) -and (Test-Path -path $saveFileName)) { write-progress -activity "$fileName already downloaded" -status "$pagepercent% of current page complete" -percentcomplete $pagepercent continue } write-progress -activity "Downloading $fileName" -status "$pagepercent% of current page complete" -percentcomplete $pagepercent trap [System.Net.WebException] { write-error $("TRAPPED: " + $_.Exception.Message); continue; } $webClient.DownloadFile($url, $saveFileName) } $link = $feed.feed.link | where { $_.rel.startsWith("next") } | select href if ($link -ne $null) { # if using a paged url with a $skiptoken like # http:// ... /Packages?$skiptoken='EnyimMemcached-log4net','2.7' # remember that you need to escape the $ in powershell with ` return $link.href } return $null } # the NuGet feed uses a fwlink which redirects # using this to follow the redirect function GetPackageUrl { param ([string]$feedUrlBase) $resp = [xml]$webClient.DownloadString($feedUrlBase) return $resp.service.GetAttribute("xml:base") } # --- do the actual work --- # if dest dir doesn't exist, create it if (!(Test-Path -path $destinationDirectory)) { New-Item $destinationDirectory -type directory } # set up feed URL $serviceBase = GetPackageUrl($feedUrlBase) $feedUrl = $serviceBase + "Packages" if($latest) { $feedUrl = $feedUrl + "?`$filter=IsLatestVersion eq true" if($top -ne $null) { $feedUrl = $feedUrl + "&`$orderby=DownloadCount desc&`$top=$top" } } while($feedUrl -ne $null) { $feedUrl = DownloadEntries $feedUrl }
PowerShellCorpus/GithubGist/fgarcia_8451635_raw_f75650e1a0fd7b4be4fb757389a12753d74067d2_gistfile1.ps1
fgarcia_8451635_raw_f75650e1a0fd7b4be4fb757389a12753d74067d2_gistfile1.ps1
#!/bin/bash # # Start CouchBase Server 2.2 ## [ "$HOME" != "" ] && exec -c $0 export SHLVL=1 export HOME=/Users/dominik export COUCHDB_ADDITIONAL_CONFIG_FILE=/Users/dominik/Library/Preferences/couchbase-server.in cd "/Applications/Couchbase Server.app/Contents/Resources" ./start-server.sh
PowerShellCorpus/GithubGist/gunungloli666_5716746_raw_ad3c53cd521927597c7640805851138b0f0d3df9_sph.ps1
gunungloli666_5716746_raw_ad3c53cd521927597c7640805851138b0f0d3df9_sph.ps1
# untuk mencari perintah tertentu pada isi suatu file program # dan mencari tahu pada baris mana perintah tersebut berada $a = dir ;# directory saat ini # string yang akan dicari, dalam hal ini perintah tertentu pada fortran $my_regex = [regex] "In+\spoute_2D" # iterasi untuk seluruh isi directory saat ini foreach($item in $a ){ # baca isi dari file masing-masing file $content = get-content $item; # iterasi terhadap baris dalam file $i = 0 ; # untuk menentukan pada baris mana perintah tersebut berada foreach($line in $content){ $hasilcari = $my_regex.matches($line) ; $hasilcari = $hasilcari[0]; # jika ditemukan setidaknya satu kali saja perintah tersebut if($hasilcari.success){ $i++ write-host "dapat di file $item, pada baris $i, pada perintah: $line" } } }
PowerShellCorpus/GithubGist/vgrem_7550721_raw_76cfc8ee80f7395dd22abdb3471e916a5dc929d2_PrintWebProperties.ps1
vgrem_7550721_raw_76cfc8ee80f7395dd22abdb3471e916a5dc929d2_PrintWebProperties.ps1
Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.SharePoint.Client.dll' Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.SharePoint.Client.Runtime.dll' function PrintWebProperties() { param( [Parameter(Mandatory=$true)][string]$url, [Parameter(Mandatory=$false)][System.Net.NetworkCredential]$credentials ) $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($url) $ctx.Credentials = $credentials $web = $ctx.Web Invoke-LoadMethod -ClientObject $web $ctx.ExecuteQuery() Write-Host "Web Properties:" Write-Host "Title: $($web.Title)" Write-Host "Url: $($web.ServerRelativeUrl)" } $credentials = New-Object System.Net.NetworkCredential('username', 'password','domain') $url = 'http://contoso.intranet.com/' PrintWebProperties $url $credentials
PowerShellCorpus/GithubGist/GuruAnt_9185054_raw_e16c69c012905758182a327693755f648b286ac0_RemoveAppSenseCCAGUID.ps1
GuruAnt_9185054_raw_e16c69c012905758182a327693755f648b286ac0_RemoveAppSenseCCAGUID.ps1
# Remove AppSense CCA GUID # "Removing values" If (Get-ItemProperty -Path "HKLM:\Software\AppSense Technologies\Communications Agent" -name "machine id" -ErrorAction SilentlyContinue){ Remove-ItemProperty -Path "HKLM:\Software\AppSense Technologies\Communications Agent" -name "machine id" } If (Remove-ItemProperty -Path "HKLM:\Software\AppSense Technologies\Communications Agent" -name "group id" -ErrorAction SilentlyContinue){ Remove-ItemProperty -Path "HKLM:\Software\AppSense Technologies\Communications Agent" -name "group id" } # "Removing subkeys" Get-Childitem "HKLM:\Software\AppSense\Environment Manager" | Remove-Item # "Removing folders" If (Test-Path "%systemdrive%\AppSenseVirtual"){ Get-Childitem "%systemdrive%\AppSenseVirtual" | Remove-Item $_ }
PowerShellCorpus/GithubGist/rlaneve_1ed4ec2cdd5cbcd585db_raw_598b1f9b28a49e156a0329d1d8b0b3303fc9df34_boxstarter.ps1
rlaneve_1ed4ec2cdd5cbcd585db_raw_598b1f9b28a49e156a0329d1d8b0b3303fc9df34_boxstarter.ps1
# Run in IE: http://boxstarter.org/package/nr/url?https://URL_TO_THIS_GISTS_RAW_CONTENT Disable-UAC Update-ExecutionPolicy Unrestricted Set-StartScreenOptions -EnableBootToDesktop -EnableShowStartOnActiveScreen -EnableSearchEverywhereInAppsView -EnableListDesktopAppsFirst Set-CornerNavigationOptions -DisableUpperRightCornerShowCharms Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -EnableShowFileExtensions Enable-RemoteDesktop cinst IIS-WebServerRole -source windowsfeatures # Basics cinst launchy-beta cinst GoogleChrome cinst dropbox cinst 7zip.install cinst filezilla cinst git cinst gitextensions cinst poshgit cinst winmerge cinst Atom cinst SublimeText3 # Visual Studio cinst VisualStudio2013Professional -InstallArguments "/Features:'SQL WebTools'" cinst VS2013.4 cinst resharper cinst VS2013.PowerTools cinst editorconfig.vs # fonts cinst ubuntu.font cinst Inconsolata cinst SourceCodePro Install-WindowsUpdate -acceptEula <# Manually install: SSMS 2012 #>
PowerShellCorpus/GithubGist/blachniet_6063622_raw_696c3320946b2f1dca3b7ed4567238b38d6f13ef_PowerShellQuickies.ps1
blachniet_6063622_raw_696c3320946b2f1dca3b7ed4567238b38d6f13ef_PowerShellQuickies.ps1
################################################################################ # Run Files Last Accessed After Date Get-ChildItem C:\Input | Select-Object FullName, LastAccessTime | Where-Object {$_.LastAccessTime -g "01/01/2013"} %{.\SuperAwesomize.exe $_.FullName} ################################################################################ # Get full path of last file accessed item in directory # ? is short for Where-Object Get-ChildItem C:\Input | Sort-Object $_.LastAccessTime -Descending | ? { $_.psiscontainer -ne $true } | Select-Object -First 1 -ExpandProperty FullName ################################################################################ # Get whether the last command was a success # If it was not, write the last error if ($? -ne $true){ Write-Error $Error[0] } ################################################################################ # Help Block <# .SYNOPSIS Short description .DESCRIPTION Long description .PARAMETER LogName Parameter description .EXAMPLE .\ExampleCommand.ps1 Description ----------- Example command description .LINK http://blachniet.com #> ################################################################################ # Determine installed version of PowerShell $psversiontable $psversiontable.psversion ################################################################################ # Install all NuGet packages referenced in solution # Execute this from the solution dir (default if using Package Manager Console) Get-ChildItem -Path *\packages.config | % { nuget install $_.FullName -OutputDirectory packages } ################################################################################ # Copy some dlls to a subdir and remove the dot-separated version from them. Get-Item *.dll | % { Copy-Item -Path $_.FullName -Destination (Join-Path nover ($_.Name -replace "\.\d+\.\d+\.\d+\.\d+", ""))}
PowerShellCorpus/GithubGist/mattpodwysocki_1300037_raw_c88d12c50e764f493d3b1e51cc80c6d8d859fafe_download-entries.ps1
mattpodwysocki_1300037_raw_c88d12c50e764f493d3b1e51cc80c6d8d859fafe_download-entries.ps1
# --- settings --- $feedUrlBase = "http://go.microsoft.com/fwlink/?LinkID=206669" # the rest will be params when converting to funclet $latest = $true $overwrite = $false $top = 500 #use $top = $null to grab all $destinationDirectory = join-path "C:\\Dev" "LocalNuGet" # --- locals --- $webClient = New-Object System.Net.WebClient # --- functions --- # download entries on a page, recursively called for page continuations function DownloadEntries { param ([string]$feedUrl) $feed = [xml]$webClient.DownloadString($feedUrl) $entries = $feed.feed.entry $progress = 0 foreach ($entry in $entries) { $url = $entry.content.src $fileName = $entry.properties.id + "." + $entry.properties.version + ".nupkg" $saveFileName = join-path $destinationDirectory $fileName $pagepercent = ((++$progress)/$entries.Length*100) if ((-not $overwrite) -and (Test-Path -path $saveFileName)) { write-progress -activity "$fileName already downloaded" -status "$pagepercent% of current page complete" -percentcomplete $pagepercent continue } write-progress -activity "Downloading $fileName" -status "$pagepercent% of current page complete" -percentcomplete $pagepercent $webClient.DownloadFile($url, $saveFileName) } $link = $feed.feed.link | where { $_.rel.startsWith("next") } | select href if ($link -ne $null) { # if using a paged url with a $skiptoken like # http:// ... /Packages?$skiptoken='EnyimMemcached-log4net','2.7' # remember that you need to escape the $ in powershell with ` $feedUrl = $link.href DownloadEntries $feedUrl } } # the NuGet feed uses a fwlink which redirects # using this to follow the redirect function GetPackageUrl { param ([string]$feedUrlBase) $resp = [xml]$webClient.DownloadString($feedUrlBase) return $resp.service.GetAttribute("xml:base") } # --- do the actual work --- # if dest dir doesn't exist, create it if (!(Test-Path -path $destinationDirectory)) { New-Item $destinationDirectory -type directory } # set up feed URL $serviceBase = GetPackageUrl($feedUrlBase) $feedUrl = $serviceBase + "Packages" if($latest) { $feedUrl = $feedUrl + "?`$filter=IsLatestVersion eq true" if($top -ne $null) { $feedUrl = $feedUrl + "&`$orderby=DownloadCount desc&`$top=$top" } } DownloadEntries $feedUrl
PowerShellCorpus/GithubGist/andrewheiss_311147_raw_744446f538da63a351545cb4f32236ac06cdb545_Download%20Quran.ps1
andrewheiss_311147_raw_744446f538da63a351545cb4f32236ac06cdb545_Download%20Quran.ps1
# PowerShell Qur'an Downloader # # Author: Andrew Heiss - http://www.andrewheiss.com # Project site: http://gist.github.com/311147 # Description: Uses Windows PowerShell to download the Qur'an # License: Licensed under the MIT License (see below) # Date: February 22, 2010 # Version: 1.0 (February 22, 2010) # # #--------------- # INSTRUCTIONS #--------------- # # You must use Windows PowerShell to run this script! # # PowerShell is included in Windows 7. If you're running Vista or XP, you'll need to download PowerShell from http://support.microsoft.com/kb/968929 # # 1. Create the folder where you want to download everything (e.g. C:\Music\Quran\ or whatever) # 2. Save this file as `download.ps1` in the new folder. # 3. Open Windows PowerShell (search for it in the Start menu) # 4. Navigate to the new folder with the script in it (e.g. `cd C:\Music\Quran\`) # 5. You need to lower the permission levels of PowerScript to run any scripts. By default it disallows all scripts. Lame, yes. Type `Set-ExecutionPolicy RemoteSigned` at the prompt. # 6. Finally, type `.\download.ps1` to begin the massive automated download. #---------------- # ACTUAL SCRIPT #---------------- foreach ($i in 1..114 ) { $file = "{0:D3}" -f $i $path = "$pwd\$file.mp3" $url = "http://download.quranicaudio.com/quran/muhammad_siddeeq_al-minshaawee/$file.mp3" "Downloading [$url]`nSaving at [$path]" $client = new-object System.Net.WebClient $client.DownloadFile( $url, $path ) } #---------- # LICENSE #---------- # # PowerShell Qur'an Downloader is licensed under the MIT License: # # Copyright (c) 2010 Andrew Heiss (http://www.andrewheiss.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
PowerShellCorpus/GithubGist/PhilMarcuson_7ec4f1a3c0318c1fc574_raw_963b2269589f167fc77d30d88b69f6d73003e0d4_Office365PowerShellConnectionScripts.ps1
PhilMarcuson_7ec4f1a3c0318c1fc574_raw_963b2269589f167fc77d30d88b69f6d73003e0d4_Office365PowerShellConnectionScripts.ps1
# You must be running Windows PowerShell as an Administrator # Configure PowerShell to run scripts # -- http://technet.microsoft.com/en-us/library/hh849812.aspx # -- Note: You'll need registry edit access on the local machine to run the following command Set-ExecutionPolicy RemoteSigned # Pull in the Office 365 PowerShell module Import-Module MsOnline # Establish a reusable credential # -- This user must have global administrator rights in Office 365 $username = "username" $password = "password" $credential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force) # Connect to Office 365 with credential Connect-MsolService -Credential $credential <# You can now run Office 365 PowerShell cmdlets. To test your connection, run this command: Get-MsolDomain You should get back the domain associated to the Office 365 tenant #> # Pull in the SharePoint Online PowerShell module Import-Module Microsoft.Online.SharePoint.PowerShell # Connect to SharePoint Online # -- The url used should be the url of the admin site for the tenant. Format: https://domainhost.sharepoint.com # -- If you get an error message about unapproved verbs, it is safe to ignore the warning. Connect-SPOService -Url https://<domainhost>.sharepoint.com -credential $credential <# You can now run SharePoint Online cmdlets. To test your connection, run this command: Get-SPOSite You should get back a list of all your SharePoint Online sites. #> # Pull in the Lync Online PowerShell module Import-Module LyncOnlineConnector # Establish a remote PowerShells session with the Lync Online servers $lyncSession = New-CsOnlineSession -Credential $credential # Start the Lync Online remote PowerShell session Import-PSSession $lyncSession # -- Wait for creation of implicit remoting module to complete <# You can now run Lync Online cmdlets. To test your connection, run this command: Get-CsMeetingConfiguration You should get back the meeting configuration attributes set in Lync #> # Establish a remote PowerShell session with the Exchange Online servers # -- It is save to ignore the warning message about the connection being redirected $exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $credential -Authentication "Basic" -AllowRedirection # Start the Exchange Online remote PowerShell session # -- If you get an error message about unapproved verbs, it is safe to ignore the warning. Import-PSSession $exchangeSession <# You can now run Exchange Online cmdlets. To test your connection, run this command: Get-AcceptedDomain You should get back information about your Exchange Online domain. #> <# ---------- You can now manage all of Office 365 from this single PowerShell session. Important! Once you are done, remember to close your remote sessions ---------- #> # Get a list or your remote PowerShell sessions Get-PSSession # Close the sessions created in this script Remove-PSSession $lyncSession Remove-PSSession $exchangeSession # You could also close all sessions by running this script: Get-PSSession | Remove-PSSession # Disconnect from SharePoint Online Disconnect-SPOService # Close the PowerShell Window
PowerShellCorpus/GithubGist/peaeater_d6ab025d108308d4733e_raw_d1c0d296b348081ef8cca98b494a4b8a648212b3_push-dir-to-remote.ps1
peaeater_d6ab025d108308d4733e_raw_d1c0d296b348081ef8cca98b494a4b8a648212b3_push-dir-to-remote.ps1
<# Sync a directory to remote server via WinSCP in SFTP mode. - Uses SFTP instead of SCP to deny any shell commands to the user, just file transfer. - Use a chrooted user on remote server (user jailed to their root dir). - Writes to Application Event Log; log source must already have been added Peter Tyrrell #> param( [Parameter(Mandatory=$false,Position=0)] [string]$logsrc = "Andi Solr Update" ) $hostname = "xxx.yyy.zzz" $username = "user1" $password = "a totally legit pw" #$keypath = "XXX" $fingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" $remotePath = "/output" $localPath = "c:\path\to\files" $winscpPath = "c:\path\to\WinSCPNet.dll" function logError([string]$msg) { # write error msg to Application EventLog Write-EventLog -LogName Application -Source $logsrc -EventId 500 -EntryType Error -Message $msg -Category 0 Write-Host ("ERROR {0}" -f $msg) } function logInfo([string]$msg) { # write info msg to Application EventLog Write-EventLog -LogName Application -Source $logsrc -EventId 200 -EntryType Information -Message $msg -Category 0 Write-Host ("INFO {0}" -f $msg) } function logWarning([string]$msg) { # write warning msg to Application EventLog Write-EventLog -LogName Application -Source $logsrc -EventId 400 -EntryType Warning -Message $msg -Category 0 Write-Host ("WARNING {0}" -f $msg) } function fileTransferred { param($e) # file transfer status if ($e.Error -eq $null) { Write-Host ("INFO {0} upload OK" -f $e.FileName) } else { Write-Host ("ERROR {0} upload failure: {1}" -f $e.FileName, $e.Error) } # file permissions status if ($e.Chmod -ne $null) { if ($e.Chmod.Error -ne $null) { Write-Host ("ERROR {0} set permissions failure: {1}" -f $e.Chmod.FileName, $e.Chmod.Error) } } # timestamp status if ($e.Touch -ne $null) { if ($e.Touch.Error -ne $null) { Write-Host ("ERROR {0} set timestamp failure: {1}" -f $e.Touch.FileName, $e.Touch.Error) } } } <# Push files to remote server. #> try { # load winscp assembly Add-Type -Path $winscpPath # session options $sessionOptions = New-Object WinSCP.SessionOptions $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp $sessionOptions.HostName = $hostname $sessionOptions.UserName = $username $sessionOptions.Password = $password #$sessionOptions.SshPrivateKeyPath = $keypath $sessionOptions.SshHostKeyFingerprint = $fingerprint $session = New-Object WinSCP.Session # sync dirs try { # continuously report sync progress $session.add_FileTransferred( { fileTransferred($_) } ) # connect $session.Open($sessionOptions) # sync files 1 direction, from local => remote. Push all local files, newer and older, and delete obsolete remote files. $syncResult = $session.SynchronizeDirectories([WinSCP.SynchronizationMode]::Remote, $localPath, $remotePath, $true, $true) # throw exception for any error $syncResult.Check() $uploadCount = $syncResult.Uploads.Count $downloadCount = $syncResults.Downloads.Count $removalCount = $syncResults.Removals.Count logInfo(("File sync to {0} successful: {1} uploaded, {2} downloaded, {3} removed." -f $hostname, $uploadCount, $downloadCount, $removalCount)) } finally { # disconnect, clean up $session.Dispose() } exit 0 } catch [Exception] { # any exception bubbles up here logError($_.Exception) exit 1 }
PowerShellCorpus/GithubGist/smasterson_9136468_raw_2c171d161212d3ffe364a7ab2111c99072f4073b_MyVeeamReport.ps1
smasterson_9136468_raw_2c171d161212d3ffe364a7ab2111c99072f4073b_MyVeeamReport.ps1
asnp "VeeamPSSnapIn" -ErrorAction SilentlyContinue #region User-Variables # Report Title $rptTitle = "My Veeam Report" # Report mode - valid modes: any number of hours, Weekly or Monthly # 24, 48, "Weekly", "Monthly" $reportMode = 24 # Save output to a file - $true or $false $saveFile = $true # File output path and filename $outFile = "E:\MyVeeamReport_$(Get-Date -format MMddyyyy_hhmmss).htm" # Launch file after creation - $true or $false $launchFile = $false # Show VMs with no successful backups within time frame ($reportMode) $showMissing = $true # Show VMs with successful backups within time frame ($reportMode) $showSuccess = $true # vCenter server(s) - As seen in VBR server #$vcenters = "vcenter1","vcenter2" $vcenters = "vcenter.yourdomain.local" # To Exclude VMs from Missing and Successful Backups report add VM names to be excluded as follows # $excludevms = @("vm1","vm2","*_replica") $excludeVMs = @("") # Exclude VMs from Missing and Successful Backups report in the following (vcenter) folder $folderExclude = "" # Show jobs w/warnings or errors $jlines = $true # Show running jobs $rlines = $true # Show running Services $runningSvc = $true # Location of Veeam executable (Veeam.Backup.Shell.exe) $veeamExePath = "C:\Program Files\Veeam\Backup and Replication\Backup\Veeam.Backup.Shell.exe" # Location of common dll - Needed for repository function - Get-vPCRepoInfo (Veeam.Backup.Core.dll) $veeamDllPath = "C:\Program Files\Veeam\Backup and Replication\Backup\Veeam.Backup.Core.dll" # Email configuration # Send Email - $true or $false $sendEmail = $false $emailHost = "smtprelay.yourdomain.local" $emailUser = "" $emailPass = "" $emailFrom = "MyVeeamReport@yourdomain.local" $emailTo = "you@yourdomain.local" # Send report as attachment - $true or $false $emailAttach = $false # Highlighting Thresholds # Repository Free Space Remaining % $repoCritical = 10 $repoWarn = 20 # Replica Target Free Space Remaining % $replicaCritical = 10 $replicaWarn = 20 # License Days Remaining $licenseCritical = 30 $licenseWarn = 90 #endregion #region VersionInfo $vPCARversion = "1.3" # # Version 1.3 - SM # Now supports VBR v8 # For VBR v7, use report version 1.2 # Added more flexable options to save and launch file # # Version 1.2 - SM # Added option to show VMs successfully backed up # # Version 1.1.4 - SM # Misc tweaks/bug fixes # Reconfigured HTML a bit to help with certain email clients # Added cell coloring to highlight status # Added $rptTitle variable to hold report title # Added ability to send report via email as attachment # # Version 1.1.3 - SM # Added Details to Sessions with Warnings or Failures # # Version 1.1.2 - SM # Minor tweaks/updates # Added Veeam version info to header # # Version 1.1.1 - Shawn Masterson # Based on vPowerCLI v6 Army Report (v1.1) by Thomas McConnell # http://www.vpowercli.co.uk/2012/01/23/vpowercli-v6-army-report/ # http://pastebin.com/6p3LrWt7 # # Tweaked HTML header (color, title) # # Changed report width to 1024px # # Moved hard-coded path to exe/dll files to user declared variables ($veeamExePath/$veeamDllPath) # # Adjusted sorting on all objects # # Modified info group/counts # Modified - Total Jobs = Job Runs # Added - Read (GB) # Added - Transferred (GB) # Modified - Warning = Warnings # Modified - Failed = Failures # Added - Failed (last session) # Added - Running (currently running sessions) # # Modified job lines # Renamed Header - Sessions with Warnings or Failures # Fixed Write (GB) - Broke with v7 # # Added support license renewal # Credit - Gavin Townsend http://www.theagreeablecow.com/2012/09/sysadmin-modular-reporting-samreports.html # Original Credit - Arne Fokkema http://ict-freak.nl/2011/12/29/powershell-veeam-br-get-total-days-before-the-license-expires/ # # Modified Proxy section # Removed Read/Write/Util - Broke in v7 - Workaround unknown # # Modified Services section # Added - $runningSvc variable to toggle displaying services that are running # Added - Ability to hide section if no results returned (all services are running) # Added - Scans proxies and repositories as well as the VBR server for services # # Added VMs Not Backed Up section # Credit - Tom Sightler - http://sightunseen.org/blog/?p=1 # http://www.sightunseen.org/files/vm_backup_status_dev.ps1 # # Modified $reportMode # Added ability to run with any number of hours (8,12,72 etc) # Added bits to allow for zero sessions (semi-gracefully) # # Added Running Jobs section # Added ability to toggle displaying running jobs # # Added catch to ensure running v7 or greater # # # Version 1.1 # Added job lines as per a request on the website # # Version 1.0 # Clean up for release # # Version 0.9 # More cmdlet rewrite to improve perfomace, credit to @SethBartlett # for practically writing the Get-vPCRepoInfo # # Version 0.8 # Added Read/Write stats for proxies at requests of @bsousapt # Performance improvement of proxy tear down due to rewrite of cmdlet # Replaced 2 other functions # Added Warning counter, .00 to all storage returns and fetch credentials for # remote WinLocal repos # # Version 0.7 # Added Utilisation(Get-vPCDailyProxyUsage) and Modes 24, 48, Weekly, and Monthly # Minor performance tweaks #endregion #region NonUser-Variables # Get the B&R Server $vbrServer = Get-VBRLocalHost # Get all the VI proxies in your army $viProxyList = Get-VBRViProxy # Get all the backup repositories $repoList = Get-VBRBackupRepository # Get unique repo servers $uniqueRepos = @() $repolist | %{$uniqueRepos += $($_.gethost().realname)} $uniqueRepos = $uniqueRepos | Sort -unique # Get all sessions to determine working jobs $allSesh = Get-VBRBackupSession # Get all the backup sessions for mode if ($reportMode -eq "Monthly") { $HourstoCheck = 720 } elseif ($reportMode -eq "Weekly") { $HourstoCheck = 168 } else { $HourstoCheck = $reportMode } $seshList = $allSesh | ?{($_.CreationTime -ge (Get-Date).AddHours(-$HourstoCheck)) -and ($_.State -ne "Working")} if (($reportMode -ne "Weekly") -And ($reportMode -ne "Monthly")) { $rptTitle = "$rptTitle (Last $reportMode Hrs)" } else { $rptTitle = "$rptTitle ($reportMode)" } #Get replica jobs $repList = Get-VBRJob | ?{$_.IsReplica} # Get the job counts $totalxfer = $null $totalRead = $null $seshList | %{$totalxfer += $([Math]::Round([Decimal]$_.Progress.TransferedSize/1GB, 2))} $seshList | %{$totalRead += $([Math]::Round([Decimal]$_.Progress.ReadSize/1GB, 2))} $succesSessions = @($seshList | ?{$_.Result -eq "Success"}) $warningSessions = @($seshList | ?{$_.Result -eq "Warning"}) $failsSessions = @($seshList | ?{$_.Result -eq "Failed"}) $totalSessions = @($seshList | ?{$_.Result -eq "Failed" -Or $_.Result -eq "Success" -Or $_.Result -eq "Warning"}) $runningSessions = @($allSesh | ?{$_.State -eq "Working"}) $failedSessions = @($seshList | ?{($_.Result -eq "Failed") -and ($_.WillBeRetried -ne "True")}) #endregion #region Functions function Get-vPCProxyInfo { [CmdletBinding()] param ( [Parameter(Position=0)] [String[]]$Name, [Parameter(Mandatory=$true, Position=1)] [PSObject[]]$Sessions ) Begin { $vPCObjAry = @() [Int]$script:jobcount = 0 [Int]$totalObjInJob = 0 $cleanSessions = $Sessions | ?{($_.Result -ne "Failed") -and ($_.State -eq "Stopped") -and ($_.JobType -ne "Copy")} $cleanSessions | %{$totalObjInJob = $totalObjInJob + $_.Progress.TotalObjects} | Out-Null function Build-vPCObj {param ([PsObject]$inputObj) $ping = new-object system.net.networkinformation.ping $pinginfo = $ping.send("$($inputObj.Host.RealName)") if ($pinginfo.Status -eq "Success") { $hostAlive = "Alive" } else { $hostAlive = "Dead" } $vPCFuncObject = New-Object PSObject -Property @{ ProxyName = $inputObj.Name RealName = $inputObj.Host.RealName.ToLower() Disabled = $inputObj.IsDisabled Status = $hostAlive IP = $pinginfo.Address Responce = $pinginfo.RoundtripTime ReadData = [Decimal]0.00 WriteData = [Decimal]0.00 UsageCount = 0 ProxiesInSessions = $($totalObjInJob*2) } return $vPCFuncObject } function Get-vPCProxyName {param ([String]$title) $titleAry = @($title.Split()) $ai = 3 $bi = $titleAry.count - 1 while ($ai -ne $bi) { $proxyString = $proxyString + " " + $titleAry[$ai] $ai ++ } return $proxyString.Trim() } function Get-vPCProxyRole {param ([String]$title) $titleAry = @($title.Split()) $roleString = $titleAry[1] return $roleString } Get-VBRViProxy | %{$vPCObjAry = $vPCObjAry + $(Build-vPCObj $_)} } Process { if ($Name -ne $null) { $output = $vPCObjAry | ?{$Name -like $_.ProxyName} } else { $output = $vPCObjAry } } End { $output } } function Get-vPCRepoInfo { [CmdletBinding()] param ( [Parameter(Position=0, ValueFromPipeline=$true)] [PSObject[]]$Repository ) Begin { $outputAry = @() [Reflection.Assembly]::LoadFile($veeamDllPath) | Out-Null function Build-Object {param($name, $path, $free, $total) $repoObj = New-Object -TypeName PSObject -Property @{ Target = $name Storepath = $path StorageFree = [Math]::Round([Decimal]$free/1GB,2) StorageTotal = [Math]::Round([Decimal]$total/1GB,2) FreePercentage = [Math]::Round(($free/$total)*100) } return $repoObj | Select Target, Storepath, StorageFree, StorageTotal, FreePercentage } } Process { foreach ($r in $Repository) { if ($r.GetType().Name -eq [String]) { $r = Get-VBRBackupRepository -Name $r } if ($r.Type -eq "WinLocal") { $Server = $r.GetHost() $FileCommander = [Veeam.Backup.Core.CWinFileCommander]::Create($Server.Info) $storage = $FileCommander.GetDrives([ref]$null) | ?{$_.Name -eq $r.Path.Substring(0,3)} $outputObj = Build-Object $r.Name $r.Path $storage.FreeSpace $storage.TotalSpace } elseif ($r.Type -eq "LinuxLocal") { $Server = $r.GetHost() $FileCommander = new-object Veeam.Backup.Core.CSshFileCommander $server.info $storage = $FileCommander.FindDirInfo($r.Path) $outputObj = Build-Object $r.Name $r.Path $storage.FreeSpace $storage.TotalSize } elseif ($r.Type -eq "CifsShare") { $fso = New-Object -Com Scripting.FileSystemObject $storage = $fso.GetDrive($r.Path) $outputObj = Build-Object $r.Name $r.Path $storage.AvailableSpace $storage.TotalSize } $outputAry = $outputAry + $outputObj } } End { $outputAry } } function Get-vPCReplicaTarget { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [PSObject[]]$InputObj ) BEGIN { $outputAry = @() $dsAry = @() if (($Name -ne $null) -and ($InputObj -eq $null)) { $InputObj = Get-VBRJob -Name $Name } } PROCESS { foreach ($obj in $InputObj) { if (($dsAry -contains $obj.ViReplicaTargetOptions.DatastoreName) -eq $false) { $esxi = $obj.GetTargetHost() $dtstr = $esxi | Find-VBRViDatastore -Name $obj.ViReplicaTargetOptions.DatastoreName $objoutput = New-Object -TypeName PSObject -Property @{ Target = $esxi.Name Datastore = $obj.ViReplicaTargetOptions.DatastoreName StorageFree = [Math]::Round([Decimal]$dtstr.FreeSpace/1GB,2) StorageTotal = [Math]::Round([Decimal]$dtstr.Capacity/1GB,2) FreePercentage = [Math]::Round(($dtstr.FreeSpace/$dtstr.Capacity)*100) } $dsAry = $dsAry + $obj.ViReplicaTargetOptions.DatastoreName $outputAry = $outputAry + $objoutput } else { return } } } END { $outputAry | Select Target, Datastore, StorageFree, StorageTotal, FreePercentage } } function Get-VeeamVersion { $veeamExe = Get-Item $veeamExePath $VeeamVersion = $veeamExe.VersionInfo.ProductVersion Return $VeeamVersion } function Get-VeeamSupportDate { #Get version and license info $regBinary = (Get-Item 'HKLM:\SOFTWARE\Veeam\Veeam Backup and Replication\license').GetValue('Lic1') $veeamLicInfo = [string]::Join($null, ($regBinary | % { [char][int]$_; })) if($script:VeeamVersion -like "6*"){ $pattern = "Expiration date\=\d{1,2}\/\d{1,2}\/\d{1,4}" } elseif($script:VeeamVersion -like "5*"){ $pattern = "EXPIRATION DATE\=\d{1,2}\/\d{1,2}\/\d{1,4}" } elseif($script:VeeamVersion -like "8*"){ $pattern = "expiration date\=\d{1,2}\/\d{1,2}\/\d{1,4}" } # Convert Binary key if($script:VeeamVersion -like "5*" -OR $script:VeeamVersion -like "6*" -OR $script:VeeamVersion -like "8*"){ $expirationDate = [regex]::matches($VeeamLicInfo, $pattern)[0].Value.Split("=")[1] $datearray = $expirationDate -split '/' $datearray = $datearray[1],$datearray[0],$datearray[2] $expirationDate = $datearray -join '/' $totalDaysLeft = ((Get-Date $expirationDate) - (get-date)).Totaldays.toString().split(",")[0] $totalDaysLeft = [int]$totalDaysLeft $objoutput = New-Object -TypeName PSObject -Property @{ ExpDate = $expirationDate DaysRemain = $totalDaysLeft } $objoutput } else{ $objoutput = New-Object -TypeName PSObject -Property @{ ExpDate = "Failed" DaysRemain = "Failed" } $objoutput } } function Get-VeeamServers { $vservers=@{} $outputAry = @() $vservers.add($($script:vbrserver.realname),"VBRServer") foreach ($srv in $script:viProxyList) { If (!$vservers.ContainsKey($srv.Host.Realname)) { $vservers.Add($srv.Host.Realname,"ProxyServer") } } foreach ($srv in $script:repoList) { If (!$vservers.ContainsKey($srv.gethost().Realname)) { $vservers.Add($srv.gethost().Realname,"RepoServer") } } $vservers = $vservers.GetEnumerator() | Sort-Object Name foreach ($vserver in $vservers) { $outputAry += $vserver.Name } return $outputAry } function Get-VeeamServices { param ( [PSObject]$inputObj) $outputAry = @() foreach ($obj in $InputObj) { $output = Get-Service -computername $obj -Name "*Veeam*" -exclude "SQLAgent*" | Select @{Name="Server Name"; Expression = {$obj}}, @{Name="Service Name"; Expression = {$_.DisplayName}}, Status $outputAry = $outputAry + $output } $outputAry } function Get-VMsBackupStatus { param ( [String]$vcenter) $outputary = @() $vcenterobj = Get-VBRServer -Name $vcenter $vmobjs = Find-VBRObject -Server $vcenterobj | Where-Object {$_.Type -eq "VirtualMachine" -and $_.VMFolderName -notlike $script:folderExclude} $jobobjids = [Veeam.Backup.Core.CHierarchyObj]::GetObjectsOnHost($vcenterobj.id) | Where-Object {$_.Type -eq "Vm"} # Convert exclusion list to simple regular expression $excludevms_regex = (‘(?i)^(‘ + (($script:excludevms | ForEach {[regex]::escape($_)}) –join “|”) + ‘)$’) -replace "\\\*", ".*" foreach ($vm in $vmobjs) { $jobobjid = ($jobobjids | Where-Object {$_.ObjectId -eq $vm.Id}).Id if (!$jobobjid) { $jobobjid = $vm.FindParent("Datacenter").Id + "\" + $vm.Id } $vm | Add-Member -MemberType NoteProperty "JobObjId" -Value $jobobjid } # Get a list of all VMs from vCenter and add to hash table, assume Unprotected $vms=@{} foreach ($vm in ($vmobjs | where {$_.Name -notmatch $excludevms_regex})) { if(!$vms.ContainsKey($vm.JobObjId)) { $vms.Add($vm.JobObjId, @("!", [string]$vm.GetParent("Datacenter"), $vm.Name)) } } # Find all backup job sessions that have ended in the last x hours $vbrjobs = Get-VBRJob | Where-Object {$_.JobType -eq "Backup"} $vbrsessions = Get-VBRBackupSession | Where-Object {$_.JobType -eq "Backup" -and $_.EndTime -ge (Get-Date).addhours(-$script:HourstoCheck)} # Find all successfully backed up VMs in selected sessions (i.e. VMs not ending in failure) and update status to "Protected" if ($vbrsessions) { foreach ($session in $vbrsessions) { foreach ($vm in ($session.gettasksessions() | Where-Object {$_.Status -ne "Failed"} | ForEach-Object { $_ })) { if($vms.ContainsKey($vm.Info.ObjectId)) { $vms[$vm.Info.ObjectId][0]=$session.JobName } } } } $vms.GetEnumerator() | Sort-Object Value } function Get-VMsMissingBackup { param ( $vms) $outputary = @() foreach ($vm in $vms) { if ($vm.Value[0] -eq "!") { $objoutput = New-Object -TypeName PSObject -Property @{ Datacenter = $vm.Value[1] Name = $vm.Value[2] } $outputAry += $objoutput } } $outputAry | Select Datacenter, Name | Sort Name } function Get-VMsSuccessBackup { param ( $vms) $outputary = @() foreach ($vm in $vms) { if ($vm.Value[0] -ne "!") { $objoutput = New-Object -TypeName PSObject -Property @{ Datacenter = $vm.Value[1] Name = $vm.Value[2] } $outputAry += $objoutput } } $outputAry | Select Datacenter, Name | Sort Name } #endregion #region Report # Get Veeam Version $VeeamVersion = Get-VeeamVersion If ($VeeamVersion -lt 8) { Write-Host "Script requires VBR v8 or greater" -ForegroundColor Red exit } # HTML Stuff $headerObj = @" <html> <head> <title>$rptTitle</title> <style> body {font-family: Tahoma; background-color:#fff;width: 1024px;} table {font-family: Tahoma;width: 1024px;font-size: 12px;border-collapse:collapse;} <!-- table tr:nth-child(odd) td {background: #e2e2e2;} --> th {background-color: #cccc99;border: 1px solid #a7a9ac;border-bottom: none;} td {background-color: #ffffff;border: 1px solid #a7a9ac;padding: 2px 3px 2px 3px;vertical-align: top;} </style> </head> "@ $bodyTop = @" <body> <table cellspacing="0" cellpadding="0"> <tr> <td style="width: 80%;height: 45px;border: none;background-color: #003366;color: White;font-size: 24px;vertical-align: bottom;padding: 0px 0px 0px 15px;">$rptTitle</td> <td style="width: 30%;height: 45px;border: none;background-color: #003366;color: White;font-size: 12px;vertical-align:text-top;text-align:right;padding: 2px 3px 2px 3px;">v$vPCARversion<br>Veeam v$VeeamVersion</td> </tr> <tr> <td style="width: 80%;height: 35px;border: none;background-color: #003366;color: White;font-size: 10px;vertical-align: bottom;padding: 0px 0px 2px 3px;">Report generated: $(Get-Date -format g)</font></td> <td style="width: 30%;height: 35px;border: none;background-color: #003366;color: White;font-size: 10px;vertical-align:bottom;text-align:right;padding: 2px 3px 2px 3px;">Based on:<br><a href="http://www.vpowercli.co.uk/2012/01/23/vpowercli-v6-army-report/" target="_blank"><font color="White">vPowerCLI v6 Army Report</font></a></td> </tr> </table> "@ $subHead01 = @" <table> <tr> <td style="height: 35px;background-color: #eeeeee;color: #003366;font-size: 16px;font-weight: bold;vertical-align: middle;padding: 5px 0 0 15px;border-top: none;border-bottom: none;"> "@ $subHead01err = @" <table> <tr> <td style="height: 35px;background-color: #eeeeee;color: #FF0000;font-size: 16px;font-weight: bold;vertical-align: middle;padding: 5px 0 0 15px;border-top: none;border-bottom: none;"> "@ $subHead02 = @" </td> </tr> </table> "@ $footerObj = @" </body> </html> "@ # Get Summary Info $vbrMasterHash = @{"Coordinator" = "$((gc env:computername).ToLower())"; "Failed" = $failedSessions.Count; "Sessions" = $totalSessions.Count; "Read" = $totalRead; "Transferred" = $totalXfer; "Successfull" = $succesSessions.Count; "Warning" = $warningSessions.Count; "Fails" = $failsSessions.Count; "Running" = $runningSessions.Count;} $vbrMasterObj = New-Object -TypeName PSObject -Property $vbrMasterHash $bodyMasterT = $vbrMasterObj | Select Coordinator, @{Name="Job Runs"; Expression = {$_.Sessions}}, @{Name="Read (GB)"; Expression = {$_.Read}}, @{Name="Transferred (GB)"; Expression = {$_.Transferred}}, @{Name="Running"; Expression = {$_.Running}}, @{Name="Successfull"; Expression = {$_.Successfull}}, @{Name="Warnings"; Expression = {$_.Warning}}, @{Name="Failures"; Expression = {$_.Fails}}, @{Name="Failed"; Expression = {$_.Failed}} | ConvertTo-HTML -Fragment #Get VM Backup Status If ($showMissing -or $showSuccess) { $vmstatus = @() foreach ($vcenter in $vcenters) { $status = Get-VMsBackupStatus $vcenter $vmstatus += $status } } # Get VMs Missing Backups $bodyMissing = $null $missingVMs = @() If ($showMissing) { $missingVMs = Get-VMsMissingBackup $vmstatus If ($missingVMs -ne $null) { $missingVMs = $missingVMs | Sort Datacenter, Name | ConvertTo-HTML -Fragment $bodyMissing = $subHead01err + "VMs with no successful backups" + $subHead02 + $missingVMs } } # Get VMs Successfully Backed Up $bodySuccess = $null $successVMs = @() If ($showSuccess) { $successVMs = Get-VMsSuccessBackup $vmstatus If ($successVMs -ne $null) { $successVMs = $successVMs | Sort Datacenter, Name | ConvertTo-HTML -Fragment $bodySuccess = $subHead01 + "VMs with successful backups" + $subHead02 + $successVMs } } # Get Running Jobs $bodyrLines = $null if ($rlines -eq $true) { if ($runningSessions.count -gt 0) { $bodyrLines = $runningSessions | Sort Creationtime | Select @{Name="Job Name"; Expression = {$_.Name}}, @{Name="Start Date"; Expression = {$_.Progress.StartTime.ToShortDateString()}}, @{Name="Start Time"; Expression = {$_.Progress.StartTime.ToShortTimeString()}}, @{Name="Duration"; Expression = {Get-Date "$($_.Progress.Duration)" -f HH:mm:ss}}, @{Name="Read (GB)"; Expression = {[Math]::Round([Decimal]$_.Progress.ReadSize/1GB, 2)}}, @{Name="Write (GB)"; Expression = {[Math]::Round([Decimal]$_.Progress.TransferedSize/1GB, 2)}} | ConvertTo-HTML -Fragment $bodyrLines = $subHead01 + "Running Jobs" + $subHead02 + $bodyrLines } } # Get Jobs with Failures or Warnings $bodyjLines = $null if ($jlines -eq $true) { $counter = @($seshList | ?{($_.Result -eq "Warning") -or ($_.Result -eq "Failed")}) if ($counter.count -gt 0) { $bodyjLines = $seshList | ?{($_.Result -eq "Warning") -or ($_.Result -eq "Failed")} | Sort Creationtime | Select @{Name="Job Name"; Expression = {$_.Name}}, @{Name="Start Date"; Expression = {$_.Progress.StartTime.ToShortDateString()}}, @{Name="Start Time"; Expression = {$_.Progress.StartTime.ToShortTimeString()}}, @{Name="Stop Time"; Expression = {$_.Progress.StopTime.ToShortTimeString()}}, @{Name="Details"; Expression = {($_.GetDetails()).Replace("<br />"," - ")}},Result | ConvertTo-HTML -Fragment $bodyjLines = $subHead01 + "Sessions with Warnings or Failures" + $subHead02 + $bodyjLines } } # Get Proxy Info $bodyProxy = $null if ($viProxyList -ne $null -And $seshList -ne $null) { $bodyProxy = Get-vPCProxyInfo -Sessions $seshList | Select @{Name="Proxy Host"; Expression = {$_.RealName}}, Disabled, @{Name="IP Address"; Expression = {$_.IP}}, @{Name="RT (ms)"; Expression = {$_.Responce}}, Status | Sort "Proxy Host" | ConvertTo-HTML -Fragment $bodyProxy = $subHead01 + "Proxy Details" + $subHead02 + $bodyProxy } # Get Repository Info $bodyRepo = $null if ($repoList -ne $null) { $bodyRepo = $repoList | Get-vPCRepoInfo | Select @{Name="Repository Name"; Expression = {$_.Target}}, @{Name="Path"; Expression = {$_.Storepath}}, @{Name="Free (GB)"; Expression = {$_.StorageFree}}, @{Name="Total (GB)"; Expression = {$_.StorageTotal}}, @{Name="Free (%)"; Expression = {$_.FreePercentage}}, @{Name="Status"; Expression = {If ($_.FreePercentage -lt $repoCritical) {"Critical"} ElseIf ($_.FreePercentage -lt $repoWarn) {"Warning"} Else {"OK"}}} | ` Sort "Repository Name" | ConvertTo-HTML -Fragment $bodyRepo = $subHead01 + "Repository Details" + $subHead02 + $bodyRepo } # Get Replica Target Info $bodyReplica = $null if ($repList -ne $null) { $bodyReplica = $repList | Get-vPCReplicaTarget | Select @{Name="Replica Target"; Expression = {$_.Target}}, Datastore, @{Name="Free (GB)"; Expression = {$_.StorageFree}}, @{Name="Total (GB)"; Expression = {$_.StorageTotal}}, @{Name="Free (%)"; Expression = {$_.FreePercentage}}, @{Name="Status"; Expression = {If ($_.FreePercentage -lt $replicaCritical) {"Critical"} ElseIf ($_.FreePercentage -lt $replicaWarn) {"Warning"} Else {"OK"}}} | ` Sort "Replica Target" | ConvertTo-HTML -Fragment $bodyReplica = $subHead01 + "Replica Details" + $subHead02 + $bodyReplica } # Get Veeam Services Info $bodyServices = Get-VeeamServers $bodyServices = Get-VeeamServices $bodyServices If ($runningSvc -ne $true) {$bodyServices = $bodyServices | ?{$_.Status -ne "Running"}} If ($bodyServices -ne $null) { $bodyServices = $bodyServices | Select "Server Name", "Service Name", Status | Sort "Server Name", "Service Name" | ConvertTo-HTML -Fragment $bodyServices = $subHead01 + "Services" + $subHead02 + $bodyServices } # Get License Info $bodyLicense = Get-VeeamSupportDate | Select @{Name="Expiry Date"; Expression = {$_.ExpDate}}, @{Name="Days Remaining"; Expression = {$_.DaysRemain}}, ` @{Name="Status"; Expression = {If ($_.DaysRemain -lt $licenseCritical) {"Critical"} ElseIf ($_.DaysRemain -lt $licenseWarn) {"Warning"} ElseIf ($_.DaysRemain -eq "Failed") {"Failed"} Else {"OK"}}} | ` ConvertTo-HTML -Fragment $bodyLicense = $subHead01 + "License/Support Renewal Date" + $subHead02 + $bodyLicense # Combine HTML Output $htmlOutput = $headerObj + $bodyTop + $bodyMasterT + $bodyMissing + $bodySuccess + $bodyrLines + $bodyjLines + $bodyRepo + $bodyProxy + $bodyReplica + $bodyServices + $bodyLicense + $footerObj # Add color to output depending on results $htmlOutput = $htmlOutput.Replace("<td>Running<","<td style=""background-color: Green;color: White;"">Running<") $htmlOutput = $htmlOutput.Replace("<td>OK<","<td style=""background-color: Green;color: White;"">OK<") $htmlOutput = $htmlOutput.Replace("<td>Alive<","<td style=""background-color: Green;color: White;"">Alive<") $htmlOutput = $htmlOutput.Replace("<td>Warning<","<td style=""background-color: Yellow;"">Warning<") $htmlOutput = $htmlOutput.Replace("<td>Stopped<","<td style=""background-color: Red;color: White;"">Stopped<") $htmlOutput = $htmlOutput.Replace("<td>Failed<","<td style=""background-color: Red;color: White;"">Failed<") $htmlOutput = $htmlOutput.Replace("<td>Critical<","<td style=""background-color: Red;color: White;"">Critical<") $htmlOutput = $htmlOutput.Replace("<td>Dead<","<td style=""background-color: Red;color: White;"">Dead<") #endregion #region Output if ($sendEmail) { $emailSubject = $rptTitle $smtp = New-Object System.Net.Mail.SmtpClient $emailHost $smtp.Credentials = New-Object System.Net.NetworkCredential($emailUser, $emailPass); $msg = New-Object System.Net.Mail.MailMessage($emailFrom, $emailTo) $msg.Subject = $emailSubject If ($emailAttach) { $body = "Veeam Report Attached" $msg.Body = $body $tempfile = "$env:TEMP\$rptTitle.htm" $htmlOutput | Out-File $tempfile $attachment = new-object System.Net.Mail.Attachment $tempfile $msg.Attachments.Add($attachment) } Else { $body = $htmlOutput $msg.Body = $body $msg.isBodyhtml = $true } $smtp.send($msg) If ($emailAttach) { $attachment.dispose() Remove-Item $tempfile } } If ($saveFile) { $htmlOutput | Out-File $outFile If ($launchFile) { Invoke-Expression $outFile } } #endregion
PowerShellCorpus/GithubGist/Romoku_4004076_raw_cdca9bcd28d549f43cbdb16be837af3beed0ef42_logger.ps1
Romoku_4004076_raw_cdca9bcd28d549f43cbdb16be837af3beed0ef42_logger.ps1
param( [String]$filePath="", [String]$fileName="" ) $logFile = "C:\temp\log.txt" Function Log($fileName, $filePath) { $currentDate = Get-Date Add-Content $logFile "File Name: ${fileName} FileP Path: ${filePath}" } Log $fileName $filePath
PowerShellCorpus/GithubGist/sandrinodimattia_3645633_raw_9184bebb1caebb32d59a748d155f0e0f6c40dcfa_gistfile1.ps1
sandrinodimattia_3645633_raw_9184bebb1caebb32d59a748d155f0e0f6c40dcfa_gistfile1.ps1
param([string]$ConnectionString = $(throw "The ConnectionString parameter is required."), [string]$DatabaseName = $(throw "The DatabaseName parameter is required."), [string]$InputFile = $(throw "The InputFile parameter is required."), [string]$SqlInstallationFolder = "C:\Program Files (x86)\Microsoft SQL Server") # Load DAC assembly. $DacAssembly = "$SqlInstallationFolder\110\DAC\bin\Microsoft.SqlServer.Dac.dll" Write-Host "Loading Dac Assembly: $DacAssembly" Add-Type -Path $DacAssembly Write-Host "Dac Assembly loaded." # Initialize Dac service. $now = $(Get-Date).ToString("HH:mm:ss") $Services = new-object Microsoft.SqlServer.Dac.DacServices $ConnectionString if ($Services -eq $null) { exit } # Start the actual export. Write-Host "Starting restore to $DatabaseName at $now" $Watch = New-Object System.Diagnostics.StopWatch $Watch.Start() $Package = [Microsoft.SqlServer.Dac.BacPackage]::Load($InputFile) $Services.ImportBacpac($Package, $DatabaseName) $Package.Dispose() $Watch.Stop() Write-Host "Restore completed in" $Watch.Elapsed.ToString()
PowerShellCorpus/GithubGist/JonBons_1751dba197252039cb5a_raw_c004ebf438c2839cb29b4dd6beb5f9eb300a305a_gistfile1.ps1
JonBons_1751dba197252039cb5a_raw_c004ebf438c2839cb29b4dd6beb5f9eb300a305a_gistfile1.ps1
hg log -r "descendants(4b70a250592c) and head()" --template "{branch}\n" | Sort-Object -Unique > merge.txt
PowerShellCorpus/GithubGist/40a_7392178_raw_613b0b5ed711b9f32f6463dd172f12bf7ef98704_SetPullMode-RTM.ps1
40a_7392178_raw_613b0b5ed711b9f32f6463dd172f12bf7ef98704_SetPullMode-RTM.ps1
Configuration SetPullMode { Node Server01 { # Set the DSC engine (LCM) to Pull mode LocalConfigurationManager { ConfigurationID = "e528dee8-6f0b-4885-98a1-1ee4d8e86d82" ConfigurationMode = "ApplyOnly" RefreshMode = "Pull" DownloadManagerName = "WebDownloadManager" DownloadManagerCustomData = @{ ServerUrl = "http://<PullServer>:8080/PSDSCPullServer/PSDSCPullServer.svc" ; AllowUnsecureConnection = "true"; } } } } SetPullMode Set-DSCLocalConfigurationManager -ComputerName Server01 -Path .\SetPullMode -Verbose
PowerShellCorpus/GithubGist/belotn_5957878_raw_0ddaf988a031310e237e3f9035485896c89c0206_onescan_fillsqllite.ps1
belotn_5957878_raw_0ddaf988a031310e237e3f9035485896c89c0206_onescan_fillsqllite.ps1
get-eventlog -LogName "Key Management Service" -ComputerName "COMPNAME" -InstanceId 1073754114 | select Index,Message |% {if ($_.MEssage -match ".*(0x[0-9a-f]+),(\d+),([^,]+),([0-9a-f\-]+),([^,]+),(\d),(\d),(\d+),([0-9a-f\-]+).*") { $_ | Add-Member -type NoteProperty -name Client -Value $matches[3] -Passthru | Add-Member -type NoteProperty -name CMID -Value $matches[4] -PassThru | Add-Member -type NoteProperty -name ErrorLevel -Value $matches[1] -PassThru| Add-Member -type NoteProperty -name MinCount -Value $matches[2] -PassThru| Add-Member -type NoteProperty -name DateDemand -Value $matches[5] -PassThru | Add-Member -type NoteProperty -name isVM -Value $matches[6] -PassThru| Add-Member -type NoteProperty -name State -Value $matches[7] -PassThru | Add-Member -type NoteProperty -name TTLmin -Value $matches[8] -PassThru | Add-Member -type NoteProperty -name LicenseId -Value $matches[9] -PassThru} } | select @{N="Id";E={$_.Index}},Client,CMID,ErrorLevel,MinCount,DateDemand,isVM,State,TTLmin,LicenseId |% { new-item -path mydb:/Leases -ComputerId $($(if(ls mydb:/Computer -filter "CMID='$($_.CMID)'"){ls mydb:/Computer -filter "CMID='$($_.CMID)'"} else { new-item mydb:/Computer -ComputerName $_.Client -CMID $_.CMID -isVM $_.IsVM }) |select ComputerId).ComputerId -LicenseRow $($(if(ls mydb:/Licence -filter "LicenseID='$($_.LicenseID)'"){ls mydb:/Licence -filter "LicenseID='$($_.LicenseID)'"} else { new-item mydb:/Licence -LicenseId $_.LicenseId -MinCount $_.MinCout }) |select LicenseRow).LicenseRow -DateDemand $_.DateDemand.replace('/','-') -State $_.State -TTLMin $_.TTLMin -ServerName "COMPNAME" }
PowerShellCorpus/GithubGist/janikvonrotz_6883313_raw_a376f4d6707e0418e43161e46a3e550860aa4790_Get-UnlinkedGPO.ps1
janikvonrotz_6883313_raw_a376f4d6707e0418e43161e46a3e550860aa4790_Get-UnlinkedGPO.ps1
function Get-UnlinkedGPO { <# .SYNOPSIS Get all unlinkend GPOs .EXAMPLE PS C:\> Get-UnlinkedGPO #> $Metadata = @{ Title = "Get unlinked GPOs" Filename = "Get-UnlinkedGPO.ps1" Description = "" Tags = "powershell, function, activedirectory" Project = "" Author = "Janik von Rotz" AuthorContact = "www.janikvonrotz.ch" CreateDate = "2013-05-06" LastEditDate = "2013-05-08" Version = "1.0.1" License = @' This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. '@ } #--------------------------------------------------# # modules #--------------------------------------------------# Import-module grouppolicy #--------------------------------------------------# # helper and functions #--------------------------------------------------# function IsNotLinked($xmldata){ If ($xmldata.GPO.LinksTo -eq $null) { Return $true } Return $false } #--------------------------------------------------# # main #--------------------------------------------------# $Report = @() $GPOs = Get-GPO -All foreach($GPO in $GPOs) { Write-Progress -Activity "Change GPO Settings" -status ("Change GPO: "+$GPO.DisplayName) -percentComplete ([int]([array]::IndexOf($GPOs, $GPO)/$GPOs.Count*100)) $GPOReport = $GPO | Get-GPOReport -ReportType xml If(IsNotLinked([xml]$GPOReport)){$Report += $GPO} } If ($Report.Count -eq 0) { Wirte-Warning "No unlinked GPO's found" }else{ return $Report } }
PowerShellCorpus/GithubGist/zhujo01_059a82107a13e76c14cd_raw_86a05da24bf3f7bf27b6907015d77201358f2a26_aws-test.ps1
zhujo01_059a82107a13e76c14cd_raw_86a05da24bf3f7bf27b6907015d77201358f2a26_aws-test.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 # - VMWare vSphere & VCD # # Coppyright (c) 2014, CliQr Technologies, Inc. All rights reserved. ######################################################################## param( [Parameter(Mandatory=$true)][string]$AccessId, [Parameter(Mandatory=$true)][string]$SecretKey, [Parameter(Mandatory=$true)][string]$AdminPass, [Parameter(Mandatory=$true)][string]$ImageName ) Start-Transcript -Path 'c:\bootstrap-transcript.txt' -Force Set-StrictMode -Version Latest Set-ExecutionPolicy Unrestricted $log = 'c:\Bootstrap.txt' $client = new-object System.Net.WebClient # Disable EC2 agent service Set-Service -name Ec2Config -startupType Disabled Start-Sleep -s 10 Remove-Item *.exe # TODO: Call pre bundle script # # Bundle Add-Content $log -value "Creating bundle..." $client.DownloadFile('https://s3.amazonaws.com/osmosixdev-test/disk2vhd.exe', 'disk2vhd.exe') Start-Process -FilePath 'C:\Users\Administrator\disk2vhd.exe' -ArgumentList "c: z:\disk.vhd -accepteula" -Wait Add-Content $log -value "Done." # Convert VHD to VMDK &qemu-img convert -O vmdk z:\disk.vhd y:\disk.vmdk # Convert VMDK $client.DownloadFile('https://s3.amazonaws.com/osmosixdev-test/vm.ovf', 'y:\vm.ovf') &ovftool y:\vm.ovf x:\$ImageName.ovf # Bundle Add-Content $log -value "Uploading bundle..." $client.DownloadFile('http://mvnrepo.cliqr.com/install/gof3r.exe', 'gof3r.exe') $Env:AWS_ACCESS_KEY_ID = $AccessId $Env:AWS_SECRET_ACCESS_KEY = $SecretKey Start-Process -FilePath 'C:\Users\Administrator\gof3r.exe' -ArgumentList "put /p x:\$ImageName-disk1.vmdk /b osmosixdev-test /k $ImageName-disk1.vmdk /c 20"-Wait Start-Process -FilePath 'C:\Users\Administrator\gof3r.exe' -ArgumentList "put /p x:\$ImageName.ovf /b osmosixdev-test /k $ImageName.ovf /c 20" -Wait Add-Content $log -value "Done." #Start-Sleep -m 300000 Add-Content $log -value "Cleaning up..." $Env:AWS_ACCESS_KEY_ID = "*" $Env:AWS_SECRET_ACCESS_KEY = "*" # shutdown /s /f
PowerShellCorpus/GithubGist/ziqbalbh_d37cc8a36a18fa696a6b_raw_e56653ec2b88d68ed80126d9fc6ad4632be1cbe9_gac-install.ps1
ziqbalbh_d37cc8a36a18fa696a6b_raw_e56653ec2b88d68ed80126d9fc6ad4632be1cbe9_gac-install.ps1
param($assembly) if ($assembly -eq $null) { write-host -foregroundcolor red "-assembly parameter is required." return } try { [Reflection.Assembly]::LoadWithPartialName("System.EnterpriseServices") | Out-Null [System.EnterpriseServices.Internal.Publish] $publish = New-Object System.EnterpriseServices.Internal.Publish if (!(Test-Path $assembly -type Leaf) ) { throw "The assembly $assembly does not exist" } if ([System.Reflection.Assembly]::LoadFile($assembly).GetName().GetPublicKey().Length -eq 0 ) { throw "The assembly $assembly must be strongly signed" } $publish.GacInstall($assembly) iisreset } catch { Write-Host -ForegroundColor Red $_.Exception.ToString() } write-host -ForegroundColor Green "done."
PowerShellCorpus/GithubGist/ashes999_56f358624dd498d34e4a_raw_5a3d0ce65b914ed63f399187fb0073b84b2b3504_boxstarter-pc.ps1
ashes999_56f358624dd498d34e4a_raw_5a3d0ce65b914ed63f399187fb0073b84b2b3504_boxstarter-pc.ps1
Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -EnableShowProtectedOSFiles -EnableShowFileExtensions -EnableShowFullPathInTitleBar Enable-RemoteDesktop $packages = @( 'fiddler4', 'conemu', 'dropbox', 'virtualbox', 'VirtualBox.ExtensionPack', 'VBoxHeadlessTray', 'GoogleChrome' ) foreach ($package in $packages) { cinst $package }
PowerShellCorpus/GithubGist/peaeater_32d339acb7cd3eec1e3e_raw_5d056b83822a3a0c9582cd4412ebe6ee734c3e8b_extractomatic.ps1
peaeater_32d339acb7cd3eec1e3e_raw_5d056b83822a3a0c9582cd4412ebe6ee734c3e8b_extractomatic.ps1
<# Extracts data from the named textbase as files like {tn}-{0}.xml in output folder. Logs to Application event log - source must already have been added. #> param( [Parameter(Mandatory=$false,Position=0)] [string]$logsrc = "Andi Solr Update" ) $basePath = "c:\path\to\extract-exe" $textbasePath = "c:\path\to\textbases" $tn = "mytextbase" $log = "" # if empty, won't write to local text file Add-Type -AssemblyName System.Data function odbcConnectionString([string]$dir) { $builder = new-object -typename System.Data.Odbc.OdbcConnectionStringBuilder $builder.Driver = "Inmagic DB/Text Driver (*.tba)" $builder.Add("dbq", $dir) $builder.Add("server", "NotTheServer") $builder.Add("readonly", "1") return $builder.ToString() } function logError([string]$msg) { # write error msg to Application EventLog Write-EventLog -LogName Application -Source $logsrc -EventId 500 -EntryType Error -Message $msg -Category 0 Write-Host ("ERROR {0}" -f $msg) } function logInfo([string]$msg) { # write info msg to Application EventLog Write-EventLog -LogName Application -Source $logsrc -EventId 200 -EntryType Information -Message $msg -Category 0 Write-Host ("INFO {0}" -f $msg) } try { $dsn = odbcConnectionString($textbasePath) # prep if (!(test-path "$basePath\output")) { mkdir "$basePath\output" } # clean rm "$basePath\output\$tn*" # connect via odbc and write to file/s start-process -nonewwindow -wait -filepath "$basePath\extract.exe" -argumentlist "/from:`"$tn`"", "/query:`"Status LIKE 'Available'`"", "/log:`"$log`"", "/rowmax:1000", "/connection:`"$dsn`"", "/out:`"$basePath\output\$tn.txt`"", "/field:`"RecordID,Title,Subject,Author`"", "/formatType:`"nominal`"", "/format:`" <doc> <field name='src'><![CDATA[MyTextbase]]></field> <field name='id'><![CDATA[mytextbase{RecordID}]]></field> <field name='srcid'><![CDATA[{RecordID}]]></field> <field name='title'><![CDATA[{Title}]]></field> <field name='topic'><![CDATA[{Subject}]]></field> <field name='topic_free'><![CDATA[{Subject}]]></field> <field name='name'><![CDATA[{Author}]]></field> <field name='name_free'><![CDATA[{Author}]]></field> <field name='freetext'><![CDATA[<name label='Author'>{Type}</name>]]></field> <field name='freetext'><![CDATA[<topic label='Subject'>{Subject}</topic>]]></field> </doc>`"" # construct xml files $xmlheader = "$basePath\config\xmlheader.txt" $xmlfooter = "$basePath\config\xmlfooter.txt" $files = ls "$basePath\output\*.*" -include $tn*.txt $utf8nobom = new-object System.Text.UTF8Encoding($false) # check for txt (attempt to determine if extractomatic has worked) if ($files.Count -eq 0) { logError("Extractomatic {0} produced no files." -f $script:myinvocation.mycommand.name) exit 1 } else { logInfo("Extractomatic {0} produced {1} files." -f $script:myinvocation.mycommand.name, $files.Count) } foreach ($file in $files) { # write UTF8 output without BOM as Java xml parsers choke on it $content = get-content (get-childitem $xmlheader, $file, $xmlfooter) -encoding UTF8 [System.IO.File]::WriteAllLines("$basePath\output\$($file.BaseName).xml", $content, $utf8nobom) } # clean txt out rm "$basePath\output\$tn*.txt" exit 0 } catch [Exception] { logError($_.Exception) exit 1 }
PowerShellCorpus/GithubGist/vermiceli_108fec65759d19645ee3_raw_bb241ba8ba864a5cb8cd346265704c5900805b57_build_ui.ps1
vermiceli_108fec65759d19645ee3_raw_bb241ba8ba864a5cb8cd346265704c5900805b57_build_ui.ps1
# This is a powershell commandlet equivalent of build_ui.sh for installation on Windows # Generate python files based on the designer ui files. pyrcc4 should be on the path. # If you need to modify the python location or pyuic path, just change the 2 variables below $pythonPath = "C:\Python27\" $pyuicPath = "C:\Python27\Lib\site-packages\PyQt4\uic\pyuic.py" If (!(Test-Path "designer")) { Write-Host "Please run this from the project root" Exit } # Create the directory. If it already exists, nothing will happen Write-Host "Creating aqt\forms" New-Item "aqt\forms" -ItemType "directory" -Force > $null $init = "aqt\forms\__init__.py" $temp = "aqt\forms\scratch" If (Test-Path $init) { Write-Host "Creating $($init)" Remove-Item $init } If (Test-Path $temp) { Write-Host "Creating $($temp)" Remove-Item $temp } Write-Output "# This file auto-generated by build_ui.sh. Don't edit." | Out-File -Encoding "UTF8" $init Write-Output "__all__ = [" | Out-File -Encoding "UTF8" -Append $init Write-Host "Generating forms.." Get-ChildItem "designer\*.ui" | Select BaseName | Foreach-Object { $base = "$($_.BaseName)" Write-Host " $($base)" $py = Join-Path "aqt\forms\" ($base + ".py") Write-Output " '$($base)'," | Out-File -Append -Encoding "UTF8" $init Write-Output "import $($base)" | Out-File -Append -Encoding "UTF8" $temp if(!(Test-Path $py) -or ((Get-Item "designer\$($base).ui").LastWriteTime -gt (Get-Item $py).LastWriteTime)) { Write-Host " $($py)" $pythonCommand = Join-Path $pythonPath "python.exe" $command = "$($pythonCommand) $($pyuicPath) ""designer\$($base).ui"" -o $($py)" Invoke-Expression $command # munge the output to use gettext # perl -pi.bak -e 's/(QtGui\.QApplication\.)?_?translate\(".*?", /_(/; s/, None.*/))/' $py # rm $py.bak } } Write-Output "]" | Out-File -Encoding "UTF8" -Append $init Cat $temp | Out-File -Encoding "UTF8" -Append $init Remove-Item $temp Write-Host "Building resources..." pyrcc4 designer\icons.qrc -o aqt\forms\icons_rc.py Write-Host "Complete"
PowerShellCorpus/GithubGist/jstangroome_1172293_raw_209a411b8633484dbb6abd6e2ff4011bd20438b3_q1.ps1
jstangroome_1172293_raw_209a411b8633484dbb6abd6e2ff4011bd20438b3_q1.ps1
$Result = Get-ChildItem -Path $Env:TEMP
PowerShellCorpus/GithubGist/dfinke_7678410_raw_844816319537f63cbd1f0314315d560712b51ee8_CountryLoopup.ps1
dfinke_7678410_raw_844816319537f63cbd1f0314315d560712b51ee8_CountryLoopup.ps1
$CountryLookup = [ordered]@{ "AD"="ANDORRA" "AE"="UNITED ARAB EMIRATES" "AF"="AFGHANISTAN" "AG"="ANTIGUA AND BARBUDA" "AI"="ANGUILLA" "AL"="ALBANIA" "AM"="ARMENIA" "AO"="ANGOLA" "AQ"="ANTARCTICA" "AR"="ARGENTINA" "AS"="AMERICAN SAMOA" "AT"="AUSTRIA" "AU"="AUSTRALIA" "AW"="ARUBA" "AX"="ÅLAND ISLANDS" "AZ"="AZERBAIJAN" "BA"="BOSNIA AND HERZEGOVINA" "BB"="BARBADOS" "BD"="BANGLADESH" "BE"="BELGIUM" "BF"="BURKINA FASO" "BG"="BULGARIA" "BH"="BAHRAIN" "BI"="BURUNDI" "BJ"="BENIN" "BL"="SAINT BARTHÉLEMY" "BM"="BERMUDA" "BN"="BRUNEI DARUSSALAM" "BO"="BOLIVIA, PLURINATIONAL STATE OF" "BQ"="BONAIRE, SINT EUSTATIUS AND SABA" "BR"="BRAZIL" "BS"="BAHAMAS" "BT"="BHUTAN" "BV"="BOUVET ISLAND" "BW"="BOTSWANA" "BY"="BELARUS" "BZ"="BELIZE" "CA"="CANADA" "CC"="COCOS (KEELING) ISLANDS" "CD"="CONGO, THE DEMOCRATIC REPUBLIC OF THE" "CF"="CENTRAL AFRICAN REPUBLIC" "CG"="CONGO" "CH"="SWITZERLAND" "CI"="CÔTE D'IVOIRE" "CK"="COOK ISLANDS" "CL"="CHILE" "CM"="CAMEROON" "CN"="CHINA" "CO"="COLOMBIA" "CR"="COSTA RICA" "CU"="CUBA" "CV"="CAPE VERDE" "CW"="CURAÇAO" "CX"="CHRISTMAS ISLAND" "CY"="CYPRUS" "CZ"="CZECH REPUBLIC" "DE"="GERMANY" "DJ"="DJIBOUTI" "DK"="DENMARK" "DM"="DOMINICA" "DO"="DOMINICAN REPUBLIC" "DZ"="ALGERIA" "EC"="ECUADOR" "EE"="ESTONIA" "EG"="EGYPT" "EH"="WESTERN SAHARA" "ER"="ERITREA" "ES"="SPAIN" "ET"="ETHIOPIA" "FI"="FINLAND" "FJ"="FIJI" "FK"="FALKLAND ISLANDS (MALVINAS)" "FM"="MICRONESIA, FEDERATED STATES OF" "FO"="FAROE ISLANDS" "FR"="FRANCE" "GA"="GABON" "GB"="UNITED KINGDOM" "GD"="GRENADA" "GE"="GEORGIA" "GF"="FRENCH GUIANA" "GG"="GUERNSEY" "GH"="GHANA" "GI"="GIBRALTAR" "GL"="GREENLAND" "GM"="GAMBIA" "GN"="GUINEA" "GP"="GUADELOUPE" "GQ"="EQUATORIAL GUINEA" "GR"="GREECE" "GS"="SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS" "GT"="GUATEMALA" "GU"="GUAM" "GW"="GUINEA-BISSAU" "GY"="GUYANA" "HK"="HONG KONG" "HM"="HEARD ISLAND AND MCDONALD ISLANDS" "HN"="HONDURAS" "HR"="CROATIA" "HT"="HAITI" "HU"="HUNGARY" "ID"="INDONESIA" "IE"="IRELAND" "IL"="ISRAEL" "IM"="ISLE OF MAN" "IN"="INDIA" "IO"="BRITISH INDIAN OCEAN TERRITORY" "IQ"="IRAQ" "IR"="IRAN, ISLAMIC REPUBLIC OF" "IS"="ICELAND" "IT"="ITALY" "JE"="JERSEY" "JM"="JAMAICA" "JO"="JORDAN" "JP"="JAPAN" "KE"="KENYA" "KG"="KYRGYZSTAN" "KH"="CAMBODIA" "KI"="KIRIBATI" "KM"="COMOROS" "KN"="SAINT KITTS AND NEVIS" "KP"="KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF" "KR"="KOREA, REPUBLIC OF" "KW"="KUWAIT" "KY"="CAYMAN ISLANDS" "KZ"="KAZAKHSTAN" "LA"="LAO PEOPLE'S DEMOCRATIC REPUBLIC" "LB"="LEBANON" "LC"="SAINT LUCIA" "LI"="LIECHTENSTEIN" "LK"="SRI LANKA" "LR"="LIBERIA" "LS"="LESOTHO" "LT"="LITHUANIA" "LU"="LUXEMBOURG" "LV"="LATVIA" "LY"="LIBYA" "MA"="MOROCCO" "MC"="MONACO" "MD"="MOLDOVA, REPUBLIC OF" "ME"="MONTENEGRO" "MF"="SAINT MARTIN (FRENCH PART)" "MG"="MADAGASCAR" "MH"="MARSHALL ISLANDS" "MK"="MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF" "ML"="MALI" "MM"="MYANMAR" "MN"="MONGOLIA" "MO"="MACAO" "MP"="NORTHERN MARIANA ISLANDS" "MQ"="MARTINIQUE" "MR"="MAURITANIA" "MS"="MONTSERRAT" "MT"="MALTA" "MU"="MAURITIUS" "MV"="MALDIVES" "MW"="MALAWI" "MX"="MEXICO" "MY"="MALAYSIA" "MZ"="MOZAMBIQUE" "NA"="NAMIBIA" "NC"="NEW CALEDONIA" "NE"="NIGER" "NF"="NORFOLK ISLAND" "NG"="NIGERIA" "NI"="NICARAGUA" "NL"="NETHERLANDS" "NO"="NORWAY" "NP"="NEPAL" "NR"="NAURU" "NU"="NIUE" "NZ"="NEW ZEALAND" "OM"="OMAN" "PA"="PANAMA" "PE"="PERU" "PF"="FRENCH POLYNESIA" "PG"="PAPUA NEW GUINEA" "PH"="PHILIPPINES" "PK"="PAKISTAN" "PL"="POLAND" "PM"="SAINT PIERRE AND MIQUELON" "PN"="PITCAIRN" "PR"="PUERTO RICO" "PS"="PALESTINE, STATE OF" "PT"="PORTUGAL" "PW"="PALAU" "PY"="PARAGUAY" "QA"="QATAR" "RE"="RÉUNION" "RO"="ROMANIA" "RS"="SERBIA" "RU"="RUSSIAN FEDERATION" "RW"="RWANDA" "SA"="SAUDI ARABIA" "SB"="SOLOMON ISLANDS" "SC"="SEYCHELLES" "SD"="SUDAN" "SE"="SWEDEN" "SG"="SINGAPORE" "SH"="SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA" "SI"="SLOVENIA" "SJ"="SVALBARD AND JAN MAYEN" "SK"="SLOVAKIA" "SL"="SIERRA LEONE" "SM"="SAN MARINO" "SN"="SENEGAL" "SO"="SOMALIA" "SR"="SURINAME" "SS"="SOUTH SUDAN" "ST"="SAO TOME AND PRINCIPE" "SV"="EL SALVADOR" "SX"="SINT MAARTEN (DUTCH PART)" "SY"="SYRIAN ARAB REPUBLIC" "SZ"="SWAZILAND" "TC"="TURKS AND CAICOS ISLANDS" "TD"="CHAD" "TF"="FRENCH SOUTHERN TERRITORIES" "TG"="TOGO" "TH"="THAILAND" "TJ"="TAJIKISTAN" "TK"="TOKELAU" "TL"="TIMOR-LESTE" "TM"="TURKMENISTAN" "TN"="TUNISIA" "TO"="TONGA" "TR"="TURKEY" "TT"="TRINIDAD AND TOBAGO" "TV"="TUVALU" "TW"="TAIWAN, PROVINCE OF CHINA" "TZ"="TANZANIA, UNITED REPUBLIC OF" "UA"="UKRAINE" "UG"="UGANDA" "UM"="UNITED STATES MINOR OUTLYING ISLANDS" "US"="UNITED STATES" "UY"="URUGUAY" "UZ"="UZBEKISTAN" "VA"="HOLY SEE (VATICAN CITY STATE)" "VC"="SAINT VINCENT AND THE GRENADINES" "VE"="VENEZUELA, BOLIVARIAN REPUBLIC OF" "VG"="VIRGIN ISLANDS, BRITISH" "VI"="VIRGIN ISLANDS, U.S." "VN"="VIET NAM" "VU"="VANUATU" "WF"="WALLIS AND FUTUNA" "WS"="SAMOA" "YE"="YEMEN" "YT"="MAYOTTE" "ZA"="SOUTH AFRICA" "ZM"="ZAMBIA" "ZW"="ZIMBABWE" }
PowerShellCorpus/GithubGist/jonforums_564589_raw_9ab5dac3d70223e94916a40fdf8ca4804ceb74cb_devkitvars.ps1
jonforums_564589_raw_9ab5dac3d70223e94916a40fdf8ca4804ceb74cb_devkitvars.ps1
# convenience script residing in the DevKit root dir used for # manually configuring a PowerShell environment to use the # DevKit for compiling native Ruby extensions echo "Adding DevKit to PATH..." $devkit = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Definition) $env:path = "$devkit\bin;$devkit\mingw\bin;$env:path"
PowerShellCorpus/GithubGist/jlao_3507824_raw_fb889d9ba0b353e298eddec2653edfa724f34f4a_profile.ps1
jlao_3507824_raw_fb889d9ba0b353e298eddec2653edfa724f34f4a_profile.ps1
function prompt { $loc = Get-Location $parts = $loc.Path.split("\") $shortparts = @($parts[0]) if ($parts.length -gt 2) { $shortparts += $parts[1..($parts.length - 2)] | % { $_[0] } } $shortparts += $parts[-1] $locstr = [string]::join("\", $shortparts) $locstr + "> " }
PowerShellCorpus/GithubGist/belotn_5984505_raw_217f0c86a72058e43e82e81ac7d623d4b106d4de_onescan_csv_incremental.ps1
belotn_5984505_raw_217f0c86a72058e43e82e81ac7d623d4b106d4de_onescan_csv_incremental.ps1
get-eventlog -LogName "Key Management Service" -ComputerName "COMPUTER" -InstanceId 1073754114 -After $([datetime]::ParseExact( $(import-csv .\Leases.csv |? { $_.ServerName -eq "COMPUTER" }| select TimeGenerated | sort TimeGenerated -desc | select -First 1).TimeGenerated ,'MM/dd/yyyy HH:mm:ss', $null) ) | select Index,Message,TimeGenerated |% {if ($_.MEssage -match ".*(0x[0-9a-f]+),(\d+),([^,]+),([0-9a-f\-]+),([^,]+),(\d),(\d),(\d+),([0-9a-f\-]+).*") { $_ | Add-Member -type NoteProperty -name Client -Value $matches[3] -Passthru | Add-Member -type NoteProperty -name CMID -Value $matches[4] -PassThru | Add-Member -type NoteProperty -name ErrorLevel -Value $matches[1] -PassThru| Add-Member -type NoteProperty -name MinCount -Value $matches[2] -PassThru| Add-Member -type NoteProperty -name DateDemand -Value $matches[5] -PassThru | Add-Member -type NoteProperty -name isVM -Value $matches[6] -PassThru| Add-Member -type NoteProperty -name State -Value $matches[7] -PassThru | Add-Member -type NoteProperty -name TTLmin -Value $matches[8] -PassThru | Add-Member -type NoteProperty -name LicenseId -Value $matches[9] -PassThru} } | select @{N="Id";E={$_.Index}},Client,CMID,ErrorLevel,MinCount,TimeGenerated,DateDemand,isVM,State,TTLmin,LicenseId |% {"$("$(@{$true=$(Import-Csv ./Leases.csv | measure-object LeaseID -Max).Maximum;$false=0}[$(Import-Csv Leases.csv | measure-object LeaseID -Max).Maximum -ne $null ]+ 1)"),$($CMID = $_.CMID;$(if( @(Import-Csv ./Computer.csv |? { $_.CMID -eq $CMID}).Count -gt 0 ){"$($(Import-Csv ./Computer.csv |? { $_.CMID -eq $CMID}).ComputerId)"}else{"$(@{$true=$(Import-Csv ./Computer.csv | measure-object ComputerId -Max).Maximum;$false=0}[$(Import-Csv Computer.csv | measure-object ComputerId -Max).Maximum -ne $null ]+ 1),$($_.Client),$($_.CMID),$($_.IsVM)">> "./Computer.csv" ; "$($(Import-Csv Computer.csv | measure-object ComputerId -Max).Maximum)"})),$($LID = $_.LicenseID;$(if( @(Import-Csv ./Licence.csv |? { $_.LicenseId -eq $LID}).Count -gt 0 ){"$($(Import-Csv ./Licence.csv |? { $_.LicenseID -eq $LID}).LicenseRow)"}else{"$(@{$true=$(Import-Csv ./Licence.csv | measure-object LicenseRow -Max).Maximum;$false=0}[$(Import-Csv Licence.csv | measure-object LicenseRow -Max).Maximum -ne $null ]+ 1),$($_.LicenseId),$($_.MinCount)" >> Licence.csv; "$($(Import-Csv Licence.csv | measure-object LicenseRow -Max).Maximum)" })),$($_.TimeGenerated),$($_.DateDemand),$($_.TTLMin),$($_.State),COMPUTER" >> Leases.csv}
PowerShellCorpus/GithubGist/stuncloud_d7dcf3c5174250e542c7_raw_2981cbfde9170cf48099b29137623913b0e5ea4c_Get-FirstLogonTime.ps1
stuncloud_d7dcf3c5174250e542c7_raw_2981cbfde9170cf48099b29137623913b0e5ea4c_Get-FirstLogonTime.ps1
function Get-FirstLogonTime { [CmdletBinding()] param( [parameter(Mandatory=$false,Position=0,ValueFromPipelineByPropertyName)] [DateTime[]] $Date = $(Get-Date) ) begin { if (-not $IsAdmin) { Write-Error '管理者特権で実行してください' break } $InstanceId = 4624 # ログオンのInstanceId $result = @() } process { foreach ($d in $Date) { # 検索範囲を指定 $After = $d.Date $Before = $After.AddDays(1) $LogonEvent = Get-EventLog -LogName Security -InstanceId $InstanceId -After $After -Before $Before | ? { $_.Message -match ('アカウント名:\s+' + $env:USERNAME + '\s+') } if ($LogonEvent.Length -gt 0) { Write-Verbose "$($After.ToShortDateString())の$($env:USERNAME)によるログオンレコードが$($LogonEvent.Length)件見つかりました" $result += $LogonEvent[-1].TimeWritten } else { Write-Verbose "$($After.ToShortDateString())の$($env:USERNAME)によるログオンレコードが見つかりませんでした" } } } end { if ($result.Length -gt 0) { return $result } Write-Error 'ログオンレコードが見つかりませんでした' return $null } }
PowerShellCorpus/GithubGist/seraphy_8293523_raw_b93f5f68910cae59cc0456027e6bb9504e78ef1b_MeasureLineCounter.ps1
seraphy_8293523_raw_b93f5f68910cae59cc0456027e6bb9504e78ef1b_MeasureLineCounter.ps1
# 第一引数として、対象となるファイルまたは親ディレクトリを指定する. # 省略時はカレントディレクトリ以下のすべてのファイルを対象とする. param($searchPath = $(pwd)) # 指定したフォルダ以下の全てのファイルを取得する. # (ファイルが指定された場合はファイル自身を返す) function GetFilesRecurse([string] $path) { Get-ChildItem $path -Recurse | Where-Object -FilterScript { # ディレクトリ以外のみ (ディレクトリのビットマスク値は16) ($_.Attributes -band 16) -eq 0 } } # エントリの型の定義 Add-Type @" public struct MeasureLineEntry { public string FullName; public string Directory; public string Name; public string Extension; public long Lines; public long Characters; } "@ function MakeEntry { process { $measure = (Get-Content $_.FullName | Measure-Object -Line -Character) return New-Object MeasureLineEntry -Property @{ FullName = $_.FullName; Directory = $_.Directory; Name = $_.Name; Extension = $_.Extension; Lines = $measure.Lines; Characters = $measure.Characters; } } } # 指定ディレクトリ下の以下の拡張子をもつ、すべてのファイルのLINE数をカウントする # 順序は名前順、拡張子順とする。 $EXTS = @(".frm", ".bas", ".vbs", ".js", ".java", ".pl", ".py", ".vb", ".c", ".cpp", ".cxx", ".h") GetFilesRecurse $searchPath | Where-Object -FilterScript { $EXTS -contains $_.Extension } | Sort-Object -Property Name | MakeEntry | Out-GridView -Title "Measure Line Count" # Format-Table -Property Directory, Name, Lines, Characters
PowerShellCorpus/GithubGist/mckn_4136080_raw_9d7db252e302d45a4f69b07ed7a139933043bad6_semver.ps1
mckn_4136080_raw_9d7db252e302d45a4f69b07ed7a139933043bad6_semver.ps1
function Bump-Version { param([string]$part = $(throw "Part is a required parameter.")) $version = Get-AssemblyInfoVersion -Directory ..\Source -GlobalAssemblyInfo $true $bumpedVersion = Clone-Object -Object $version switch -wildcard ($part) { "ma*" { $bumpedVersion.Major = Bump-NumericVersion -Current $version.Major } "mi*" { $bumpedVersion.Minor = Bump-NumericVersion -Current $version.Minor } "p*" { $bumpedVersion.Patch = Bump-NumericVersion -Current $version.Patch } "b*" { $bumpedVersion.Build = Bump-SpecialVersion -Current $version.Build } default { throw "Parameter Part should be: minor, major, patch or build!"} } if($bumpedVersion.Major -eq $version.Major -and $bumpedVersion.Minor -eq $version.Minor -and $bumpedVersion.Patch -eq $version.Patch -and $bumpedVersion.Build -eq $version.build) { throw "Version didn't change due to some error..." } Update-AssemblyInfoVersion -Directory ..\Source -GlobalAssemblyInfo $true -BumpedVersion $bumpedVersion } function Bump-NumericVersion { param([int] $current = $(throw "Current is a required parameter.")) return $current + 1; } function Bump-SpecialVersion { param([string]$current = $(throw "Current is a required paramter.")) throw "Not implemented...." } function Clone-Object { param([PSObject] $object = $(throw "Object is a required parameter.")) $clone = New-Object PSObject $object.psobject.properties | % { $clone | Add-Member -MemberType $_.MemberType -Name $_.Name -Value $_.Value } return $clone } function Get-AssemblyInfoVersion { param([string] $directory = $(throw "Directory is a required parameter."), [bool] $globalAssemblyInfo = $false) $fileName = "AssemblyInfo.cs" $versionPattern = 'AssemblyVersion\("([0-9])+\.([0-9])+\.([0-9])+\-?(.*)?"\)' if($globalAssemblyInfo) { $fileName = "GlobalAssemblyInfo.cs" } $assemblyInfo = Get-ChildItem $directory -Recurse | Where-Object {$_.Name -eq $fileName} | Select-Object -First 1 if(!$assemblyInfo) { throw "Could not find assembly info file" } $matchedLine = Get-Content $assemblyInfo.FullName | Where-Object { $_ -match $versionPattern } | Select-Object -First 1 if(!$matchedLine) { throw "Could not find line containing assembly version in assembly info file" } $major, $minor, $patch, $build = ([regex]$versionPattern).matches($matchedLine) | foreach {$_.Groups } | Select-Object -Skip 1 return New-Object PSObject -Property @{ Minor = $minor.Value Major = $major.Value Patch = $patch.Value Build = $build.Value } } function Update-AssemblyInfoVersion { param([PSObject] $bumpedVersion = $(throw "BumpedVersion is a required parameter."), [string] $directory = $(throw "Directory is a required parameter."), [bool] $globalAssemblyInfo = $false) $assemblyVersionPattern = 'AssemblyVersion\("([0-9])+\.([0-9])+\.([0-9])+\-?(.*)?"\)' $assemblyFileVersionPattern = 'AssemblyFileVersion\("([0-9])+\.([0-9])+\.([0-9])+\-?(.*)?"\)' $version = ("{0}.{1}.{2}" -f $bumpedVersion.Major, $bumpedVersion.Minor, $bumpedVersion.Patch) if($bumpedVersion.Build) { $version = "{0}-{1}" -f $version, $bumpedVersion.Build } $assemblyVersion = 'AssemblyVersion("' + $version + '")' $fileVersion = 'AssemblyFileVersion("' + $version + '")' $fileName = "AssemblyInfo.cs" if($globalAssemblyInfo) { $fileName = "GlobalAssemblyInfo.cs" } Get-ChildItem $directory -Recurse -Filter $fileName | ForEach-Object { $currentFile = $_.FullName $tempFile = ("{0}.tmp" -f $_.FullName) Get-Content $currentFile | ForEach-Object { % { $_ -Replace $assemblyVersionPattern, $assemblyVersion } | % { $_ -Replace $assemblyFileVersionPattern, $fileVersion } } | Set-Content $tempFile Remove-Item $currentFile Rename-Item $tempFile $currentFile Write-Host "Updated version to: $version in $currentFile" } } Bump-Version -part "patch" -useGlobalAssemblyInfo $true
PowerShellCorpus/GithubGist/headchant_6240555_raw_5269823d01de1f81dce3d124385d1db03aa79ef5_roguelike.ps1
headchant_6240555_raw_5269823d01de1f81dce3d124385d1db03aa79ef5_roguelike.ps1
Function writetext { Param ([int]$x, [int]$y, [string]$text) [Console]::SetCursorPosition($x, $y) [Console]::Write($text) } # set background color of the shell to black (Get-Host).UI.RawUI.BackgroundColor = "black" clear # player objects factory function function newPlayer() { $player = New-Object PSObject $player | Add-Member -type Noteproperty -Name x -Value 3 $player | Add-Member -type Noteproperty -Name y -Value 3 $player | Add-Member -type Noteproperty -Name char -Value "@" return $player } #create the player object $player = newPlayer #create the map $width = 20 $height = 20 $map = new-Object 'object[,]' $width, $height for($i=1; $i -le $width-1; $i++) { for($j=1; $j -le $height-1; $j++) { $map[$i,$j] = "." } } # main loop do { [Console]::Clear() for($i=1; $i -le $width-1; $i++) { for($j=1; $j -le $height-1; $j++) { writetext $i $j $map[$i,$j] } } writetext $player.x $player.y $player.char $input = [Console]::ReadKey(("NoEcho")) if ($input.key -eq "RightArrow"){ $player.x = $player.x + 1 } if ($input.key -eq "LeftArrow"){ $player.x = $player.x - 1 } if ($input.key -eq "DownArrow"){ $player.y = $player.y + 1 } if ($input.key -eq "UpArrow"){ $player.y = $player.y - 1 } } while ($input.keychar -ne "q")
PowerShellCorpus/GithubGist/pnowosie_6160177_raw_acd2d773990397edce52a365a8073e9b7dc0888b_SimpleAutoVersion.ps1
pnowosie_6160177_raw_acd2d773990397edce52a365a8073e9b7dc0888b_SimpleAutoVersion.ps1
## TODO: Add header, licence ... # Missing parts: # * Error handlig # * User friendly configuration and customization # * Usage info # ===== Configuration ==== # $SVNCMD = "C:\Program Files\TortoiseSVN\bin\svn.exe" $BUILDTOOL = "C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" # What is file name with AssemblyVersion attribute of your project $asminfoFile = "SharedAssemblyInfo.cs" $ToolInfo = "[SimpleVersioning v0.1.0]" $rx = "Checked out revision (\d+)\." $asmrx = '\[assembly: AssemblyVersion\("(\d+\.\d+\.)(-?\d+)\.(\d+)"' $verrx = '(\s*\[assembly: AssemblyVersion\("\d+\.\d+\.)-?\d+\.\d+("\)\]\s*)' $repofile = '.\repo.txt' foreach ($repo in cat $repofile) { $out = (&$SVNCMD co $repo | Out-String) echo $repo, $out if ($out -match $rx) { $revision = $Matches[1] echo "Most update revision: $revision" # Get shared assembly info file and prepare version info $repoDir = [System.IO.Path]::GetFileName($repo) # There is an error PS v2.0 with: Split-Path -Leaf $repo echo "Searching SharedAsmInfo in $repoDir repository directory" $sai = ls -Path $repoDir -Recurse -Filter "$asminfoFile" if ($sai -ne $nul) { echo "Found at $($sai.FullName)" $asm = (cat $sai.FullName | Out-String) if ($asm -match $asmrx) { $mm = $Matches[1] $build = [int]$Matches[2] $rev = $Matches[3] echo "Matched AssemblyVersion attribute value $mm$build.$rev" echo "[Major.Minor] won't be modified`t`t`t : $mm" echo "[Build] will be increased by 1`t`t`t : $build -> $($build+1)" echo "[Revision] will be current repo revision`t : $rev -> $revision" # Increase build number $build = $build + 1 # Replace revision with last checked-out revision number $rev = $revision # Prepare new version string $asver = $mm + $build + "." + $rev # Replace asm version with prepared one $dummy= $asm -match $verrx $currAsmVersion = $Matches[0] -replace "`t|`n|`r","" echo "$currAsmVersion -> AssemblyVersion(""$asver"")" $asm = $asm -replace $verrx, "`${1}$build.$rev`${2}" echo $asm | Set-Content -Path $sai.FullName -Encoding UTF8 # Build solution Push-Location $sai.DirectoryName &$BUILDTOOL &$SVNCMD ci $sai.Name -m "$(Get-Date -Format 'yyyyMMddHHmmss') $ToolInfo Preparing version *$asver*. Code included up to revision $rev. Build machine *$(hostname)*." Pop-Location } } } } ## Sample output # PS C:\Projects\Learn\AutoVersioning\build> .\build.ps1 # file:///C:/Projects/Learn/AutoVersioning/BareRepo # A BareRepo\tags # A BareRepo\trunk # A BareRepo\trunk\ProjectName # A BareRepo\trunk\ProjectName\SharedAssemblyInfo.cs # A BareRepo\branches # Checked out revision 3. # # Most update revision: 3 # Searching SharedAsmInfo in BareRepo repository directory # Found at C:\Projects\Learn\AutoVersioning\build\BareRepo\trunk\ProjectName\SharedAssemblyInfo.cs # Matched AssemblyVersion attribute value 1.0.-1.0 # [Major.Minor] won't be modified : 1.0. # [Build] will be increased by 1 : -1 -> 0 # [Revision] will be current repo revision : 0 -> 3 # # [assembly: AssemblyVersion("1.0.-1.0")] -> AssemblyVersion("1.0.0.3") # -- BUILD output is skiped -- # Sending SharedAssemblyInfo.cs # Transmitting file data . # Committed revision 4. # # Commit message from auto-versioning tool: # 20130807142723 [SimpleVersioning v0.1.0] Preparing version *1.0.0.3*. Code included up to revision 3. Build machine *NOT-EXPOSED*.
PowerShellCorpus/GithubGist/n3wjack_4b370eeb47dcbd90e010_raw_871422222766009294faf220c444d91d6c89b169_recycle.ps1
n3wjack_4b370eeb47dcbd90e010_raw_871422222766009294faf220c444d91d6c89b169_recycle.ps1
# Recycle application pools based on a given substring using the appcmd.exe tool. param ( $AppPool ) $appcmd = "C:\Windows\system32\inetsrv\appcmd.exe" $pools = & $appcmd list apppool | % { ($_ -split "`"")[1] } foreach ($pool in ($pools -like "*$AppPool*")) { & $appcmd recycle apppool $pool }
PowerShellCorpus/GithubGist/jrotello_3095372_raw_d5b027e6821c99efeb267a1b596c7b715e9c2c6e_GodMode.ps1
jrotello_3095372_raw_d5b027e6821c99efeb267a1b596c7b715e9c2c6e_GodMode.ps1
$godMode = "$env:userprofile\Desktop\GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}" if (!(Test-Path -Path $godMode)) { mkdir $godMode }
PowerShellCorpus/GithubGist/smasterson_9141359_raw_374d9ff698d283378bb0f16e2f97a1ba748ffff7_DeployVM.ps1
smasterson_9141359_raw_374d9ff698d283378bb0f16e2f97a1ba748ffff7_DeployVM.ps1
<# .SYNOPSIS Deploy Multiple VMs to vCenter .DESCRIPTION VMs are deployed asynchronously based on a pre-configured csv file (DeployVM.csv) .PARAMETER csvfile Path to DeployVM.csv file with new VM info .PARAMETER vCenter vCenter Server FQDN or IP .PARAMETER auto Will allow script to run with no review or confirmation .PARAMETER createcsv Generates a blank csv file - DeployVM.csv .EXAMPLE .\DeployVM.ps1 Runs DeployVM .EXAMPLE .\DeployVM.ps1 -vcenter my.vcenter.address Runs DeployVM specifying vCenter address .EXAMPLE .\DeployVM.ps1 -csvfile "E:\Scripts\Deploy\DeployVM.csv" -vcenter my.vcenter.address -auto Runs DeployVM specifying path to csv file, vCenter address and no confirmation .EXAMPLE .\DeployVM.ps1 -createcsv Creates a new/blank DeployVM.csv file in same directory as script .NOTES Author: Shawn Masterson Created: May 2014 Version: 1.2 REQUIREMENTS PowerShell v3 or greater vCenter (tested on 5.1/5.5) PowerCLI 5.5 R2 or later CSV File - VM info with the following headers Name, Boot, OSType, Template, CustSpec, Folder, ResourcePool, CPU, RAM, Disk2, Disk3, Disk4, Datastore, DiskStorageFormat, NetType, Network, DHCP, IPAddress, SubnetMask, Gateway, pDNS, sDNS, Notes Must be named DeployVM.csv Can be created with -createcsv switch CSV Field Definitions Name - Name of new VM Boot - Determines whether or not to boot the VM - Must be 'true' or 'false' OSType - Must be 'Windows' or 'Linux' Template - Name of existing template to clone CustSpec - Name of existing OS Customiation Spec to use Folder - Folder in which to place VM in vCenter (optional) ResourcePool - VM placement - can be a reasource pool, host or a cluster CPU - Number of vCPU RAM - Amount of RAM Disk2 - Size of additional disk to add (GB)(optional) Disk3 - Size of additional disk to add (GB)(optional) Disk4 - Size of additional disk to add (GB)(optional) Datastore - Datastore placement - Can be a datastore or datastore cluster DiskStorageFormat - Disk storage format - Must be 'Thin', 'Thick' or 'EagerZeroedThick' NetType - vSwitch type - Must be 'vSS' or 'vDS' Network - Network/Port Group to connect NIC DHCP - Use DHCP - Must be 'true' or 'false' IPAddress - IP Address for NIC SubnetMask - Subnet Mask for NIC Gateway - Gateway for NIC pDNS - Primary DNS (Windows Only) sDNS - Secondary NIC (Windows Only) Notes - Description applied to the vCenter Notes field on VM CREDITS Handling New-VM Async - LucD - @LucD22 http://www.lucd.info/2010/02/21/about-async-tasks-the-get-task-cmdlet-and-a-hash-table/ USE AT YOUR OWN RISK! .LINK http://blog.smasterson.com/2014/05/21/deploying-multiple-vms-via-powercli-updated-v1-2/ #> #requires –Version 3 #-------------------------------------------------------------------- # Parameters param ( [parameter(Mandatory=$false)] [string]$csvfile, [parameter(Mandatory=$false)] [string]$vcenter, [parameter(Mandatory=$false)] [switch]$auto, [parameter(Mandatory=$false)] [switch]$createcsv ) #-------------------------------------------------------------------- # User Defined Variables #-------------------------------------------------------------------- # Static Variables $scriptName = "DeployVM" $scriptVer = "1.2" $scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent $starttime = Get-Date -uformat "%m-%d-%Y %I:%M:%S" $logDir = $scriptDir + "\Logs\" $logfile = $logDir + $scriptName + "_" + (Get-Date -uformat %m-%d-%Y_%I-%M-%S) + "_" + $env:username + ".txt" $deployedDir = $scriptDir + "\Deployed\" $deployedFile = $deployedDir + "DeployVM_" + (Get-Date -uformat %m-%d-%Y_%I-%M-%S) + "_" + $env:username + ".csv" $exportpath = $scriptDir + "\DeployVM.csv" $headers = "" | Select-Object Name, Boot, OSType, Template, CustSpec, Folder, ResourcePool, CPU, RAM, Disk2, Disk3, Disk4, Datastore, DiskStorageFormat, NetType, Network, DHCP, IPAddress, SubnetMask, Gateway, pDNS, sDNS, Notes $taskTab = @{} #-------------------------------------------------------------------- # Load Snap-ins # Add VMware snap-in if required If ((Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null) {add-pssnapin VMware.VimAutomation.Core} #-------------------------------------------------------------------- # Functions Function Out-Log { Param( [Parameter(Mandatory=$true)][string]$LineValue, [Parameter(Mandatory=$false)][string]$fcolor = "White" ) Add-Content -Path $logfile -Value $LineValue Write-Host $LineValue -ForegroundColor $fcolor } Function Read-OpenFileDialog([string]$WindowTitle, [string]$InitialDirectory, [string]$Filter = "All files (*.*)|*.*", [switch]$AllowMultiSelect) { Add-Type -AssemblyName System.Windows.Forms $openFileDialog = New-Object System.Windows.Forms.OpenFileDialog $openFileDialog.Title = $WindowTitle if (![string]::IsNullOrWhiteSpace($InitialDirectory)) { $openFileDialog.InitialDirectory = $InitialDirectory } $openFileDialog.Filter = $Filter if ($AllowMultiSelect) { $openFileDialog.MultiSelect = $true } $openFileDialog.ShowHelp = $true # Without this line the ShowDialog() function may hang depending on system configuration and running from console vs. ISE. $openFileDialog.ShowDialog() > $null if ($AllowMultiSelect) { return $openFileDialog.Filenames } else { return $openFileDialog.Filename } } #-------------------------------------------------------------------- # Main Procedures # Start Logging Clear-Host If (!(Test-Path $logDir)) {New-Item -ItemType directory -Path $logDir | Out-Null} Out-Log "**************************************************************************************" Out-Log "$scriptName`tVer:$scriptVer`t`t`t`tStart Time:`t$starttime" Out-Log "**************************************************************************************`n" # If requested, create DeployVM.csv and exit If ($createcsv) { If (Test-Path $exportpath) { Out-Log "`n$exportpath Already Exists!`n" "Red" Exit } Else { Out-Log "`nCreating $exportpath`n" "Yellow" $headers | Export-Csv $exportpath -NoTypeInformation Out-Log "Done!`n" Exit } } # Ensure PowerCLI is at least version 5.5 R2 (Build 1649237) If ((Get-PowerCLIVersion).Build -lt 1649237) { Out-Log "Error: DeployVM script requires PowerCLI version 5.5 R2 (Build 1649237) or later" "Red" Out-Log "PowerCLI Version Detected: $((Get-PowerCLIVersion).UserFriendlyVersion)" "Red" Out-Log "Exiting...`n`n" "Red" Exit } # Test to ensure csv file is available If ($csvfile -eq "" -or !(Test-Path $csvfile) -or !$csvfile.EndsWith("DeployVM.csv")) { Out-Log "Path to DeployVM.csv not specified...prompting`n" "Yellow" $csvfile = Read-OpenFileDialog "Locate DeployVM.csv" "C:\" "DeployVM.csv|DeployVM.csv" } If ($csvfile -eq "" -or !(Test-Path $csvfile) -or !$csvfile.EndsWith("DeployVM.csv")) { Out-Log "`nStill can't find it...I give up" "Red" Out-Log "Exiting..." "Red" Exit } Out-Log "Using $csvfile`n" "Yellow" # Make copy of DeployVM.csv If (!(Test-Path $deployedDir)) {New-Item -ItemType directory -Path $deployedDir | Out-Null} Copy-Item $csvfile -Destination $deployedFile | Out-Null # Import VMs from csv $newVMs = Import-Csv $csvfile $newVMs = $newVMs | Where {$_.Name -ne ""} [INT]$totalVMs = @($newVMs).count Out-Log "New VMs to create: $totalVMs" "Yellow" # Check to ensure csv is populated If ($totalVMs -lt 1) { Out-Log "`nError: No entries found in DeployVM.csv" "Red" Out-Log "Exiting...`n" "Red" Exit } # Show input and ask for confirmation, unless -auto was used If (!$auto) { $newVMs | Out-GridView -Title "VMs to be Created" $continue = Read-Host "`nContinue (y/n)?" If ($continue -notmatch "y") { Out-Log "Exiting..." "Red" Exit } } # Connect to vCenter server If ($vcenter -eq "") {$vcenter = Read-Host "`nEnter vCenter server FQDN or IP"} Try { Out-Log "`nConnecting to vCenter - $vcenter`n`n" "Yellow" Connect-VIServer $vcenter -EA Stop | Out-Null } Catch { Out-Log "`r`n`r`nUnable to connect to $vcenter" "Red" Out-Log "Exiting...`r`n`r`n" "Red" Exit } # Start provisioning VMs $v = 0 Out-Log "Deploying VMs`n" "Yellow" Foreach ($VM in $newVMs) { $Error.Clear() $vmName = $VM.Name $v++ $vmStatus = "[{0} of {1}] {2}" -f $v, $newVMs.count, $vmName Write-Progress -Activity "Deploying VMs" -Status $vmStatus -PercentComplete (100*$v/($newVMs.count)) # Create custom OS Custumization spec If ($vm.DHCP -match "true") { $spec = Get-OSCustomizationSpec -Name $VM.CustSpec $tempSpec = $spec | New-OSCustomizationSpec -Name temp$vmName $tempSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping ` -IpMode UseDhcp | Out-Null } Else { If ($VM.OSType -eq "Windows") { $spec = Get-OSCustomizationSpec -Name $VM.CustSpec $tempSpec = $spec | New-OSCustomizationSpec -Name temp$vmName $tempSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping ` -IpMode UseStaticIP -IpAddress $VM.IPAddress -SubnetMask $VM.SubnetMask ` -Dns $VM.pDNS,$VM.sDNS -DefaultGateway $VM.Gateway | Out-Null } ElseIF ($VM.OSType -eq "Linux") { $spec = Get-OSCustomizationSpec -Name $VM.CustSpec $tempSpec = $spec | New-OSCustomizationSpec -Name temp$vmName $tempSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping ` -IpMode UseStaticIP -IpAddress $VM.IPAddress -SubnetMask $VM.SubnetMask ` -DefaultGateway $VM.Gateway | Out-Null } } # Create VM Out-Log "Deploying $vmName" $taskTab[(New-VM -Name $VM.Name -ResourcePool $VM.ResourcePool -Location $VM.Folder -Datastore $VM.Datastore -DiskStorageFormat $VM.DiskStorageFormat ` -Notes $VM.Notes -Template $VM.Template -OSCustomizationSpec temp$vmName -RunAsync -EA SilentlyContinue).Id] = $VM.Name # Remove temp OS Custumization spec Remove-OSCustomizationSpec -OSCustomizationSpec temp$vmName -Confirm:$false # Log errors If ($Error.Count -ne 0) { If ($Error.Count -eq 1 -and $Error.Exception -match "'Location' expects a single value") { $vmLocation = $VM.Folder Out-Log "Unable to place $vmName in desired location, multiple $vmLocation folders exist, check root folder" "Red" } Else { Out-Log "`n$vmName failed to deploy!" "Red" Foreach ($err in $Error) { Out-Log "$err" "Red" } $failDeploy += @($vmName) } } } Out-Log "`n`nAll Deployment Tasks Created" "Yellow" Out-Log "`n`nMonitoring Task Processing" "Yellow" # When finsihed deploying, reconfigure new VMs $totalTasks = $taskTab.Count $runningTasks = $totalTasks while($runningTasks -gt 0){ $vmStatus = "[{0} of {1}] {2}" -f $runningTasks, $totalTasks, "Tasks Remaining" Write-Progress -Activity "Monitoring Task Processing" -Status $vmStatus -PercentComplete (100*($totalTasks-$runningTasks)/$totalTasks) Get-Task | % { if($taskTab.ContainsKey($_.Id) -and $_.State -eq "Success"){ #Deployment completed $Error.Clear() $vmName = $taskTab[$_.Id] Out-Log "`n`nReconfiguring $vmName" "Yellow" $VM = Get-VM $vmName $VMconfig = $newVMs | Where {$_.Name -eq $vmName} # Set CPU and RAM Out-Log "Setting vCPU(s) and RAM on $vmName" "Yellow" $VM | Set-VM -NumCpu $VMconfig.CPU -MemoryGB $VMconfig.RAM -Confirm:$false | Out-Null # Set port group on virtual adapter Out-Log "Setting Port Group on $vmName" "Yellow" If ($VMconfig.NetType -match "vSS") { $network = @{ 'NetworkName' = $VMconfig.network 'Confirm' = $false } } Else { $network = @{ 'Portgroup' = $VMconfig.network 'Confirm' = $false } } $VM | Get-NetworkAdapter | Set-NetworkAdapter @network | Out-Null # Add additional disks if needed If ($VMConfig.Disk2 -gt 1) { Out-Log "Adding additional disk on $vmName - don't forget to format within the OS" "Yellow" $VM | New-HardDisk -CapacityGB $VMConfig.Disk2 -StorageFormat $VMConfig.DiskStorageFormat -Persistence persistent | Out-Null } If ($VMConfig.Disk3 -gt 1) { Out-Log "Adding additional disk on $vmName - don't forget to format within the OS" "Yellow" $VM | New-HardDisk -CapacityGB $VMConfig.Disk3 -StorageFormat $VMConfig.DiskStorageFormat -Persistence persistent | Out-Null } If ($VMConfig.Disk4 -gt 1) { Out-Log "Adding additional disk on $vmName - don't forget to format within the OS" "Yellow" $VM | New-HardDisk -CapacityGB $VMConfig.Disk4 -StorageFormat $VMConfig.DiskStorageFormat -Persistence persistent | Out-Null } # Boot VM If ($VMconfig.Boot -match "true") { Out-Log "Booting $vmName" "Yellow" $VM | Start-VM -EA SilentlyContinue | Out-Null } $taskTab.Remove($_.Id) $runningTasks-- If ($Error.Count -ne 0) { Out-Log "$vmName completed with errors" "Red" Foreach ($err in $Error) { Out-Log "$Err" "Red" } $failReconfig += @($vmName) } Else { Out-Log "$vmName is Complete" "Green" $successVMs += @($vmName) } } elseif($taskTab.ContainsKey($_.Id) -and $_.State -eq "Error"){ # Deployment failed $failed = $taskTab[$_.Id] Out-Log "`n$failed failed to deploy!`n" "Red" $taskTab.Remove($_.Id) $runningTasks-- $failDeploy += @($failed) } } Start-Sleep -Seconds 10 } #-------------------------------------------------------------------- # Close Connections Disconnect-VIServer -Server $vcenter -Force -Confirm:$false #-------------------------------------------------------------------- # Outputs Out-Log "`n**************************************************************************************" Out-Log "Processing Complete" "Yellow" If ($successVMs -ne $null) { Out-Log "`nThe following VMs were successfully created:" "Yellow" Foreach ($success in $successVMs) {Out-Log "$success" "Green"} } If ($failReconfig -ne $null) { Out-Log "`nThe following VMs failed to reconfigure properly:" "Yellow" Foreach ($reconfig in $failReconfig) {Out-Log "$reconfig" "Red"} } If ($failDeploy -ne $null) { Out-Log "`nThe following VMs failed to deploy:" "Yellow" Foreach ($deploy in $failDeploy) {Out-Log "$deploy" "Red"} } $finishtime = Get-Date -uformat "%m-%d-%Y %I:%M:%S" Out-Log "`n`n" Out-Log "**************************************************************************************" Out-Log "$scriptName`t`t`t`t`tFinish Time:`t$finishtime" Out-Log "**************************************************************************************"
PowerShellCorpus/GithubGist/MikeAStevenson_a018025b0f12404d3d0e_raw_77e3bab52d923b041722c141bc316d8852b02d51_Get-LockedOutUsers.ps1
MikeAStevenson_a018025b0f12404d3d0e_raw_77e3bab52d923b041722c141bc316d8852b02d51_Get-LockedOutUsers.ps1
# # Date : 2014-10-31 M. Stevenson - Initial Version # Desc : Get users that were probably locked out by a # bad password # Get-ADUser -Filter { LockoutTime -gt 0 -and BadPwdCount -ge 5 } -Properties * | sort lockouttime -descending | ForEach-Object { $lockouttime = [DateTime]::FromFileTimeUtc($_.lockoutTime) $bptime = [DateTime]::FromFileTimeUtc($_.badPasswordTime) Write-Host "=================================================================================" Write-Host "$($_.SAMAccountName) ($($_.Name)) locked out on $lockouttime" Write-Host "Bad Password Time - $($bptime)" Write-Host "=================================================================================" }
PowerShellCorpus/GithubGist/jelster_e1cc34e3303dacaad36f_raw_075cda9d0c4c9e2a3ccee68b9ec06d856356e163_mech-importer.ps1
jelster_e1cc34e3303dacaad36f_raw_075cda9d0c4c9e2a3ccee68b9ec06d856356e163_mech-importer.ps1
Function Get-MwoBlenderMech { [CmdletBinding()] param( [Parameter(Position = 0, Mandatory = $True, ValueFromPipeline=$true)] [Alias('Family')] [Alias('Chassis')] [string[]]$MechFamily, [Parameter(Position=1, Mandatory=$false, valuefrompipeline=$false)] [Alias('Path')] [string]$BaseDirectory = ".\", [Parameter(Position=2, Mandatory=$false, ValueFromPipeline=$false)] [string]$UsePngImageFormat = $False ) process { # Python commands used by Blender $scriptimport = "bpy.ops.import_scene.obj" $scriptscene = "bpy.context.scene.objects.active" $scriptrotationmode = "bpy.context.active_object.rotation_mode=`"QUATERNION`"" $scriptrotation = "bpy.context.active_object.rotation_quaternion" $scripttransform = "bpy.ops.transform.translate" $scriptremovedoubles = "bpy.ops.mesh.remove_doubles()" $scripttristoquads = "bpy.ops.mesh.tris_convert_to_quads()" $scriptseteditmode = "bpy.ops.object.mode_set(mode = `"EDIT`")" $scriptsetobjectmode = "bpy.ops.object.mode_set(mode = `"OBJECT`")" $scriptclearmaterial = "bpy.context.object.data.materials.clear()" #only works with 2.69 or newer function getImagePath([string]$file) { $imgExten = $file.replace(".tif","$imageformat").replace(".dds",".$imageformat") if (!(test-path "$basedir\$imgExten")) { return "" } $imgPath = resolve-path ("$basedir\$imgExten") return $imgPath.Path.replace("\", "\\") } foreach($mech in $MechFamily) { if ($UsePngImageFormat[0] -eq $True) { $imageformat = ".png" } else { $imageformat = ".jpg" } $basedir = (resolve-path $BaseDirectory).Path $objectDir = Join-Path -Path $baseDir -ChildPath "objects" $modeldir = Join-Path -Path $objectDir -ChildPath "mechs\$mech" $mechFile = Join-Path -Path $modelDir -ChildPath ($mech + ".cdf") $modeldir = $modeldir.replace("\","\\") # convert the path so it can be used by Blender $bodyDir = join-path -Path $modelDir "body" $basedir = $basedir.Replace("\","\\") write-Debug "Mech is $mech" Write-Debug "Image format $imageformat" write-debug "Converted paths $basedir" Write-Debug "Model directory is $modeldir" Write-Debug "path to .CDF is $mechFile" write-debug "path to body is $bodyDir" if (!(test-path $mechFile)) { write-error "Unable to find the input .cdf file: $mechFile" continue } [xml]$cdffile = get-content $mechFile $mechFile = $mechFile.replace("\","\\") $importBuilder = new-object System.Text.StringBuilder # TODO: guard clauses around calls to Get-Content # *** MATERIALS *** # Load up materials from the <mech_body.mtl> file # Assumptions: The .cdf file we read has the name of the mech in it, and the mtl file is <mech>_body.mtl under the body subdirectory. # For the cockpit, the mtl file is <mech>_a_cockpit_standard, and under the cockpit_standard subdir. [xml]$matfile = get-content (resolve-path ("$bodyDir\\$mech" + "_body.mtl")) [xml]$matcockpitfile = Get-Content (resolve-path("$modeldir\cockpit_standard\$mech" + "_a_cockpit_standard.mtl")) # Set Blender to Cycles write-progress $importBuilder.AppendLine("bpy.context.scene.render.engine = 'CYCLES'").Length Write-Debug "Processing materials" # Get the 4 materials from $matfile and create them in Blender # material append wants an object of type material, not a string. Will have to generate that. # Since we can't really generate a node layout at this time, we're just going to open the image files # so it's easier for the user to generate. $matfile.Material.SubMaterials.Material | % { $matname = $_.Name # $matname is the name of the material write-Debug "material $matname" write-progress $importBuilder.AppendLine("$matname=bpy.data.materials.new('$matname')").Length write-progress $importBuilder.AppendLine("$matname.use_nodes=True").Length write-progress $importBuilder.AppendLine("$matname.active_node_material").Length write-progress $importBuilder.AppendLine("TreeNodes = $matname.node_tree").Length write-progress $importBuilder.AppendLine("links = TreeNodes.links").Length write-progress $importBuilder.AppendLine("for n in TreeNodes.nodes:").Length write-progress $importBuilder.AppendLine(" TreeNodes.nodes.remove(n)").Length write-progress $importBuilder.AppendLine("").Length #TODO check file existence (applies to all) $_.textures.Texture | % { write-debug "Texture $_.Map defines $_.File" if ( $_.Map -eq "Diffuse") { $matdiffuse = getImagePath($_.file).replace("/","\\") #assumes diffuse is in slot 0 write-progress $importBuilder.AppendLine("matDiffuse = bpy.data.images.load(filepath=`"$matdiffuse`")").Length write-progress $importBuilder.AppendLine("shaderDiffuse=TreeNodes.nodes.new('ShaderNodeBsdfDiffuse')").Length write-progress $importBuilder.AppendLine("shaderMix=TreeNodes.nodes.new('ShaderNodeMixShader')").Length write-progress $importBuilder.AppendLine("shout=TreeNodes.nodes.new('ShaderNodeOutputMaterial')").Length write-progress $importBuilder.AppendLine("shaderDiffImg=TreeNodes.nodes.new('ShaderNodeTexImage')").Length write-progress $importBuilder.AppendLine("shaderDiffImg.image=matDiffuse").Length write-progress $importBuilder.AppendLine("shaderDiffuse.location = 100,500").Length write-progress $importBuilder.AppendLine("shout.location = 500,400").Length write-progress $importBuilder.AppendLine("shaderMix.location = 300,500").Length write-progress $importBuilder.AppendLine("shaderDiffImg.location = -100,500").Length write-progress $importBuilder.AppendLine("links.new(shaderDiffuse.outputs[0],shaderMix.inputs[1])").Length write-progress $importBuilder.AppendLine("links.new(shaderMix.outputs[0],shout.inputs[0])").Length write-progress $importBuilder.AppendLine("links.new(shaderDiffImg.outputs[0],shaderDiffuse.inputs[0])").Length } if ($_.Map -eq "Specular") { $matspec = getImagePath($_.file).replace("/","\\") write-progress $importBuilder.AppendLine("matSpec=bpy.data.images.load(filepath=`"$matspec`")").Length write-progress $importBuilder.AppendLine("shaderSpec=TreeNodes.nodes.new('ShaderNodeBsdfGlossy')").Length write-progress $importBuilder.AppendLine("shaderSpecImg=TreeNodes.nodes.new('ShaderNodeTexImage')").Length write-progress $importBuilder.AppendLine("shaderSpecImg.image=matSpec").Length write-progress $importBuilder.AppendLine("shaderSpec.location = 100,300").Length write-progress $importBuilder.AppendLine("shaderSpecImg.location = -100,300").Length write-progress $importBuilder.AppendLine("links.new(shaderSpec.outputs[0],shaderMix.inputs[2])").Length write-progress $importBuilder.AppendLine("links.new(shaderSpecImg.outputs[0],shaderSpec.inputs[0])").Length } if ($_.Map -eq "Bumpmap") { $matnormal = getImagePath($_.file).replace("/", "\\") write-progress $importBuilder.AppendLine("matNormal=bpy.data.images.load(filepath=`"$matnormal`")").Length write-progress $importBuilder.AppendLine("shaderNormalImg=TreeNodes.nodes.new('ShaderNodeTexImage')").Length write-progress $importBuilder.AppendLine("shaderRGBtoBW=TreeNodes.nodes.new('ShaderNodeRGBToBW')").Length write-progress $importBuilder.AppendLine("shaderNormalImg.image=matNormal").Length write-progress $importBuilder.AppendLine("shaderNormalImg.location = -100,100").Length write-progress $importBuilder.AppendLine("shaderRGBtoBW.location = 100,100").Length write-progress $importBuilder.AppendLine("links.new(shaderNormalImg.outputs[0],shaderRGBtoBW.inputs[0])").Length write-progress $importBuilder.AppendLine("links.new(shaderRGBtoBW.outputs[0],shout.inputs[2])").Length } } } Write-debug "Processing cockpit materials" $matcockpitfile.Material.SubMaterials.Material | % { $matname = $_.Name write-progress $importBuilder.AppendLine("$matname=bpy.data.materials.new('$matname')").Length write-progress $importBuilder.AppendLine("$matname.use_nodes=True").Length write-progress $importBuilder.AppendLine("$matname.active_node_material").Length write-progress $importBuilder.AppendLine("TreeNodes = $matname.node_tree").Length write-progress $importBuilder.AppendLine("links = TreeNodes.links").Length write-progress $importBuilder.AppendLine("for n in TreeNodes.nodes:").Length write-progress $importBuilder.AppendLine(" TreeNodes.nodes.remove(n)").Length write-progress $importBuilder.AppendLine("").Length $_.textures.Texture | % { if ( $_.Map -eq "Diffuse") { $matdiffuse = getImagePath($_.file).replace("/", "\\") if ( $_.File.Contains("@") ) { #fixes monitor materials where it assigns a file that doesn't exist $matdiffuse = "$basedir\\libs\\UI\\HUD\\Screens\\Monitors\\killcount_i7$imageFormat" } write-progress $importBuilder.AppendLine("matDiffuse = bpy.data.images.load(filepath=`"$matdiffuse`")" ).Length write-progress $importBuilder.AppendLine("shaderDiffuse=TreeNodes.nodes.new('ShaderNodeBsdfDiffuse')" ).Length write-progress $importBuilder.AppendLine("shaderMix=TreeNodes.nodes.new('ShaderNodeMixShader')" ).Length write-progress $importBuilder.AppendLine("shout=TreeNodes.nodes.new('ShaderNodeOutputMaterial')" ).Length write-progress $importBuilder.AppendLine("shaderDiffImg=TreeNodes.nodes.new('ShaderNodeTexImage')" ).Length write-progress $importBuilder.AppendLine("shaderDiffImg.image=matDiffuse" ).Length write-progress $importBuilder.AppendLine("shaderDiffuse.location = 100,500" ).Length write-progress $importBuilder.AppendLine("shout.location = 500,400" ).Length write-progress $importBuilder.AppendLine("shaderMix.location = 300,500" ).Length write-progress $importBuilder.AppendLine("shaderDiffImg.location = -100,500" ).Length write-progress $importBuilder.AppendLine("links.new(shaderDiffuse.outputs[0],shaderMix.inputs[1])" ).Length write-progress $importBuilder.AppendLine("links.new(shaderMix.outputs[0],shout.inputs[0])" ).Length write-progress $importBuilder.AppendLine("links.new(shaderDiffImg.outputs[0],shaderDiffuse.inputs[0])" ).Length } if ($_.Map -eq "Specular") { $matspec = getImagePath($_.file).replace("/", "\\") write-progress $importBuilder.AppendLine("matSpec=bpy.data.images.load(filepath=`"$matspec`")" ).Length write-progress $importBuilder.AppendLine("shaderSpec=TreeNodes.nodes.new('ShaderNodeBsdfGlossy')" ).Length write-progress $importBuilder.AppendLine("shaderSpecImg=TreeNodes.nodes.new('ShaderNodeTexImage')" ).Length write-progress $importBuilder.AppendLine("shaderSpecImg.image=matSpec" ).Length write-progress $importBuilder.AppendLine("shaderSpec.location = 100,300" ).Length write-progress $importBuilder.AppendLine("shaderSpecImg.location = -100,300" ).Length write-progress $importBuilder.AppendLine("links.new(shaderSpec.outputs[0],shaderMix.inputs[2])" ).Length write-progress $importBuilder.AppendLine("links.new(shaderSpecImg.outputs[0],shaderSpec.inputs[0])" ).Length } if ($_.Map -eq "Bumpmap") { $matnormal = getImagePath($_.file).replace("/", "\\") write-progress $importBuilder.AppendLine("matNormal=bpy.data.images.load(filepath=`"$matnormal`")" ).Length write-progress $importBuilder.AppendLine("shaderNormalImg=TreeNodes.nodes.new('ShaderNodeTexImage')" ).Length write-progress $importBuilder.AppendLine("shaderRGBtoBW=TreeNodes.nodes.new('ShaderNodeRGBToBW')" ).Length write-progress $importBuilder.AppendLine("shaderNormalImg.image=matNormal" ).Length write-progress $importBuilder.AppendLine("shaderNormalImg.location = -100,100" ).Length write-progress $importBuilder.AppendLine("shaderRGBtoBW.location = 100,100" ).Length write-progress $importBuilder.AppendLine("links.new(shaderNormalImg.outputs[0],shaderRGBtoBW.inputs[0])" ).Length write-progress $importBuilder.AppendLine("links.new(shaderRGBtoBW.outputs[0],shout.inputs[2])" ).Length } } } Write-debug "Parsing .OBJ" # *** PARSING OBJs *** # Start parsing out $mechline $cdffile.CharacterDefinition.attachmentlist.Attachment | % { #TODO: If you're reading a .cdf file here, it's recursive and you'll have to load in a few more files. For now, just replace to .obj # for basic cockpit. $aname = $_.AName $rotation = $_.Rotation $position = $_.Position $bonename = $_.BoneName.replace(" ","_") write-debug ("attachment file path $binding " + (Test-Path ($baseDirectory + "\" + $_.Binding))) $binding = Get-Item -Path ($BaseDirectory + "\" + $_.Binding) write-debug "value of Binding: $binding" $binding_modified = $binding.FullName.replace(".cdf", ".obj").replace(".cga",".obj").replace(".cgf", ".obj").replace("\","\\") # For use by script $flags = $_.Flags if ($_.material) { # Material doesn't exist for every object. Don't set it if it doesn't. $material = $_.Material $matname = $material.split("/") $matname = $matname[-1] $material = $material.replace("/","\\") } # Figure out how to get the object name from $binding. [string]$objectname = $binding.BaseName # Time to generate the commands (in $parsedline, an array) $parsedline = @() # if it's a cockpit item, it'll have multiple groups. to avoid screwing up naming, we will import these keeping the vertex # order with split_mode('OFF'). We do NOT want to remove doubles though, as this destroys the UVMap. if ($objectname.Contains("cockpit")) { $parsedline += $scriptimport + "(filepath='$binding_modified',use_groups_as_vgroups=True,split_mode=`'OFF`')" } else { $parsedline += $scriptimport + "(filepath='$binding_modified',use_groups_as_vgroups=True,split_mode=`'OFF`')" } # set new object as the active object $parsedline += $scriptscene + "=bpy.data.objects[`"$objectname`"]" # Parent the object to the Armature: Assumes armature name is Armature and that it's been imported! # $parsedline += $scriptscene + "=bpy.data.objects[`"Armature`"]" # We may at this point (someday) to replace $objectname (above) with the $Aname, but for now let's stick with $objectname $parsedline += $scriptrotationmode $parsedline += $scriptrotation + "=[$rotation]" $parsedline += $scripttransform + "(value=($position))" $parsedline += $scriptclearmaterial $parsedline += $scriptseteditmode # Check to see if it's a cockpit item, and if so don't remove doubles! if ($objectname -ne $null -and !$objectname.Contains("cockpit")) { $parsedline += $scriptremovedoubles } $parsedline += $scripttristoquads # Create a vertex group with the bone name. This makes parenting to armature super easy! $parsedline += "bpy.ops.object.vertex_group_add()" $parsedline += "bpy.context.object.vertex_groups.active.name = `"$bonename`"" $parsedline += "bpy.ops.mesh.select_all(action=`'SELECT`')" $parsedline += "bpy.ops.object.vertex_group_assign()" $parsedline += "bpy.ops.mesh.select_all(action=`'TOGGLE`')" $parsedline += $scriptsetobjectmode $parsedline += "bpy.context.object.data.materials.append($matname)" foreach ($line in $parsedline ) { write-progress $importBuilder.AppendLine($line).Length } } Write-Output $importBuilder.ToString() } } }
PowerShellCorpus/GithubGist/adamskt_2891859_raw_5525efd457073af0117df0c9f05278c8f8ee3e12_GetLatestTfsDropLocation.ps1
adamskt_2891859_raw_5525efd457073af0117df0c9f05278c8f8ee3e12_GetLatestTfsDropLocation.ps1
Add-Type -AssemblyName "Microsoft.TeamFoundation.Client, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" Add-Type -AssemblyName "Microsoft.TeamFoundation.Build.Client, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" $tfsUri = New-object Uri("[[http://your.tfs.server:8080/defaultcollection]]") $teamProjectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsUri) $service = $teamProjectCollection.GetService([Type]"Microsoft.TeamFoundation.Build.Client.IBuildServer") $spec = $service.CreateBuildDetailSpec("[[Your Project Name]]", "[[ Your build definition name]]") $spec.MaxBuildsPerDefinition = 1 $spec.QueryOrder = [Microsoft.TeamFoundation.Build.Client.BuildQueryOrder]::FinishTimeDescending $spec.Status = [Microsoft.TeamFoundation.Build.Client.BuildStatus]::Succeeded $results = $service.QueryBuilds($spec) if ($results.Builds.Length -eq 1) { $results.Builds[0].DropLocation } else { Write-Error "No builds found." }
PowerShellCorpus/GithubGist/stevegood_733292_raw_c5ecc6725ae5d6d8ef3470b64f212197de6ebac6_Microsoft.PowerShell_profile.ps1
stevegood_733292_raw_c5ecc6725ae5d6d8ef3470b64f212197de6ebac6_Microsoft.PowerShell_profile.ps1
new-alias jrun "C:\ColdFusion9\runtime\bin\jrun.exe" function cf($server="coldfusion"){ jrun -start $server }
PowerShellCorpus/GithubGist/JFFail_48e7961082636c6747d5_raw_72dccdb939f76a62cdf9b375a0b91ced83ac3380_deparse-numbers.ps1
JFFail_48e7961082636c6747d5_raw_72dccdb939f76a62cdf9b375a0b91ced83ac3380_deparse-numbers.ps1
<# # Reddit Daily Programmer 199 Part 2 # http://www.reddit.com/r/dailyprogrammer/comments/2u0fyx/2015126_challenge_199_bank_number_banners_pt_2/ #> #Create the strings for the inputs. $inputTop = " _ _ _ _ _ _ _ " $inputMid = "|_| |_| | | |_| |_ | | | |_ " $inputBot = " | _| |_| |_| |_| | | | _|" #Hash table of possible solutions. $solutionHash = @{0=" _ ","| |","|_|";1=" "," |"," |";2=" _ "," _|","|_ ";3=" _ "," _|"," _|";4=" ","|_|"," |";5=" _ ","|_ "," _|";6=" _ ","|_ ","|_|";7=" _ "," |"," |";8=" _ ","|_|","|_|";9=" _ ","|_|"," _|"} #We know there are always 9 numbers. Start to parse them. for($i = 0; $i -lt 9; $i++) { #Make an empty array and string to temporarily store parsed values. $tempArray = @() $currentLine = "" #Added logic since the start-end index will be different after the first number due to spaces between them. if($i -gt 0) { #Start at a different location! $index = ($i*3)+$i } else { #Start at the beginning. $index = $i } #Parse the first line and write it to the array. $currentLine = $inputTop[$index] $currentLine += $inputTop[$index+1] $currentLine += $inputTop[$index+2] $tempArray += $currentLine #Parse the second line and add it to the array. $currentLine = $inputMid[$index] $currentLine += $inputMid[$index+1] $currentLine += $inputMid[$index+2] $tempArray += $currentLine #Parse the third line and add it to the array. $currentLine = $inputBot[$index] $currentLine += $inputBot[$index+1] $currentLine += $inputBot[$index+2] $tempArray += $currentLine #Compare the current array to the hash table. foreach($solution in $solutionHash.GetEnumerator()) { #Since the value and the tempArray are different types, compare their indexes! Each will be 3 in length. if($solution.Value[0] -eq $tempArray[0] -and $solution.Value[1] -eq $tempArray[1] -and $solution.Value[2] -eq $tempArray[2]) { Write-Host $solution.Key -NoNewLine } } } #Final newline. Write-Host ""
PowerShellCorpus/GithubGist/mikeplate_3789958_raw_a6d8aacada95cb55ddca20046ebdb3655caf6ab4_sp-create-users.ps1
mikeplate_3789958_raw_a6d8aacada95cb55ddca20046ebdb3655caf6ab4_sp-create-users.ps1
$user_list = "SPS_INSTALL", "SQL_SERVICE", "SPS_FARM", "SPS_APP_POOL1", "SPS_MYSITE", "SPS_SERVICES", "SPS_SEARCH", "SPS_CRAWL", "SPS_PROFILE", "SPS_CACHEADM", "SPS_CACHERD" function Gen-Password([int]$length) { $assembly = Add-Type -AssemblyName System.Web [System.Web.Security.Membership]::GeneratePassword($length, 2) } function Get-ScriptDirectory() { $invocation = (Get-Variable MyInvocation -Scope 1).Value Split-Path $invocation.MyCommand.Path } $output_file = Get-ScriptDirectory $output_file += "\sp-create-users-output.txt" $server = [ADSI]"WinNT://localhost" foreach ($user_data in $user_list) { $pwd = Gen-Password 10 # $user = $server.Create("User", $user_data[0]) # $user.SetPassword($user_data[1]) # $user.SetInfo() ($user_data + " " + $pwd) >> $output_file }
PowerShellCorpus/GithubGist/palmar_61bc83fff37b5c539577_raw_11614f5495670d7093ce51c295a91918339041f3_gistfile1.ps1
palmar_61bc83fff37b5c539577_raw_11614f5495670d7093ce51c295a91918339041f3_gistfile1.ps1
Write-Output "Do you want to play as Russia or USA?" $select = $false $dead = $false While($select -eq $false) { $a = Read-Host if($a -eq "Russia") { Write-Output "Greetings comrade" Write-Output " " $select = $true $opp = "USA" } elseif($a -eq "USA") { Write-Output "'MURICA, FUCK YEAH" Write-Output " " $select = $true $opp = "Russia" } else { Write-Output "Pick one or the other loser" Write-Output " " } } $i = 1 While($dead -eq $false) { Write-Output "It is now day $i. Do you want to nuke $opp" $b = Read-Host if($b -eq "y") { Write-Output "They nuke you back, the world ends in a nucelar holocaust. Everyone is dead. You made it to day $i" $dead = $true sleep -Seconds 10 } elseif($b -eq "n") { Write-Output "Okay, you did a good job today commander. See you tomorrow." Write-Output " " $i = $i + 1 } else { Write-Output "This code sucks and only accepts y or n" Write-Output " " } }
PowerShellCorpus/GithubGist/jbarber_464358_raw_b45f8b7ec2f3a48aa68e7cd44c0e8bf5f27ee86f_deballoon.ps1
jbarber_464358_raw_b45f8b7ec2f3a48aa68e7cd44c0e8bf5f27ee86f_deballoon.ps1
# VMware: set the advanced configuration option sched.mem.maxmemctl to zero to prevent ballooning function deballoon ($vmname) { # Set "sched.mem.maxmemctl" to 0 $opt = new-object Vmware.Vim.OptionValue -Property @{ Key = "sched.mem.maxmemctl"; Value = 0 } $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec $vmConfigSpec.extraconfig += $opt # Use a filter to find a particular VM $vm = get-view -viewtype "VirtualMachine" -filter @{ "Name" = $vmname } # And update the config on the server $vm.ReconfigVM( $vmConfigSpec ) } connect-viserver -server virtualcenter -credential (Get-Credential (Get-Item env:username).value) deballoon( "vm-name" )
PowerShellCorpus/GithubGist/seanbamforth_9388507_raw_55c4b36df66b6bac7dd809d0029553073969ac93_AmazonEtagHashForFile.ps1
seanbamforth_9388507_raw_55c4b36df66b6bac7dd809d0029553073969ac93_AmazonEtagHashForFile.ps1
#Calculates an eTag for a local file that should match the S3 eTag of the uploaded file. $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider $blocksize = (1024*1024*5) $startblocks = (1024*1024*16) function AmazonEtagHashForFile($filename) { $lines = 0 [byte[]] $binHash = @() $reader = [System.IO.File]::Open($filename,"OPEN","READ") if ((Get-Item $filename).length -gt $startblocks) { $buf = new-object byte[] $blocksize while (($read_len = $reader.Read($buf,0,$buf.length)) -ne 0){ $lines += 1 $binHash += $md5.ComputeHash($buf,0,$read_len) } $binHash=$md5.ComputeHash( $binHash ) } else { $lines = 1 $binHash += $md5.ComputeHash($reader) } $reader.Close() $hash = [System.BitConverter]::ToString( $binHash ) $hash = $hash.Replace("-","").ToLower() if ($lines -gt 1) { $hash = $hash + "-$lines" } return $hash }
PowerShellCorpus/GithubGist/gpduck_6308785_raw_e4774a06530f5bd6fa7c63a03c3d81e38cb27846_Get-HexValue.ps1
gpduck_6308785_raw_e4774a06530f5bd6fa7c63a03c3d81e38cb27846_Get-HexValue.ps1
function Get-HexValue { param( [Parameter(Mandatory=$true)] [Char]$Character, [ValidateSet("ASCII","BigEndianUnicode","Default","Unicode","UTF32","UTF7","UTF8")] [String]$Encoding = "Unicode" ) $E = [Text.Encoding]::$Encoding $Bytes = $E.GetBytes($Character) if($Encoding -ne "BigEndianUnicode") { [Array]::Reverse($Bytes) } -join ( $Bytes | Foreach-Object { "{0:X2}" -f $_ }) }
PowerShellCorpus/GithubGist/johndacosta_6081808_raw_00aa982a3f7642d3c408de3e34ae03e4794f174c_Get-SQLServerDatabaseUsers.ps1
johndacosta_6081808_raw_00aa982a3f7642d3c408de3e34ae03e4794f174c_Get-SQLServerDatabaseUsers.ps1
## Invoke by Running .\Get-SQLServerDatabaseUsers.ps1 SQLSERVER\INSTANCENAME ## Gets List of Applications, Users and Host Names from SQL Server Default Trace param( [string] $ServerInstance = $(Throw "Provide a SQL Server Instance Name as first parameter") ) [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO'); [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") $QueryApplications = "SELECT DISTINCT t.ServerName,t.DatabaseName, t.DatabaseID,t.NTUserName,t.NTDomainName,t.HostName,t.ApplicationName,t.LoginName,t.DBUserName,t.LinkedServerName,t.SessionLoginName FROM sys.fn_trace_gettable(CONVERT(VARCHAR(150), ( SELECT TOP 1 f.[value] FROM sys.fn_trace_getinfo(NULL) f WHERE f.property = 2 )), DEFAULT) T" $QueryApplicationsResults = Invoke-Sqlcmd -ServerInstance $ServerInstance -Query $QueryApplications $QueryApplicationsResults | Select-Object ServerName,DatabaseName,DatabaseID,NTUserName,NTDomainName,HostName,ApplicationName,LoginName,DBUserName,LinkedServerName,SessionLoginName | ConvertTo-JSON
PowerShellCorpus/GithubGist/mkropat_0aa2b45503bcc9fc4b6f_raw_6f8dba73e4dbb5b1ca50ec03dd9f38e8c42fe38c_provision-base-box.ps1
mkropat_0aa2b45503bcc9fc4b6f_raw_6f8dba73e4dbb5b1ca50ec03dd9f38e8c42fe38c_provision-base-box.ps1
# provision-base-box.ps1 - Prepare Server 2012 for building a Vagrant base box # Instructions: # # 1. Create a new Windows VM in VirtualBox # 2. Install Server 2012 R2 onto the VM # 3. Download and run this script from within the VM # 4. Install Windows Updates within the VM # 5. From the host machine, run: `vagrant package --base <name of VM in VirtualBox> --output <name>.box` # 6. Then run: `vagrant box add <name> /path/to/<name>.box function main { Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -force Disable-UAC Write-Status "User Access Control (UAC) has been disabled." Disable-ServerManagerStartup Write-Status "Server Manager is disabled from running at logon." Disable-IEEnhancedSecurity Write-Status "IE Enhanced Security Configuration (ESC) has been disabled." Disable-ShutdownTracker Write-Status "Shutdown Tracker has been disabled." Disable-AutomaticUpdates Write-Status "Windows Update has been disabled." Disable-PasswordComplexityRequirements Write-Status "Passwords complexity requirements have been eased." Enable-RemoteDesktop Write-Status "Remote desktop enabled." Enable-WinRM Write-Status "WinRM has been configured and enabled." Disable-Firewall Write-Status "Windows Firewall has been disabled." Rename-User "Administrator" "vagrant" -ErrorAction SilentlyContinue Set-UserPassword "vagrant" "vagrant" Write-Status "Created 'vagrant' account from builtin 'Administrator' account." Write-Host "Restarting Computer." -ForegroundColor Yellow Restart-Computer } function Disable-UAC { New-ItemProperty -Path 'HKLM:Software\Microsoft\Windows\CurrentVersion\Policies\System' -Name EnableLUA -PropertyType DWord -Value 0 -Force | Out-Null } function Disable-ServerManagerStartup { New-ItemProperty -Path 'HKLM:\Software\Microsoft\ServerManager' -Name DoNotOpenServerManagerAtLogon -PropertyType DWord -Value 1 -Force | Out-Null New-ItemProperty -Path 'HKCU:Software\Microsoft\ServerManager' -Name CheckedUnattendLaunchSetting -PropertyType DWord -Value 0 -Force | Out-Null } function Disable-IEEnhancedSecurity { $componentBasePath = 'HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components' $componentIds = @( '{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}', '{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}' ) foreach ($id in $componentIds) { $path = Join-Path $componentBasePath $id Set-ItemProperty -Path $path -Name 'IsInstalled' -Value 0 | Out-Null } Stop-Process -Name Explorer | Out-Null } function Disable-ShutdownTracker { # Reference: http://www.askvg.com/how-to-disable-remove-annoying-shutdown-event-tracker-in-windows-server-2003-2008/ $reliabililtyPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" If (!(Test-Path $reliabililtyPath)) { New-Item -Path $reliabililtyPath } New-ItemProperty -Path $reliabililtyPath -Name "ShutdownReasonOn" -PropertyType DWord -Value 0 -Force -ErrorAction Continue | Out-Null New-ItemProperty -Path $reliabililtyPath -Name "ShutdownReasonUI" -PropertyType DWord -Value 0 -Force -ErrorAction Continue | Out-Null } function Disable-AutomaticUpdates { # Reference: http://www.benmorris.me/2012/05/1st-test-blog-post.html $autoUpdateSettings = (New-Object -ComObject "Microsoft.Update.AutoUpdate").Settings $autoUpdateSettings.NotificationLevel = 1 $autoUpdateSettings.Save() } function Disable-PasswordComplexityRequirements { # Reference: http://vlasenko.org/2011/04/27/removing-password-complexity-requirements-from-windows-server-2008-core/ $seccfg = [IO.Path]::GetTempFileName() try { Run-Silently secedit /export /cfg $seccfg (Get-Content $seccfg) | foreach { $_ -replace "PasswordComplexity\s*=\s*1", "PasswordComplexity=0" } | Set-Content $seccfg Run-Silently secedit /configure /db $env:windir\security\new.sdb /cfg $seccfg /areas SECURITYPOLICY } finally { Remove-Item $seccfg } } function Enable-RemoteDesktop { # Reference: http://social.technet.microsoft.com/Forums/windowsserver/en-US/323d6bab-e3a9-4d9d-8fa8-dc4277be1729/enable-remote-desktop-connections-with-powershell $tsSettings = Get-WmiObject Win32_TerminalServiceSetting -Namespace root\cimv2\TerminalServices $tsSettings.SetAllowTsConnections(1,1) | Out-Null $tsGeneralSettings = Get-WmiObject -Class "Win32_TSGeneralSetting" -Namespace root\cimv2\TerminalServices -Filter "TerminalName='RDP-tcp'" $tsGeneralSettings.SetUserAuthenticationRequired(0) | Out-Null } function Enable-WinRM { Run-Silently winrm quickconfig -q Run-Silently winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="512"}' Run-Silently winrm set winrm/config '@{MaxTimeoutms="1800000"}' Run-Silently winrm set winrm/config/service '@{AllowUnencrypted="true"}' Run-Silently winrm set winrm/config/service/auth '@{Basic="true"}' } function Disable-Firewall { Run-Silently netsh advfirewall set allprofiles state off } function Rename-User { [CmdletBinding()] param($user, $newName) $adsiUser = [adsi]"WinNT://./$user,user" $adsiUser.PSBase.Rename($newName) } function Set-UserPassword($user, $password) { Run-Silently net user $user $password } function Run-Silently { param( [string]$script, [parameter(ValueFromRemainingArguments=$true)] $args ) $output = & $script $args 2>&1 | Out-String if (-not $?) { Write-Output $output } } function Write-Status($text) { Write-Host $text -ForegroundColor Green } main
PowerShellCorpus/GithubGist/gravejester_474bb7f65062d8de168c_raw_943ff8363642427e3a3ac60d93ecc8ce4102d090_Get-VMWareResourceStatus.ps1
gravejester_474bb7f65062d8de168c_raw_943ff8363642427e3a3ac60d93ecc8ce4102d090_Get-VMWareResourceStatus.ps1
function Get-VMWareResourceStatus { <# .SYNOPSIS Get resource status from VMWare vSphere .DESCRIPTION Get overall status, configuration status and any configuration issues on VMWare resources by querying vSphere. .EXAMPLE Get-VMWareResourceStatus -VIServer 'VIServer01' -ResourceType 'VirtualMachine' Get the resource status of all virtual machines from 'VIServer01' .EXAMPLE Get-VMWareResourceStatus -VIServer 'VIServer01','VIServer02' -Name 'ESXHost01' -ResourceType 'HostSystem' Get the resource status of ESX host 'ESXHost01' by querying VIServer01 and VIServer02 .EXAMPLE Get-VMWareResourceStatus -VIServer 'VIServer01' -Name 'Server01','Server02' -ResourceType 'VirtualMachine' Get resource status for Server01 and Server02 from VIServer01 .NOTES Author: Øyvind Kallstad Date: 15.10.2014 Version: 1.0 #> [CmdletBinding()] param ( # vSphere server(s) to connect to [Parameter(Mandatory = $true)] [string[]] $VIServer, # Name(s) used to filter the result [Parameter()] [string[]] $Name, # ResourceType to search for [Parameter(Mandatory = $true)] [ValidateSet('ClusterComputeResource','ComputeResource','Datacenter','Datastore','DistributedVirtualPortgroup','DistributedVirtualSwitch','Folder','HostSystem','Network','ResourcePool','StoragePod','VirtualApp','VirtualMachine','VmwareDistributedVirtualSwitch')] [string] $ResourceType ) try { # Check if VMWare snapin is loaded, and load it if it's not if ((Get-PSSnapin -Name 'VMWare.VimAutomation.Core' -ErrorAction 'SilentlyContinue') -eq $null) { Add-PSSnapin -Name 'VMWare.VimAutomation.Core' Write-Verbose 'VMWare.VimAutomation.Core snapin loaded' } # Connect to VIserver(s) Connect-VIServer -Server $VIServer -WarningAction 'SilentlyContinue' | Out-Null Write-Verbose 'Connected to VIServer(s)' if ($PSBoundParameters['Name']) { # if more than one name is given, generate correct regex for the filtering if ($Name.Length -gt 1) { $regexString = ($Name | ForEach-Object {"($($_)`$)"}) -Join '|' Get-View -ViewType $ResourceType -Property Name,OverallStatus,ConfigStatus,ConfigIssue -Filter @{"Name"=$regexString} | Select-Object Name,OverallStatus,ConfigStatus,ConfigIssue } # if only one name is given, the filter is easier else { Get-View -ViewType $ResourceType -Property Name,OverallStatus,ConfigStatus,ConfigIssue -Filter @{"Name"="$($Name)`$"} | Select-Object Name,OverallStatus,ConfigStatus,ConfigIssue } Write-Verbose 'Got data from vSphere' } # if the name parameter is not used, no filtering is done else { Get-View -ViewType $ResourceType -Property Name,OverallStatus,ConfigStatus,ConfigIssue | Select-Object Name,OverallStatus,ConfigStatus,ConfigIssue Write-Verbose 'Got data from vSphere' } } catch { Write-Warning $_.Exception.Message } }
PowerShellCorpus/GithubGist/erik-kallen_3437689_raw_2c839e276282ecd679cac84c5db109fe2d811d68_GenerateSqlClrAssemblySql.ps1
erik-kallen_3437689_raw_2c839e276282ecd679cac84c5db109fe2d811d68_GenerateSqlClrAssemblySql.ps1
Param( [Parameter(Mandatory=$true)][string] $File, [string]$Schema = "dbo", [string]$PermissionSet = "safe" ) Function Parse-Attr($attr) { if ($attr) { $result = @{ "TypeName" = $attr.AttributeType.Name } $attr.Properties | % { $result[$_.Name] = $_.Argument.Value } $result } else { $null } } Function Get-SqlName($item, $attrData) { if ($attr.Name) { $attr.Name } else { $item.Name } } Function Get-ParameterSql($param) { "@$($param.Name) $(Get-TypeSql $param.ParameterType ($param.CustomAttributes | % { Parse-Attr $_ }))" } Function Get-TypeName($type, $attrData) { if (-not $attrData) { $attrData = $type.CustomAttributes | ? { $_.AttributeType.Namespace -eq "Microsoft.SqlServer.Server" } | % { Parse-Attr $_ } } Get-QualifiedName (Get-SqlName $type $attrData) } Function Get-QualifiedName($name) { if ($name -match "^(.*?)\.(.*)$") { "[$($matches[1])].[$($matches[2])]" } else { "[$Schema].[$name]" } } Function Get-SimpleTypeSql($type, $attrData) { switch ($type.FullName) { { $_ -eq "System.String" -or $_ -eq "System.Data.SqlTypes.SqlString" } { if ($attrData.MaxSize) { $maxSize = $attrData.MaxSize } else { $maxSize = 4000 } if ($MaxSize -le -0) { "nvarchar(max)" } elseif ($attrData.IsFixedLength) { "nchar($maxSize)" } else { "nvarchar($maxSize)" } } "System.Char" { "nchar(1)" } { $_ -eq "System.Single" -or $_ -eq "System.Data.SqlTypes.SqlSingle" } { "real" } { $_ -eq "System.Double" -or $_ -eq "System.Data.SqlTypes.SqlDouble" } { "float" } { $_ -eq "System.Decimal" -or $_ -eq "System.Data.SqlTypes.SqlDecimal" } { if ($attrData.Scale -gt 0) { $scale = $attrData.Scale } else { $scale = 0 } if ($attrData.Precision -gt 0) { $precision = $attrData.Precision } else { $precision = 18 } "numeric($precision, $scale)" } { $_ -eq "System.Boolean" -or $_ -eq "System.Data.SqlTypes.SqlBoolean" } { "bit" } { $_ -eq "System.Int64" -or $_ -eq "System.Data.SqlTypes.SqlInt64" } { "bigint" } { $_ -eq "System.Int32" -or $_ -eq "System.Data.SqlTypes.SqlInt32" } { "int" } { $_ -eq "System.Int16" -or $_ -eq "System.Data.SqlTypes.SqlInt16" } { "smallint" } { $_ -eq "System.Byte" -or $_ -eq "System.Data.SqlTypes.SqlByte" } { "tinyint" } "System.Object" { "sql_variant" } "System.Data.SqlTypes.SqlXml" { "xml" } { $_ -eq "System.Byte[]" -or $_ -eq "System.Data.SqlTypes.SqlBinary" } { if ($attrData.MaxSize) { $maxSize = $attrData.MaxSize } else { $maxSize = 8000 } if ($maxSize -le 0) { "varbinary(max)" } elseif ($attrData.IsFixedLength) { "binary($maxSize)" } else { "varbinary($maxSize)" } } { $_ -eq "System.Guid" -or $_ -eq "System.Data.SqlTypes.SqlGuid" } { "uniqueidentifier" } { $_ -eq "System.DateTime" -or $_ -eq "System.Data.SqlTypes.SqlDateTime" } { "datetime" } "System.Data.SqlTypes.SqlMoney" { "money" } default { if ($type -is [Mono.Cecil.TypeDefinition]) { Get-TypeName $type } else { throw "Unknown argument type $type" } } } } Function Get-TypeSql($type, $attrData) { if (($type.GenericArguments.Count -eq 1) -and ($type.ElementType.FullName -eq "System.Nullable``1")) { Get-TypeSql $type.GenericArguments[0] $attrData return } if ($type.IsByReference) { "$(Get-SimpleTypeSql $type.ElementType $attrData) OUT" } else { Get-SimpleTypeSql $type $attrData } } Function Get-CallSpec($method) { "AS EXTERNAL NAME [$($asm.Name.Name)].[$($method.DeclaringType.FullName)].[$($method.Name)]" } Function Get-ReturnTypeSql($method) { "$(Get-TypeSql $method.ReturnType ($method.MethodReturnType.CustomAttributes | % { Parse-Attr $_ }))" } Function GenerateFunctionSql($method, $attrData) { $name = Get-SqlName $method $attrData $tableDefinition = $attr.TableDefinition if ($tableDefinition) { $returnType = "TABLE ($tableDefinition)" } else { $returnType = Get-ReturnTypeSql $method } "CREATE FUNCTION $(Get-QualifiedName $name)($(($method.Parameters | % { Get-ParameterSql $_ }) -join ", ")) RETURNS $returnType $(Get-CallSpec $method)" } Function GenerateProcedureSql($method, $attrData) { $name = Get-SqlName $method $attrData if ($method.Parameters.Count -gt 0) { $paramspec = "($(($method.Parameters | % { Get-ParameterSql $_ }) -join ", "))" } else { $paramspec = "" } "CREATE PROCEDURE $(Get-QualifiedName $name)$paramspec $(Get-CallSpec $method)" } Function GenerateTriggerSql($method, $attrData) { $name = Get-SqlName $method $attrData "CREATE TRIGGER $(Get-QualifiedName $name) ON $(Get-QualifiedName($attrData.Target)) $($attrData.Event) $(Get-CallSpec $method)" } Function GenerateUserDefinedAggregateSql($type, $attrData) { $name = Get-SqlName $type $attrData $params = $type.Methods | ? { $_.Name -eq "Accumulate" } | % { $_.Parameters } | % { Get-ParameterSql $_ } $rettype = $type.Methods | ? { $_.Name -eq "Terminate" } | % { Get-ReturnTypeSql $_ } "CREATE AGGREGATE $(Get-QualifiedName $name)($($params -join ", ")) RETURNS $rettype EXTERNAL NAME [$($asm.Name.Name)].[$($type.FullName)]" } Function GenerateUserDefinedTypeSql($type, $attrData) { "CREATE TYPE $(Get-TypeName $type $attrData) EXTERNAL NAME [$($asm.Name.Name)].[$($type.FullName)]" } Function CreateSqlForMethods() { process { $method = $_ $attr = $method.CustomAttributes | ? { $_.AttributeType.Namespace -eq "Microsoft.SqlServer.Server" } | % { Parse-Attr $_ } if ($attr -ne $null) { if ($attr -is [Array]) { throw "More than one attribute from the namespace 'Microsoft.SqlServer.Server' on the method $($_.Name)." } switch ($attr.TypeName) { "SqlFunctionAttribute" { GenerateFunctionSql $method $attr } "SqlProcedureAttribute" { GenerateProcedureSql $method $attr } "SqlTriggerAttribute" { GenerateTriggerSql $method $attr } "SqlMethodAttribute" {} # Nothing to do, AFAIK default { throw "Unsupported attribute $($attr.AttributeType.Name)" } } } } } Function CreateSqlForTypes() { process { $type = $_ $attr = $type.CustomAttributes | ? { $_.AttributeType.Namespace -eq "Microsoft.SqlServer.Server" } | % { Parse-Attr $_ } if ($attr -ne $null) { if ($attr -is [Array]) { throw "More than one attribute from the namespace 'Microsoft.SqlServer.Server' on the type $($_.FullName)." } switch ($attr.TypeName) { "SqlUserDefinedTypeAttribute" { GenerateUserDefinedTypeSql $type $attr } "SqlUserDefinedAggregateAttribute" { GenerateUserDefinedAggregateSql $type $attr } default { throw "Unsupported attribute $($attr.AttributeType.Name)" } } } $_.Methods | CreateSqlForMethods } } Function BinaryContentToHex([string]$File, [int]$MaxBytesPerLine = [int]::MaxValue) { $content = [System.IO.File]::ReadAllBytes($File) $sb = New-Object System.Text.StringBuilder $index = 0 while ($index -lt $content.Length) { if ($index -gt 0) { $sb.AppendLine("\") > $null } $sb.AppendFormat([System.BitConverter]::ToString($content, $index, [System.Math]::Min($content.Length - $index, $MaxBytesPerLine)) -replace "-", "") > $null $index += $MaxBytesPerLine } $sb.ToString() } Import-Module .\Mono.Cecil.dll $resolvedPath = Resolve-Path "$File" $asm = [Mono.Cecil.AssemblyDefinition]::ReadAssembly($resolvedPath) @" CREATE ASSEMBLY [$($asm.Name.Name)] AUTHORIZATION dbo FROM 0x$(BinaryContentToHex $resolvedPath -MaxBytesPerLine 1000) WITH PERMISSION_SET = $($PermissionSet.ToUpper()) "@ $asm | % { $_.Modules } | % { $_.Types } | CreateSqlForTypes
PowerShellCorpus/GithubGist/phwelo_b629d76ac175ad1e0497_raw_653a9cfb73e6028fb2bc54e0ba14f7e10cd2cc06_gistfile1.ps1
phwelo_b629d76ac175ad1e0497_raw_653a9cfb73e6028fb2bc54e0ba14f7e10cd2cc06_gistfile1.ps1
Get-Federationtrust | Set-FederationTrust –RefreshMetadata
PowerShellCorpus/GithubGist/yzorg_88d041f0e69f45a967b2_raw_d5238641c56f7e318d30c9b6952834a4b9c86fed_CreateHardLinks.ps1
yzorg_88d041f0e69f45a967b2_raw_d5238641c56f7e318d30c9b6952834a4b9c86fed_CreateHardLinks.ps1
#CreateHardLinks -source C:\folderD -destination c:\folderC -recurse function CreateHardLinks ($Source, $Destination, [switch]$Recurse) { # Copy of directory structure best handled with `robocopy /E /XF *`, # which will copy directory timestamps. if ($recurse) { robocopy $Source $Destination /E /XF * /DCOPY:T } Get-ChildItem $source -Recurse:$recurse -File | %{ $currFile = $_.Fullname $newLink = $currFile -replace [regex]::Escape($source), $destination #if(!(Test-Path (Split-Path $newLink))) { # #Create missing subfolders # md (Split-Path $newLink) -Verbose #} cmd /c ('mklink /H "{0}" "{1}"' -f $newLink,$currFile) if (!$?) { Write-Warning ("bad command: " + ('mklink /H "{0}" "{1}"' -f $newLink,$currFile)) throw "mklink failed - EXITCODE $LastExitCode - on $currFile" } } }
PowerShellCorpus/GithubGist/vongillern_5404915_raw_d1738a00c63a075559a29ed00b555d7cd7ce36cf_gistfile1.ps1
vongillern_5404915_raw_d1738a00c63a075559a29ed00b555d7cd7ce36cf_gistfile1.ps1
#profile.example.ps1 Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent) # Load posh-git module from current directory Import-Module .\posh-git # If module is installed in a default location ($env:PSModulePath), # use this instead (see about_Modules for more information): # Import-Module posh-git # Set up a simple prompt, adding the git prompt parts inside git repos function prompt { $realLASTEXITCODE = $LASTEXITCODE # Reset color, which can be messed up by Enable-GitColors $Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor # ADDED - extra line so commands don't run together. Whitespace is nice. Write-Host("") Write-Host($pwd) -nonewline Write-VcsStatus $global:LASTEXITCODE = $realLASTEXITCODE # MODIFIED - Added linebreak after the path + git status # See screenshot here: http://pic.twitter.com/GSmZcWBtYQ return " >> " } Enable-GitColors Pop-Location Start-SshAgent -Quiet
PowerShellCorpus/GithubGist/aggieben_227582_raw_3d3d8c926607e4230ffc330132a67bc9fbc829d5_Enable-SPAjax.ps1
aggieben_227582_raw_3d3d8c926607e4230ffc330132a67bc9fbc829d5_Enable-SPAjax.ps1
# script for AJAX-enabling a SharePoint (MOSS 2007 / WSS 3.0) config # Copyright © 2009 Benjamin Collins <ben.collins@acm.org> # # Compatible with .NET 3.5 AJAX support and AJAX Control Toolkit # # usage: # enable-spajax <path to web.config> # function usage { write-host "Enable-SpAjax <path>" write-host "Copyright © 2009 Benjamin Collins <ben.collins@acm.org>" } # validate args if ($args.count -eq 1 && $args{0} # First, create backup Write-Host "Making backup..." copy-item $args{0}
PowerShellCorpus/GithubGist/robertchong_e2c64ddae8c3369bd289_raw_8f455e4721bfa66518bbc5e81d47f12c40eb0811_Get-LoggedOnUsers.ps1
robertchong_e2c64ddae8c3369bd289_raw_8f455e4721bfa66518bbc5e81d47f12c40eb0811_Get-LoggedOnUsers.ps1
<# .Synopsis This script will use the Sysinternals PsLoggedon.exe tool to get the list of users logged onto a workstation or computer .Description The script has a check built in to validate that the computer name belongs to your domain. It will also get the full name of the logged on user back in the results. There is a built in check to ask the operator if they would like to rerun the script. The script can be used with the parameter PathToPSLoggedon to specify the location of PsLoggedon.exe. Or this can be set to always default to this location. The script is built upon the original by Glenn Sizemore detailed at http://goo.gl/21qFZ .Parameter PathToPSLoggedon Alter the location of the path to PsLoggedon.exe .Example PS C:> .\Get-LoggedOnUsers.ps1 -PathToPSLoggedon "\\server\share\_Tools\PSTools\" Enter the name of computer or server to check: PC1 ..... User(s) logged onto PC1 Domain User ------ ---- DOMAIN Joe Bloggs ..... .Notes NAME: Get-LoggedOnUsers AUTHOR: jdunlop LASTEDIT: Thursday, 8 September 2011 KEYWORDS: #Requires -Version 2.0 #> Param( [Parameter()] [String]$PathToPSLoggedon #= "\\server\share\_Tools\PSTools\" ) $Searcher = New-Object DirectoryServices.DirectorySearcher([ADSI]"") While ($choice -ne 1) { Clear-Host While ($account -ne "") { $Computer = Read-Host "Enter the name of computer to check for logged on users" Clear-Host $Searcher.filter = "(&(objectCategory=Computer)(cn=$Computer))" $account = $searcher.findone() If ($account) {break} Write-Warning "No computer account exists for $(($Computer).ToUpper()) in the Domain." } # End While $Results = $null [object[]]$Results = Invoke-Expression ($PathToPSLoggedon + "PsLoggedon.exe -accepteula -x -l \\$Computer 2> null") | Where-Object {$_ -match '^\s{2,}((?<domain>\w+)\\(?<user>\S+))'} | Select-Object @{ Name = 'Domain' Expression = {$matches.Domain} }, # End Expression @{ Name = 'User' Expression = { $Searcher.filter = "(&(objectcategory=person)(objectclass=user)(SAMAccountName=$($matches.user)))" ($searcher.findone()).properties.displayname } # End Expression } # End hash table "User(s) logged onto $(($Computer).ToUpper())" $Results | Format-Table -auto $title = 'Would you like to rerun?' $rerun = New-Object System.Management.Automation.Host.ChoiceDescription '&Rerun','Rerun the script' $exit = New-Object System.Management.Automation.Host.ChoiceDescription '&Exit','Aborts the script' $options = [System.Management.Automation.Host.ChoiceDescription[]] ($rerun,$exit) $choice = $host.ui.PromptForChoice($title,$null,$options,1) } # End While
PowerShellCorpus/GithubGist/ao-zkn_114e0175345cb899395f_raw_f594dda3cd9e5725dc99f64b336cf1abaf624429_Out-LogFile.ps1
ao-zkn_114e0175345cb899395f_raw_f594dda3cd9e5725dc99f64b336cf1abaf624429_Out-LogFile.ps1
# ------------------------------------------------------------------ # ログをファイルに出力する # 関数名:Out-LogFile # 引数 :LogFilePath ログファイルパス # :Value ログとして出力する文字列 # :LogType ログの種類(0:デバック,1:情報,2:警告,3:エラー) # 指定がない場合は「情報」として出力 # :Encoding 文字コード # 指定がない場合は「UTF8」として出力 # 戻り値:なし # ------------------------------------------------------------------ function Out-LogFile([String]$LogFilePath,[String]$Value,[Int]$LogType=1,[String]$LogEncoding="utf8"){ # 日付のフォーマット [String]$LogDateFormat = "yyyy/MM/dd HH:mm:ss.fff" if($Value){ switch ($LogType){ 0{ [String]$log = (Get-Date -Format $LogDateFormat) + " [DEBUG] : " + $Value } 1{ [String]$log = (Get-Date -Format $LogDateFormat) + " [INFO ] : " + $Value } 2{ [String]$log = (Get-Date -Format $LogDateFormat) + " [WARN ] : " + $Value } 3{ [String]$log = (Get-Date -Format $LogDateFormat) + " [ERROR] : " + $Value } } Write-Output $Log | Out-File -FilePath $LogFilePath -Encoding $LogEncoding -append } }
PowerShellCorpus/GithubGist/michaelherndon_eaf19bf88e8388ef757e_raw_96ab043d2716efc346f7b98ac6913a00ba373905_examples.ps1
michaelherndon_eaf19bf88e8388ef757e_raw_96ab043d2716efc346f7b98ac6913a00ba373905_examples.ps1
<# Copyright 2014 Michael Herndon Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> # Backtick or How to escape characters in strings. # -------------------------------------------------- # linebreak, tab echo "`r`n `t " # its worth nothing this can often break syntax editors # that use regular expressions to parse language grammer. echo "`"" # Bound Parameters # --------------------------------------------------- # use bound parameter ./script1.ps1 -Debug # detect and use as boolean flag $debug = $PSCmdlet.MyInvocation.BoundParameters["Debug"].IsPresent; if($debug) { Write-Host "Debuggin' Time!" } # Quick 'Exists' check for file or folders # -------------------------------------------- $file = "c:\opt\info.csv" if(! (Test-Path $file)) { Write-Host "The file does not exist at $path." } # Execute a string value as a command or executable # ---------------------------------------------- $location = "C:\Program Files (x86)\Windows Kits\8.1\bin\x64" $makecert = "$location\makecert.exe"; # special folder 'Desktop' for the current user $desktop = [Environment]::GetFolderPath("Desktop"); $cert = "$desktop\Test.cer"; # use the '&' symbol to invoke a string as a command or executable. &$makecert -r -pe -n CN=Test -ss my -sr localmachine -eku 1.3.6.1.5.5.7.3.2 -len 2048 -e 01/01/2016 $cert
PowerShellCorpus/GithubGist/anderssonjohan_b612f0fe036e75fe76d3_raw_e6d339e5a6805f4046311550fe04387560253bba_generate-createscript.ps1
anderssonjohan_b612f0fe036e75fe76d3_raw_e6d339e5a6805f4046311550fe04387560253bba_generate-createscript.ps1
param( [parameter(mandatory=$false)] $sqlInstance = "(local)", [parameter(mandatory=$false)] $database, [switch] $silent ) $csFilePath = join-path -resolve $PSScriptRoot "Services/RESTService/Service/connectionstrings.config" $CreateTablesSql = join-path -resolve $PSScriptRoot "Setup/SetupSkeleton/DB/Schema/CreateScripts/CreateTables.sql" $CreateSearchTablesSql = join-path -resolve $PSScriptRoot "Setup/SetupSkeleton/DB/Schema/CreateScripts/CreateSearchTables.sql" [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Management.Sdk.Sfc") | out-null function ScriptDatabase( [string] $sqlInstance, [string] $database, [string[]] $excludeSchema, [string[]] $includeSchema ) { $srv = new-object Microsoft.SqlServer.Management.Smo.Server $sqlInstance $db = $srv.Databases[$database] $scrp = new-object Microsoft.SqlServer.Management.Smo.Scripter $srv $scrp.Options.ScriptSchema = $true $scrp.Options.SchemaQualify = $true $scrp.Options.WithDependencies = $true $scrp.Options.Indexes = $true # To include indexes $scrp.Options.FullTextIndexes = $true # To include full text indexes $scrp.Options.DriAllConstraints = $true # to include referential constraints in the script $scrp.Options.DriDefaults = $true $scrp.Options.AnsiPadding = $false $scrp.Options.ScriptBatchTerminator = $true $scrp.Options.ExtendedProperties = $true $scrp.PrefetchObjects = $true # some sources suggest this may speed things up $schemas = @() $urns = @() # Schemas cannot be scripted using the options above without getting an scripting error # We create a new options object here for that $schemaOptions = (new-object Microsoft.SqlServer.Management.Smo.Scripter $srv).Options $schemaOptions.IncludeHeaders = $false $schemaOptions.ScriptOwner = $true $db.Schemas | %{ if (!$_.IsSystemObject -and (($excludeSchema -and $excludeSchema -notcontains $_.Name ) -or ($includeSchema -and $includeSchema -contains $_.Name)) ) { $schemas += $_.Script($schemaOptions) if(!$silent) { Write-Host -nonewline "." } } } $db.Tables + $db.Views + $db.StoredProcedures + $db.UserDefinedFunctions | %{ if (!$_.IsSystemObject -and (($excludeSchema -and $excludeSchema -notcontains $_.Schema ) -or ($includeSchema -and $includeSchema -contains $_.Schema)) ) { $urns += $_.Urn if(!$silent) { Write-Host -nonewline "." } } } $builder = new-object System.Text.StringBuilder $schemas + $scrp.Script($urns) | %{ $builder.AppendLine($_) | out-null $builder.AppendLine("GO") | out-null } return $builder.ToString() } function connectionstring_hash( $connectionString ) { $connectionString.Split(';') | %{ $pair = $_.Split( '=' ) new-object psobject -property @{ "Key" = $pair[0]; "Value" = $pair[1] } } | group -AsHashTable Key } if( !( $sqlInstance -and $database )) { [xml]$config = gc $csFilePath $csmap = connectionstring_hash $config.connectionStrings.add.connectionString $sqlInstance = $csmap["Data Source"].Value $database = $csmap["Initial Catalog"].Value } Write-Host -foregroundcolor yellow "Using SQL server $sqlInstance and database $database" Write-Host "Generating $CreateTablesSql" sc -path $CreateTablesSql -value (ScriptDatabase -sqlInstance $sqlInstance -database $database -excludeSchema "Search" ) Write-Host "" Write-Host "Generating $CreateSearchTablesSql" sc -path $CreateSearchTablesSql -value (ScriptDatabase -sqlInstance $sqlInstance -database $database -includeSchema "Search") Write-Host ""
PowerShellCorpus/GithubGist/kyle-herzog_4053002_raw_2118775f7b633f928c656cd7881feaaf0e2c8092_Expand-Item7Zip.ps1
kyle-herzog_4053002_raw_2118775f7b633f928c656cd7881feaaf0e2c8092_Expand-Item7Zip.ps1
function Expand-Item7zip { param ( [Parameter(Mandatory=$true)] [string] $item, [Parameter(Mandatory=$true)] [string] $destinationDirectory ) if (!(Test-Path -Path $item -PathType Leaf)) { throw ("Specified archive File is invalid: " + $item) } if (!(Test-Path -Path $destinationDirectory -PathType Container)) { New-Item $destinationDirectory -ItemType Directory | Out-Null } if(!(Get-Command "7z" -ErrorAction SilentlyContinue)) { $7zipInstallationDirectory = "C:\Program Files\7-Zip" if(!(Confirm-64BitOS)) { $7zipInstallationDirectory = "C:\Program Files (x86)\7-Zip" } Set-EnvironmentVariable -name "Path" -value $7zipInstallationDirectory -scope "session" -appendValue } #& "7z" l $item $result = (& "7z" x "-o$destinationDirectory" "$item") } function Confirm-64BitOS { (Get-WmiObject -Class Win32_OperatingSystem).OSArchitecture -eq "64-bit" } function Set-EnvironmentVariable { param ( [Parameter(Mandatory=$true)] [string] $name, [Parameter(Mandatory=$true)] [string] $value, [Parameter(Mandatory=$false)] [string] $scope = "process", [switch] $appendValue ) $scope = $scope.ToLower() if(($scope -ne "machine") -and ($scope -ne "user") -and ($scope -ne "process")) { THROW New-Object System.Exception "Scope must be 'machine', 'user', or 'process'" } if($appendValue) { $newValue = (Get-Item "Env:\$name").Value if(!$newValue.Contains($value)) { $newValue += ";$value" } $value = $newValue } Set-Item -Path "Env:$name" -Value "$value" [Environment]::SetEnvironmentVariable("$name", "$value", "$scope") }
PowerShellCorpus/GithubGist/ajkerrigan_5ca7a8bb5460c7789e37_raw_86c5cfd943d3dc32eb4e831b83f19ce7cb7e7ae8_Set-LoLCompatMode.ps1
ajkerrigan_5ca7a8bb5460c7789e37_raw_86c5cfd943d3dc32eb4e831b83f19ce7cb7e7ae8_Set-LoLCompatMode.ps1
function Set-LoLCompatibilityMode { param( $InstallPath = 'C:\Riot Games' ) # This Powershell function automates some settings changes I've seen recommended # for Windows 8.1 users experiencing League of Legends lag spikes on Windows 8.1. # # Warnings: # - This is a quick script intended for my own use only. # - There is no error checking. # - Existing compatibility mode settings for LoL executables will be clobbered without warning. # - This will only be effective on a Windows 8/8.1 machine with League of Legends # installed. # - The function must be executed with elevated privileges because it requires read-write # access to the registry. # Delete existing compatibility mode flags $key = (Get-Item 'HKCU:\software\microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers\'); Write-Output "Deleting League of Legends compatibility mode settings from registry key $($key.name):" $key.GetValueNames() | Where-Object { $_ -match ($InstallPath -replace '\\','\\') } | Foreach-Object { Write-Output "Deleting registry value for '$_'" reg delete $key.name /f /v $_ }; # Set the Windows 7 compatibility mode flag Get-ChildItem -Recurse -Include *.exe $InstallPath | Foreach-Object { Write-Output "Enabling compatibility mode for '$($_.FullName)'" reg add "HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" /f /v $_.FullName /d '~ WIN7RTM' } }
PowerShellCorpus/GithubGist/ofonesandzeros_e2fe42d89a0a68c32b56_raw_4c32442f96b3182600eb6e249aecf2cacf09411c_Get-Fab40.ps1
ofonesandzeros_e2fe42d89a0a68c32b56_raw_4c32442f96b3182600eb6e249aecf2cacf09411c_Get-Fab40.ps1
<# .SYNOPSIS Get-Fab40 .DESCRIPTION Get a list of the webs and the templates from which they were built within a specified web application. I wrote this script to determine which sites were based on the "Fabulous 40" site templates for SharePoint 2007 after upgrading my client to SharePoint 2010. .EXAMPLE Get-SPSiteTemplates .INPUTS .OUTPUTS For each SPWeb within an SPWebApplication, lists the ParentWeb, Title, and WebTemplate properties. .NOTES This script was written by Eric Skaggs and modified by Bryan Napier to filter only Fab 40 webs. .LINK http://www.twitter.com/skaggej http://www.sharepointnerd.com #> Param( [string]$Web = "$(Read-Host 'Enter the root URL of a web application')" ) begin { } process { try { $PSSnapinSP = Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue if ($PSSnapinSP -eq $Null) { Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop } $webApplication = Get-SPWebApplication $Web $siteCollection = $webApplication | Get-SPSite -Limit ALL $allWebs = $siteCollection | Get-SPWeb -Limit ALL $allWebs | ?{$_.WebTemplateId -gt 75000} | Select-Object ParentWeb, Url, Title, WebTemplate, WebTemplateId | Sort WebTemplateId, ParentWeb, Title | Format-Table } catch [Exception] { Write-Error $Error[0] $err = $_.Exception while ( $err.InnerException ) { $err = $err.InnerException Write-Output $err.Message } } }
PowerShellCorpus/GithubGist/devlead_9146bf4aec78c7b1114e_raw_e94d4da7bb8d4470c1a493573608b505209ee3cb_PostMessage.ps1
devlead_9146bf4aec78c7b1114e_raw_e94d4da7bb8d4470c1a493573608b505209ee3cb_PostMessage.ps1
$postSlackMessage = @{token="*topsecret*";channel="#general";text="Hello from PowerShell!";username="PowerShell";icon_url="https://pbs.twimg.com/profile_images/1604347359/logo_512x512_normal.png"} Invoke-RestMethod -Uri https://slack.com/api/chat.postMessage -Body $postSlackMessage
PowerShellCorpus/GithubGist/codingoutloud_4253147_raw_528b7ded8150625c85044d04332b8842344ae5b5_temp-tidy.ps1
codingoutloud_4253147_raw_528b7ded8150625c85044d04332b8842344ae5b5_temp-tidy.ps1
# The intent is that the command is to be scheduled to be run by the Windows Scheduler once a day: http://stackoverflow.com/a/8888886 # For Windows Azure, a new Windows Scheduler task is best added by a Startup Script and, like any other machine with the default PowerShell security settings, will need the PowerShell ExecutionPolicy configured: http://blogs.msdn.com/b/jimoneil/archive/2011/02/07/azure-startup-tasks-and-powershell-lessons-learned.aspx # Bill Wilder @codingoutloud # See also http://blog.codingoutloud.com/2012/12/10/tidy-the-temp-folder-on-windows-azure get-childitem $TEMP -recurse | where {$_.lastwritetime -lt (get-date).adddays(-7)} |% {remove-item $_.fullname -force -recurse -verbose}
PowerShellCorpus/GithubGist/heaths_8722508_raw_acb91a8c28c90576dca28589d31b57684501d93c_Move-WixPackageCache.ps1
heaths_8722508_raw_acb91a8c28c90576dca28589d31b57684501d93c_Move-WixPackageCache.ps1
<# This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. #> #Requires -Version 3.0 [CmdletBinding()] param ( [Parameter(Position=0, Mandatory=$true)] [string] $Path, [Parameter()] [ValidateRange(0, 2TB)] [long] $Size = 1TB ) # Require elevated privileges (Tip: PSv4 supports '#Requires -RunAsAdministrator'). $Principal = New-Object System.Security.Principal.WindowsPrincipal ([System.Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Error 'Elevated privileges are required to move the package cache.' -Category PermissionDenied return } # Make sure modules are loaded (Tip: PSv3 supports '#Requires -Modules <String[]>'). Import-Module 'Dism', 'Storage', 'ScheduledTasks' $VhdPath = Join-Path $Path 'Cache.vhd' $CachePath = Join-Path $env:ProgramData 'Package Cache' # Make sure the necessary Windows features are enabled. $Features = 'Microsoft-Hyper-V-All', 'Microsoft-Hyper-V-Tools-All', 'Microsoft-Hyper-V-Management-PowerShell' | ForEach-Object { Get-WindowsOptionalFeature -Online -FeatureName $_ -Verbose:$false } | Where-Object { $_.State -ne 'Enabled' } | Select-Object -expand FeatureName if ($Features) { Write-Verbose "Installing required Windows feature(s): $($Features -split ', ')" Enable-WindowsOptionalFeature -Online -FeatureName $Features -NoRestart -Verbose:$false if (-not $?) { return } } # Create, partition, and format the cache VHD. if (-not (Test-Path $Path -PathType Container)) { Write-Verbose "Creating directory for virtual disk: $Path" $null = New-Item $Path -Type 'Directory' } elseif (Test-Path "$VhdPath" -PathType Leaf) { Write-Error "A virtual disk already exists at `"$VhdPath`"." -Category ResourceExists return } Write-Verbose "Creating virtual disk: $VhdPath" $Disk = New-VHD "$VhdPath" -SizeBytes $Size -Dynamic | Mount-VHD -NoDriveLetter -Passthru if (-not $?) { return } $Acl = New-Object System.Security.AccessControl.FileSecurity $Acl.SetSecurityDescriptorSddlForm('O:BAG:DUD:P(A;;FA;;;BA)(A;;FA;;;SY)(A;;FRFX;;;BU)(A;;FRFX;;;WD)', 'All') $Acl | Set-Acl $Disk.Path $Partition = Initialize-Disk $Disk.Number -PassThru | New-Partition -UseMaximumSize $null = $Partition | Format-Volume -FileSystem NTFS -NewFileSystemLabel 'Package Cache' -Confirm:$false $Volume = $Partition | Add-PartitionAccessPath -AssignDriveLetter -PassThru | Get-Volume $Drive = "$($Volume.DriveLetter):" $Acl = New-Object System.Security.AccessControl.DirectorySecurity $Acl.SetSecurityDescriptorSddlForm('O:BAG:DUD:PAI(A;OICIID;FA;;;BA)(A;OICIID;FA;;;SY)(A;OICIID;FRFX;;;BU)(A;OICIID;FRFX;;;WD)', 'All') Set-Acl "$Drive\" -AclObject $Acl Write-Verbose "Created and formatted drive: $Drive, label: Package Cache" # Copy the existing package cache (if any). if (Test-Path "$CachePath" -PathType Container) { Write-Verbose "Copying contents from: $CachePath; to: $Drive" Copy-Item "$CachePath\*" "$Drive\" -Recurse if (-not $?) { return } Write-Verbose "Deleting directory: $CachePath" Remove-Item "$CachePath" -Force -Recurse if (-not $?) { return } } # Create the empty directory and mount the VHD into it. Write-Verbose "Creating empty directory: $CachePath" New-Item "$CachePath" -Type 'Directory' -Force | Set-Acl -AclObject $Acl if (-not $?) { return } Write-Verbose "Mounting virtual disk into directory: $CachePath" $Partition | Add-PartitionAccessPath -AccessPath "$CachePath" -PassThru | Remove-PartitionAccessPath -AccessPath "$Drive" Write-Verbose "Removed drive letter: $Drive" # Schedule a task to make sure the VHD is always mounted on boot. Write-Verbose "Creating script to mount VHD: $VhdPath, path: $ScriptPath" $ScriptPath = [System.IO.Path]::ChangeExtension($VhdPath, '.txt') @" select vdisk file=$VhdPath attach vdisk "@ | Set-Content $ScriptPath -Force Get-Acl $VhdPath | Set-Acl $ScriptPath Write-Verbose "Scheduling task to mount VHD: $VhdPath" $trigger = New-ScheduledTaskTrigger -AtStartup $action = New-ScheduledTaskAction -Execute (get-command diskpart.exe).Path -Argument "/s `"$ScriptPath`"" $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries $user = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -RunLevel Highest -LogonType ServiceAccount $null = Register-ScheduledTask -TaskName 'Attach Package Cache' -Trigger $trigger -Action $action -Settings $settings -Principal $user -Force <# .Synopsis Move the Burn package cache to another drive or directory. .Description Actually moving the Burn package cache to another drive or directory is currently not supported. Instead this script creates a expandable virtual disk (VHD) in whatever directory you want - even on another drive. Any existing payload is copied and the expandable virtual disk is mounted into the now empty package cache. .Parameter Path The directory in which the package cache is moved. .Parameter Size The maximum size of the expandable virtual disk to create. The default is 1TB. .Notes You need administrator privileges to run this script. .Link http://aka.ms/mvcache #>
PowerShellCorpus/GithubGist/jongalloway_1402840_raw_7eda51c29f41522ab575e89436bc325a7c4a48da_GetLocalNuget.ps1
jongalloway_1402840_raw_7eda51c29f41522ab575e89436bc325a7c4a48da_GetLocalNuget.ps1
# --- settings --- $feedUrlBase = "http://go.microsoft.com/fwlink/?LinkID=206669" # the rest will be params when converting to funclet $latest = $true $overwrite = $false $top = 500 #use $top = $null to grab all $destinationDirectory = join-path ([Environment]::GetFolderPath("MyDocuments")) "NuGetLocal" # --- locals --- $webClient = New-Object System.Net.WebClient # --- functions --- # download entries on a page, recursively called for page continuations function DownloadEntries { param ([string]$feedUrl) $feed = [xml]$webClient.DownloadString($feedUrl) $entries = $feed.feed.entry $progress = 0 foreach ($entry in $entries) { $url = $entry.content.src $fileName = $entry.properties.id + "." + $entry.properties.version + ".nupkg" $saveFileName = join-path $destinationDirectory $fileName $pagepercent = ((++$progress)/$entries.Length*100) if ((-not $overwrite) -and (Test-Path -path $saveFileName)) { write-progress -activity "$fileName already downloaded" ` -status "$pagepercent% of current page complete" ` -percentcomplete $pagepercent continue } write-progress -activity "Downloading $fileName" ` -status "$pagepercent% of current page complete" ` -percentcomplete $pagepercent [int]$trials = 0 do { try { $trials +=1 $webClient.DownloadFile($url, $saveFileName) break } catch [System.Net.WebException] { write-host "Problem downloading $url `tTrial $trials ` `n`tException: " $_.Exception.Message } } while ($trials -lt 3) } $link = $feed.feed.link | where { $_.rel.startsWith("next") } | select href if ($link -ne $null) { # if using a paged url with a $skiptoken like # http:// ... /Packages?$skiptoken='EnyimMemcached-log4net','2.7' # remember that you need to escape the $ in powershell with ` return $link.href } return $null } # the NuGet feed uses a fwlink which redirects # using this to follow the redirect function GetPackageUrl { param ([string]$feedUrlBase) $resp = [xml]$webClient.DownloadString($feedUrlBase) return $resp.service.GetAttribute("xml:base") } # --- do the actual work --- # if dest dir doesn't exist, create it if (!(Test-Path -path $destinationDirectory)) { New-Item $destinationDirectory -type directory } # set up feed URL $serviceBase = GetPackageUrl($feedUrlBase) $feedUrl = $serviceBase + "Packages" if($latest) { $feedUrl = $feedUrl + "?`$filter=IsLatestVersion eq true" if($top -ne $null) { $feedUrl = $feedUrl + "&`$orderby=DownloadCount desc&`$top=$top" } } while($feedUrl -ne $null) { $feedUrl = DownloadEntries $feedUrl }
PowerShellCorpus/GithubGist/mbrownnycnyc_48a88ac982e9e09ff2c9_raw_2249c30bea59143ae05b95aa6ae710fcc92c027d_get-aduserbysid.ps1
mbrownnycnyc_48a88ac982e9e09ff2c9_raw_2249c30bea59143ae05b95aa6ae710fcc92c027d_get-aduserbysid.ps1
function get-aduserbysid{ #http://community.spiceworks.com/how_to/show/2776-powershell-sid-to-user-and-user-to-sid param( [string]$domain, [string]$sid ) $objSID = New-Object System.Security.Principal.SecurityIdentifier ` ("$sid") $objUser = $objSID.Translate( [System.Security.Principal.NTAccount]) $objUser.Value }
PowerShellCorpus/GithubGist/uncas_1988101_raw_0c57051419aa7bc6f4203368621a6451c96eb1c6_NuGetCopy.ps1
uncas_1988101_raw_0c57051419aa7bc6f4203368621a6451c96eb1c6_NuGetCopy.ps1
# Input: $inputFolder = "D:\Projects" $destinationFolder = "D:\LocalNuGetFeed\" if (!(Test-Path $destinationFolder)) { mkdir $destinationFolder } $files = gci $inputFolder -recurse $packages = $files | where {$_.extension -eq ".nupkg"} foreach ($package in $packages) { $packageName = $package.Name $destinationFileName = $destinationFolder + $packageName $packageSize = [math]::round($package.Length / 1KB) if (!(Test-Path $destinationFileName)) { "Copies NuGet package $packageName ($packageSize KB)." copy $package.FullName $destinationFileName } }
PowerShellCorpus/GithubGist/jonforums_5095788_raw_3e6b6a826a7645baa83a30d7a2e1bb141750d28b_build_zlib.ps1
jonforums_5095788_raw_3e6b6a826a7645baa83a30d7a2e1bb141750d28b_build_zlib.ps1
#requires -version 2.0 # Author: Jon Maken # License: 3-clause BSD # Revision: 2013-03-11 01:39:59 -0600 # # TODO: # - extract generics into a downloadable utils helper module # - add proper try-catch-finally error handling # - support x86 and x64 builds param( [parameter(Mandatory=$true, Position=0, HelpMessage='zlib version to build (eg - 1.2.7)')] [alias('v')] [validateset('1.2.7')] [string] $version, [parameter(HelpMessage='Path to 7-Zip command line tool')] [string] $7ZA = 'C:/tools/7za.exe', [parameter(HelpMessage='Path to DevKit root directory')] [string] $DEVKIT = 'C:/Devkit' ) $msg_color = 'Yellow' $root = Split-Path -parent $script:MyInvocation.MyCommand.Path $libname = 'zlib' $source = "${libname}-${version}.tar.gz" $source_dir = "${libname}-${version}" $repo_root = 'http://zlib.net/' $archive = "${repo_root}${source}" $hash_uri = "https://raw.github.com/jonforums/poshlab/master/hashery/${libname}.md5" # download and verify # TODO implement progress bar when extracted to util helper module if(-not (Test-Path $source)) { Import-Module BitsTransfer Write-Host "[INFO] downloading $archive" -foregroundcolor $msg_color Start-BitsTransfer $archive "$PWD\$source" } # download hash data and validate downloaded source archive Write-Host "[INFO] validating $source" -foregroundcolor $msg_color $client = New-Object System.Net.WebClient $hash = ConvertFrom-StringData $client.DownloadString($hash_uri) try { $hasher = New-Object System.Security.Cryptography.MD5Cng $fs = New-Object System.IO.FileStream "$PWD\$source", 'Open', 'Read' $test_hash = [BitConverter]::ToString($hasher.ComputeHash($fs)).Replace('-','').ToLower() } finally { $fs.Close() } if ($test_hash -ne $hash[$version].ToLower()) { Write-Host "[ERROR] $source validation failed, exiting" -foregroundcolor red break } # extract Write-Host "[INFO] extracting $source" -foregroundcolor $msg_color $tar_file = "$($source.Substring(0, $source.LastIndexOf('-')))*.tar" (& "$7ZA" "x" $source) -and (& "$7ZA" "x" $tar_file) -and (rm $tar_file) | Out-Null # patch, configure, build, archive Push-Location "${source_dir}" # activate toolchain Write-Host "[INFO] activating toolchain" -foregroundcolor $msg_color . "$DEVKIT/devkitvars.ps1" | Out-Null # configure Write-Host "[INFO] configuring ${source_dir}" -foregroundcolor $msg_color $install_dir = "$($PWD.ToString().Replace('\','/'))/my_install" # build Write-Host "[INFO] building ${source_dir}" -foregroundcolor $msg_color sh -c "make -f win32/Makefile.gcc" | Out-Null # install $install_opts = @("BINARY_PATH=${install_dir}/bin", "INCLUDE_PATH=${install_dir}/include", "LIBRARY_PATH=${install_dir}/lib", "SHARED_MODE=1") sh -c "make install -f win32/Makefile.gcc $(${install_opts} -join ' ')" | Out-Null # archive Push-Location "$install_dir" Write-Host "[INFO] creating binary archive for ${source_dir}" -foregroundcolor $msg_color $bin_archive = "${source_dir}-x86-windows-bin.7z" & "$7ZA" "a" "-mx=9" "-r" $bin_archive "*" | Out-Null Pop-Location Pop-Location # hoist binary archive and cleanup Write-Host "[INFO] cleaning up" -foregroundcolor $msg_color mv "$install_dir\$bin_archive" "$PWD" rm -recurse -force "${source_dir}"
PowerShellCorpus/GithubGist/rposbo_8d55b8f76572145a8889_raw_34255d96e8ad22e2b9dbbb3e283a6f0e4602b69d_delete%20unreferenced%20images.ps1
rposbo_8d55b8f76572145a8889_raw_34255d96e8ad22e2b9dbbb3e283a6f0e4602b69d_delete%20unreferenced%20images.ps1
# cd to your project directory cd "d:\my luverly project\" # get all the images $images = Get-ChildItem "d:\my luverly project\img\" -Exclude "*.config" # for each image.. foreach($img in $images){ $found = "" # look in css, js, cshtml files for a match foreach($file in Get-ChildItem -Include "*.css", "*.js","*.cshtml" -Recurse){ # got a match! if (Select-String -pattern $img.Name -SimpleMatch -Quiet -Path $file.FullName){ $found = $img.Name } } # no match? delete the image if ($found -ne $img.Name){ Remove-Item $img.FullName } }
PowerShellCorpus/GithubGist/sheeeng_7155184_raw_4e5f63b360b758c90abad516b210bf8da7204856_EnableScript.ps1
sheeeng_7155184_raw_4e5f63b360b758c90abad516b210bf8da7204856_EnableScript.ps1
Set-ExecutionPolicy Unrestricted -scope CurrentUser
PowerShellCorpus/GithubGist/sveinn-steinarsson_f8d21f1832800bd4428a_raw_db6a5571669f694b81b9b3d70ef2c6dd17dd10b2_powerssh.ps1
sveinn-steinarsson_f8d21f1832800bd4428a_raw_db6a5571669f694b81b9b3d70ef2c6dd17dd10b2_powerssh.ps1
# Script Name: powerssh # Version: 1.1.0 (9. July, 2014) # Author: Sveinn Steinarsson # Description: Use Powershell to connect to a remote server via SSH and run a shell script/command # Prerequisite: # plink.exe in script path (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) # Examples: # With key file (*.ppk) and script file # .\powerssh.ps1 -server hostname -login username -key keyfile.ppk -script task.sh # With key file and command # .\powerssh.ps1 -server hostname -login username -key keyfile.ppk -cmd "ls; pwd" Param ( [string]$server = $(Throw "Please provide a server hostname/ip"), [string]$login = $(Throw "Please provide a login username"), [string]$key, [string]$pw, [string]$script, [string]$cmd, [switch]$batch = $false, [switch]$agentForwarding = $true, [switch]$verbose = $false, [switch]$acceptHostKey = $true # For convenient. Make sure the server is the computer you think it is. ) $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path $plinkPath = Join-Path -Path $scriptPath -Childpath "Plink.exe" if (-not (Test-Path $plinkPath)){ Throw "Missing Plink.exe in script path. Please download it from http://the.earth.li/~sgtatham/putty/latest/x86/plink.exe" } if ($key -eq "" -and $pw -eq "") { Throw "You must supply either a password or key file." } if ($script -eq "" -and $cmd -eq "") { Throw "You must supply either a shell script file or command." } if ($key -ne "" -and $pw -ne "") { Write-Output "Notice: Only password or key file is required. Using key file." } if ($script -ne "" -and $cmd -ne "") { Write-Output "Notice: Only script file or command is required. Using script file." } if ($acceptHostKey -eq $true) { $command = "echo Y|" + $plinkPath } else { $command = $plinkPath } $command += " -ssh " + $server + " -l " + $login if ($key -ne "") { $command += " -i " + $key } else { $command += " -pw " + $pw } if ($batch -eq $true) { $command += " -batch" } if ($agentForwarding -eq $true) { $command += " -a" } if ($verbose -eq $true) { $command += " -v" } if ($script -ne "") { $command += " -m " + $script } else { $command += ' "' + $cmd + '"' } $command += " 2>&1" if ($verbose -eq $true) { Write-Output "Command to Plink:" Write-Output $command # Write out the command for debugging Write-Output "" } $output = Invoke-Expression $command if ($LastExitCode -ne 0) { Throw $output } else { Write-Output $output Exit 0 }
PowerShellCorpus/GithubGist/tobynet_11127306_raw_f5aadc35f344477607436fa456c30be6887d9df6_saveAsPdf.ps1
tobynet_11127306_raw_f5aadc35f344477607436fa456c30be6887d9df6_saveAsPdf.ps1
function saveAsPdf($filename) { echo ("Converting {0}" -f $filename) $excel = New-Object -ComObject Excel.Application -Property @{visible=$false} try { $excel.AlertBeforeOverwriting = $true $workbook = $excel.Workbooks.Open($filename) $workbook.ExportAsFixedFormat( [Microsoft.Office.Interop.Excel.XlFixedFormatType]::xlTypePDF , [Io.Path]::ChangeExtension($filename, '.pdf') , [Microsoft.Office.Interop.Excel.XlFixedFormatQuality]::xlQualityStandard ) } finally { $excel.Quit() } } echo $("Begin to convert {0} files to PDF" -f $args.Length) $args | %{ saveAsPdf -filename $_ } echo "DONE"
PowerShellCorpus/GithubGist/alwalker_3063656_raw_bf7bf59ece92f87136d6341dadfcd5fdb1671ab4_FlacMp3.ps1
alwalker_3063656_raw_bf7bf59ece92f87136d6341dadfcd5fdb1671ab4_FlacMp3.ps1
$files = get-childitem F:\Work_Area\Music\Raw *.flac -rec foreach ($file in $files) { $artist = metaflac $file.fullname --show-tag=ARTIST $artist = $artist.split("=")[1] $title = metaflac $file.fullname --show-tag=TITLE $title = $title.split("=")[1] $album = metaflac $file.fullname --show-tag=ALBUM $album = $album.split("=")[1] $genre = metaflac $file.fullname --show-tag=GENRE $genre = $genre.split("=")[1] $tracknumber = metaflac $file.fullname --show-tag=TRACKNUMBER $tracknumber = $tracknumber.split("=")[1] $date = metaflac $file.fullname --show-tag=DATE $date = $date.split("=")[1] if(!(Test-Path "F:\Work_Area\Music\sd\$artist\$album")) { New-Item "F:\Work_Area\Music\sd\$artist\$album" -type directory } $mp3 = "F:\Work_Area\Music\sd\$artist\$album\" + $file.tostring().Replace(".flac", ".mp3") $wav = $file.fullname.Replace(".flac", ".wav") flac -d $file.Fullname metaflac $file.Fullname --export-picture-to=cover.jpg lame -V2 --add-id3v2 --pad-id3v2 --ignore-tag-errors --nohist --ty $date --tt $title --ta $artist --tl $album --tn $tracknumber --tg $genre --ti cover.jpg $wav $mp3 Remove-Item $wav Remove-Item cover.jpg }
PowerShellCorpus/GithubGist/RichardSlater_5460609_raw_94028663b18f30b6e72701642cd57c5c3353ff4d_Set-AzureMinimumInstanceCount.ps1
RichardSlater_5460609_raw_94028663b18f30b6e72701642cd57c5c3353ff4d_Set-AzureMinimumInstanceCount.ps1
$deployments = Get-AzureService | Select-Object ServiceName | Get-AzureDeployment $instances = $deployments | Select-Object ServiceName,Slot -ExpandProperty RoleInstanceList $instances | Select-Object ServiceName,Slot,RoleName | Group-Object RoleName,ServiceName,Slot -NoElement | Where-Object {$_.Count -gt 1} | Select-Object Count,@{Name="RoleName"; Expression={$_.Name.Split(',')[0].Trim()}},@{Name="ServiceName";Expression={$_.Name.Split(',')[1].Trim()}},@{Name="Slot";Expression={$_.Name.Split(',')[2].Trim()}} | Set-AzureRole -Count 1
PowerShellCorpus/GithubGist/atifaziz_5356241_raw_b2bca98dac9a585dc6d1aebfb023ebfe71e6ac84_ConvertTo-SqlValues.ps1
atifaziz_5356241_raw_b2bca98dac9a585dc6d1aebfb023ebfe71e6ac84_ConvertTo-SqlValues.ps1
function ConvertTo-SqlValues { [CmdletBinding()] param ( [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [object]$InputObject, [string]$TableName = 'Data', [Parameter(Position = 0)] [string[]]$Property, [switch]$DontForceDateTimeOffset ) BEGIN { function SqlIdent([string]$s) { "[$($s -replace ']', ']]')]" } $initialized = $false; $i = -1 $sqlTableName = SqlIdent($tableName) } PROCESS { $i++ if (!$initialized) { $initialized = $true $names = if (!$property) { $aliasProperty = [Management.Automation.PSMemberTypes]'AliasProperty' $inputObject | Get-Member -MemberType Properties | ? { $_.MemberType -ne $aliaProperty } | Select -Expand Name } else { $property } if ($names) { $columns = ($names | % { SqlIdent($_) }) -join ', ' "SELECT $columns FROM (VALUES" } else { Write-Warning 'No properties found in input object.' } } $literals = $names | % { $v = $inputObject.$_ switch ($(if ($v -ne $null) { $v.GetType() } else { [Void] })) { { [string], [char] -contains $_ } { "N'" + ($v -replace "'", "''") + "'" } { [int], [long], [single], [double], [decimal] -contains $_ } { [string]$v } { $_ -eq [bool] } { [int]$v } { $_ -eq [datetime] } { if ($DontForceDateTimeOffset) { "CONVERT(datetime, '{0:yyyy-MM-dd HH:mm:ss.fff}', 121)" -f $v } else { "CAST('{0:o}' AS datetimeoffset)" -f $v } } { $_ -eq [guid] } { "CAST('$(([string]$v).ToUpperInvariant())' AS uniqueidentifier)" } default { 'NULL' } } } if ($names) { " $(if ($i -gt 0) { ',' } else { ' ' }) ($($literals -join ', '))" } } END { if ($initialized -and $names) { ") $sqlTableName($columns)" } } }
PowerShellCorpus/GithubGist/Kr3m_7165247_raw_4588dae8f3bb5cd6da6b19d756dbcf48ebdf0882_hosts.ps1
Kr3m_7165247_raw_4588dae8f3bb5cd6da6b19d756dbcf48ebdf0882_hosts.ps1
# # Powershell script for adding/removing/showing entries to the hosts file. # # Known limitations: # - does not handle entries with comments afterwards ("<ip> <host> # comment") # $file = "C:\Windows\System32\drivers\etc\hosts" function add-host([string]$filename, [string]$ip, [string]$hostname) { remove-host $filename $hostname $ip + "`t`t" + $hostname | Out-File -encoding ASCII -append $filename } function remove-host([string]$filename, [string]$hostname) { $c = Get-Content $filename $newLines = @() foreach ($line in $c) { $bits = [regex]::Split($line, "\t+") if ($bits.count -eq 2) { if ($bits[1] -ne $hostname) { $newLines += $line } } else { $newLines += $line } } # Write file Clear-Content $filename foreach ($line in $newLines) { $line | Out-File -encoding ASCII -append $filename } } function print-hosts([string]$filename) { $c = Get-Content $filename foreach ($line in $c) { $bits = [regex]::Split($line, "\t+") if ($bits.count -eq 2) { Write-Host $bits[0] `t`t $bits[1] } } } try { if ($args[0] -eq "add") { if ($args.count -lt 3) { throw "Not enough arguments for add." } else { add-host $file $args[1] $args[2] } } elseif ($args[0] -eq "remove") { if ($args.count -lt 2) { throw "Not enough arguments for remove." } else { remove-host $file $args[1] } } elseif ($args[0] -eq "show") { print-hosts $file } else { throw "Invalid operation '" + $args[0] + "' - must be one of 'add', 'remove', 'show'." } } catch { Write-Host $error[0] Write-Host "`nUsage: hosts add <ip> <hostname>`n hosts remove <hostname>`n hosts show" }
PowerShellCorpus/GithubGist/GuruAnt_7213597_raw_0ea672f7dcd2b7fc4d1518d3457d3f3d22bb2d9c_FindVMTemplatesWithNonPersistentDisks.ps1
GuruAnt_7213597_raw_0ea672f7dcd2b7fc4d1518d3457d3f3d22bb2d9c_FindVMTemplatesWithNonPersistentDisks.ps1
# Set up an empty array $arrTemplatesWithPersistentDrives = @() # Get all the template objects $objTemplates = Get-Template # Loop through each template ForEach ($objTemplate in $objTemplates){ # Get the drives associated with that template $objHardDisks = $objTemplate | Get-HardDisk # Loop through each drive ForEach ($objHardDisk in $objHardDisks){ # If any of the drives are non-persistent, add the template object to the empty array If ($objHardDisk.Persistence -match "non"){ $arrTemplatesWithPersistentDrives += $objTemplate } } } # List the names of the unique templates in the array (as a template with more than one non-perisistent drive would appear more than once) $arrTemplatesWithPersistentDrives | Sort-Object -Unique | Select-Object Name
PowerShellCorpus/GithubGist/varemenos_6315711_raw_2f7db3acac1d65ecd7a74610b3f8b4f8911f9a73_Microsoft.PowerShell_profile.ps1
varemenos_6315711_raw_2f7db3acac1d65ecd7a74610b3f8b4f8911f9a73_Microsoft.PowerShell_profile.ps1
# Clear screen cls # Get user $USER = $PWD.toString() $USER = $USER.Remove(0, 9) # Get hostname $HOSTNAME = HOSTNAME.exe # Signs $COLON = ":" $DOLLAR = "$" function prompt { "$USER@$HOSTNAME$COLON $pwd $DOLLAR" }
PowerShellCorpus/GithubGist/mbrownnycnyc_3cd777471d768858b8ee_raw_725774d5e8200972218b4f641ce296c8edba66b6_check-filepresence.ps1
mbrownnycnyc_3cd777471d768858b8ee_raw_725774d5e8200972218b4f641ce296c8edba66b6_check-filepresence.ps1
#this script is to check for the presence of files #this will populate a variable with the specified format of today's date (see format specifier http://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx) $yyyy = $(Get-Date -format yyyy) # "2014" $mmmm = $(Get-Date -format MMMM) # "September" $mm = $(Get-Date -format MM) # "09" $dd = $(Get-Date -format dd) # "22" #if today is Friday if ($(get-date -format dddd) -eq "Friday") { $FilesToCheck = ` #for file-*, we will be checking yesterday's file "\\filey\file-$(get-date -date $((get-date).adddays(-1)) -format MMddyyyy).txt",` #for the rest, we will be checking today's file "\\filey\file1-mmddyyyy.txt" } #if today is monday elseif ($(get-date -format dddd) -eq "Monday") { $FilesToCheck = ` "\\filey\file.txt",` #for file1-*, we will be checking Saturday's file "file1-$(get-date -date $((get-date).adddays(-2)) -format MM-dd-yyyy).txt" } #if today is Tuesday, wednesday, or Thursday else { $FilesToCheck = ` "\\filey\file.txt",` "\\filey\file1.txt" } #create the presenceinfo object # http://poshcode.com/paste/555/ $presenceinfo = @() #check if the files exist foreach ( $file in $FilesToCheck ) { #if file exists: try { $objfile = get-item $file $tempobj = New-Object PSObject -Property @{ Filename = $objfile.name Presence = test-path $objfile } } catch { $tempobj = New-Object PSObject -Property @{ Filename = $file.substring($file.LastIndexOf('\')+1,$file.length-$file.LastIndexOf('\')-1) Presence = $false } } $presenceinfo += $tempobj } #http://thesurlyadmin.com/2013/01/21/how-to-create-html-reports/ $Header = @" <style> TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;} TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;} TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;} .odd { background-color:#ffffff; } .even { background-color:#dddddd; } </style> <title></title> "@ send-mailmessage -smtpserver $smtpserver -to $recipient -from $sender -subject "file presence report" -bodyashtml -body ( $presenceinfo | select filename,presence | convertto-html -Head $Header | out-string )
PowerShellCorpus/GithubGist/alanrenouf_4949574fe5977026e9fe_raw_90cd576d74324feae0a611ac1b803b31e62967c5_SnapshotCountEmail.ps1
alanrenouf_4949574fe5977026e9fe_raw_90cd576d74324feae0a611ac1b803b31e62967c5_SnapshotCountEmail.ps1
$NumberOfSnapshotsToReport = 5 $EmailFrom = "me@mymail.com" $EmailTo = "you@yourmail.com" # Add multiple with "mail1", "mail2", "Mail3" $Subject = "VMs with $NumberOfSnapshotsToReport or more snapshots" $SMTPServer = "smtp.mymailserver.com" Connect-VIServer 172.16.88.200 -User administrator@vsphere.local -Password VMware1! Foreach ($VM in Get-VM) { $Snapshots = $VM | Get-Snapshot if ($Snapshots.count -ge $NumberOfSnapshotsToReport) { $Info = $Snapshots | Select -last 1 | Select VM, Name, Created, Description $Body += "$VM has $($Snapshots.Count) Snapshots, the last one was created on $($Info.Created) and was named $($Info.Name).`n`n" } } Send-MailMessage -SmtpServer $SMTPServer -From $EmailFrom -To $EmailTo -Subject $Subject -Body $Body
PowerShellCorpus/GithubGist/iainbryson_5ba37c6186fef035b403_raw_fa27329ef3f7492efff8f3866e13b1cb6eefff53_MailWebPage.ps1
iainbryson_5ba37c6186fef035b403_raw_fa27329ef3f7492efff8f3866e13b1cb6eefff53_MailWebPage.ps1
#requires -Version 3 param( [string]$url = "www.example.com", [string]$subject, [string]$fromMail = "sending_account@example.com" [string[]]$toMail = ("receiving_account@example.com") [switch]$dontSend = $false ) function execRemoteScript () { param( [Object]$browser, [string]$url ) $document = $browser.document $head = @($document.getElementsByTagName("head"))[0] Write-Host "got head $url" $script = $document.createElement('script') $script.type = 'text/javascript' $script.src = $url $head.appendChild($script) | Out-Null } if (-not $subject) { $subject = $url; } $ie = new-object -com "InternetExplorer.Application" $ie.visible = $true $ie.navigate2($url) # Wait for the page to start rendering Start-Sleep -MilliSeconds 5000 $doc = $ie.Document $win = $doc.parentWindow if (-not $doc) { Write-Error "Browser document is null"; exit(0); } if (-not $win) { Write-Error "Browser parent window is null"; exit(0); } # Wait for the page to complete rendering while ($ie.Busy -or $ie.Document.readyState -ne "complete") { Start-Sleep -MilliSeconds 100 Write-Host $ie.Document.readyState } Write-Host "ReadyState: $($ie.Document.readyState)" # Add the CSS links in the head. $bodyHtml = "<!DOCTYPE html><html><head>"; foreach ($ss in $doc.styleSheets) { $href = $($ss | Select-Object -expandProperty href); Write-Output "Processing stylesheet $href"; $bodyHtml += "<link rel='stylesheet' type='text/css' href='$($href)' />" } # Load canvg execRemoteScript -browser $ie -url "http://canvg.googlecode.com/svn/trunk/rgbcolor.js" execRemoteScript -browser $ie -url "http://canvg.googlecode.com/svn/trunk/canvg.js" $now = [DateTime]::Now $utcNow = [DateTime]::UtcNow Start-Sleep -MilliSeconds 15000 #`$('body').append('<div style=""font-family: 'Segoe UI Web Semilight', 'Segoe UI', 'Open Sans Light', 'Helvetica Light', 'Arial', sans-serif; ""> generated $($now) $($utcNow) (UTC) &mdash; </p><a href=""$($surl)"">link</a> to site</div>'); $scriptCode = " `$('body').append('<div style=""font-size:10px;""> <p>report generated $($now) ($($utcNow) UTC) &mdash; <a href=""$($surl)"">link</a> to site</p></div>'); `$('body').append('<div style=""font-size:8px;font-family:consolas, sans-serif;color:darkgreen;""><h3>DEBUG</h3><pre id=""debug""/></div>'); function dbg(a) { `$('#debug').text(`$('#debug').text() + '\n' + a); }; // Add a background `$('svg').each(function () { d3.select(this).insert('rect', ':first-child').attr('width', '100%').attr('height', '100%').attr('fill', '#f0f0f0').attr('opacity','1.0').attr('z-order','-1000'); } ) // canvg doesn't seem to apply CSS styles to SVG elements, so we hack this by explicitly setting the attributes. `$('svg').each(function () { d3.select(this).selectAll('.axis path, .axis line').attr('class', '').attr('stroke', 'black').attr('fill', 'none').attr('style', 'shape-rendering:crispEdges'); } ) canvg(); var id = 0; `$('svg').each(function(d) { var svg_element = `$(this).parent(); var canvas_element = (svg_element.parent().append('<canvas id=""canvas'+id+'""></canvas>'))[1]; dbg('rendering svg to image: '+svg_element.context.parentNode.id ); canvg('canvas'+id++, svg_element.html()); svg_element.remove(); }); // Remove all the script on the page; we don't need to email it. (function(){jQuery('script').remove();})(); `$('body').append('<div id=""defaultElement""/>'); var hard_code_attributes = ['background-color', 'color', 'font-size', 'font-family']; var defaultElement = `$('#defaultElement').get()[0]; // add the computed style to the style attribute for every element. // this prevents incorrect rendering with viewers which can't handle CSS3 (i.e. Outlook). jQuery('*').each(function(e) { var newStyle = ''; for (var i = 0; i < hard_code_attributes.length; i++) { var a = hard_code_attributes[i]; if (this.currentStyle && this.currentStyle[a] && defaultElement.currentStyle && this.currentStyle[a] != defaultElement.currentStyle[a] ) { newStyle += a + ':' + this.currentStyle[a] + ';'; } } this.setAttribute('style', newStyle); }); var interval = setInterval(function(){ var numSvg = `$('svg').length; if (numSvg === 0) { // Render all the canvases as images. `$('canvas').each( function(d) { dbg(' processing svg canvas to image:'+`$(this).context.parentNode.id); var img = this.toDataURL('image/png'); var ii = `$('<img src=`"'+img+'`"/>').attr('src',img); `$(this).replaceWith(ii); } ); clearInterval(interval); } }, 100); " Write-Host -ForegroundColor Blue "Executing javascript..."+([DateTime]::Now.ToString()) $win.execScript($scriptCode, "javascript"); Write-Host -ForegroundColor Blue "Javascript done..."+([DateTime]::Now.ToString()) Start-Sleep -MilliSeconds 10000 $attachments = @(); $imgSuffix = ((($subject -replace ':','-') -replace '\s','') -replace "\[|\]",'') # Outlook won't render data url images as large as we need, so take the turn the data url into a separate file. # h/t http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/90ff6edd-75db-443a-bcaf-194f6f37e829 $imgNum = 1; foreach ($img in $ie.Document.getElementsByTagName("img")) { $imgNum++ $t1 = $img.ie8_getAttribute("src") $id = $img.ie8_getAttribute("id") $t1 = $img.src $imgFileName = "imgid$($id)_$($imgSuffix).png" if ($t1) { $txt = $t1.Replace("data:image/png;base64,", "") $imghref = "cid:$($imgFileName)" if ($dontSend) { $imghref = $imgFileName; } if (-not ($txt -imatch '^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$')) { Write-Host "Image is not base64 encoded! {$txt}" } else { $bytes = [System.Convert]::FromBase64String($txt) if ($bytes) { $decoded = [System.Text.Encoding]::Default.GetString($bytes) [Byte[]]$bytes_imagefront=[System.Text.Encoding]::Default.GetBytes($decoded) [io.file]::WriteAllBytes($imgFileName, $bytes_imagefront) $Attachment = New-Object System.Net.Mail.Attachment($imgFileName) $Attachment.ContentDisposition.Inline = $true $Attachment.ContentDisposition.DispositionType = "Inline" $Attachment.ContentType.MediaType = "image/png" $Attachment.ContentId = $imgFileName $attachments += $Attachment $img.ie8_setAttribute("src", $imghref) $img.src = $imghref $img.style = "width:100%;height:100%;" $img.ie8_setAttribute("style", "width:100%;height:100%;") } else { Write-Output "bytes is null for $id {$txt}" } } } } $body = $ie.Document.body.innerHtml; $bodyHtml += $body; $bodyHtml += "</html>"; $bodyHtml = $bodyHtml.Replace("—", "`&mdash;").Replace("†", "`&dagger;").Replace("‡", "`&Dagger;"); $bodyHtml | out-File -Encoding ascii -FilePath "body_$($imgSuffix).html" $smtpServer = "smtphost" $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = $fromMail foreach ($account in $toMail) { $msg.To.Add($account) } $msg.Subject = $subject $msg.Body = $bodyHtml $msg.IsBodyHtml = $true $attachments |% { $msg.Attachments.Add($_); } $smtp.UseDefaultCredentials = $true #$smtp.EnableSsl = $true if (-not $dontSend) { $smtp.Send($msg) } #http://stackoverflow.com/questions/7333973/how-to-get-rendered-html-processed-by-javascript-in-webbrowser-control #http://stackoverflow.com/questions/9435616/powershell-ie-automation-getelementbyid-with-multiple-entries $ie.Quit()
PowerShellCorpus/GithubGist/anroots_9421460_raw_54541be46b2768d95fd78f8f27a6d139a03453de_ping.ps1
anroots_9421460_raw_54541be46b2768d95fd78f8f27a6d139a03453de_ping.ps1
# A PowerShell script to check the status (online / offline) of NODE-s # Pings each NODE with a ICMP packet to get its status # # Author Ando Roots <ando@sqroot.eu> 2014-03-05 # -------------- CONFIG ------------------- # # Node numbers to ping $NodeList = 11,12,13,14,15,16,17,18,24 # How many pings to each node. The status is DOWN if any of them fail. $PingCount = 2 # Time to Live for the ping packets $TTL = 5 # ------------ END CONFIG ----------------- # echo "" date echo "NODE status check started" echo "" $Percent = 10 $SuccessCounter = 0 foreach ($Node in $NodeList) { # Full NODE IP to ping (CISCO gateway) $IP = "10.54."+$Node+".62" # Progress window write-progress -activity "Testing NODE Links..." -status "$Percent% complete" -percentcomplete $Percent -currentOperation "connecting to N$Node..." # Ping NODE, save output (bool) to a var $IsOnline = test-connection ($IP) -count $PingCount -Quiet -TimeToLive $TTL if ($IsOnline) { echo "N$Node is UP" $SuccessCounter += 1 } else { echo "N$Node is DOWN!" } $Percent += 10 } echo "-----------------" # Show summary $NodeCount = $NodeList.length $UPPercent = $SuccessCounter*100/$NodeList.length echo "$SuccessCounter of $NodeCount UP ($UPPercent%)"
PowerShellCorpus/GithubGist/kohlbrr_d7bc4af94e5a50e884ac_raw_04748950b327ed4dcbd0e77a1a58cfc7a2874def_folder_size.ps1
kohlbrr_d7bc4af94e5a50e884ac_raw_04748950b327ed4dcbd0e77a1a58cfc7a2874def_folder_size.ps1
$folderList = Get-ChildItem $rootFolder | Where-Object {$_.PSIsContainer -eq $true} foreach ($folder in $folderList) { $folderSize = Get-ChildItem $folder.FullName -Recurse -Force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -Sum -Property Length | Select-Object Sum Write-Output "$($folder.Name) -- $("{0:N2}" -f ($folderSize.sum / 1MB)) MB" }
PowerShellCorpus/GithubGist/guitarrapc_974f676f025586491b86_raw_1ae92e8797d937c84f620bd35caebd957dcdfb05_GetDSCResource.ps1
guitarrapc_974f676f025586491b86_raw_1ae92e8797d937c84f620bd35caebd957dcdfb05_GetDSCResource.ps1
Get-DscResource
PowerShellCorpus/GithubGist/trondhindenes_f5a1bc15074e9d19e81a_raw_f93b7ebff2f50df5718d4b94c7a8a4c85e0950e8_win_feature.ps1
trondhindenes_f5a1bc15074e9d19e81a_raw_f93b7ebff2f50df5718d4b94c7a8a4c85e0950e8_win_feature.ps1
#!powershell # This file is part of Ansible. # # Copyright 2014, Paul Durivage <paul.durivage@rackspace.com> # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # WANT_JSON # POWERSHELL_COMMON Import-Module Servermanager; $params = Parse-Args $args; $result = New-Object psobject @{ changed = $false } If ($params.name) { $name = $params.name } Else { Fail-Json $result "mising required argument: name" } If ($params.state) { $state = $params.state.ToString().ToLower() If (($state -ne 'present') -and ($state -ne 'absent')) { Fail-Json $result "state is '$state'; must be 'present' or 'absent'" } } Elseif (!$params.state) { $state = "present" } If ($params.restart) { $restart = $params.restart | ConvertTo-Bool } Else { $restart = $false } if ($params.include_sub_features) { $includesubfeatures = $params.include_sub_features | ConvertTo-Bool } Else { $includesubfeatures = $false } if ($params.include_management_tools) { $includemanagementtools = $params.include_management_tools | ConvertTo-Bool } Else { $includemanagementtools = $false } $name = $name.split(",") If ($state -eq "present") { try { $featureresult = Add-WindowsFeature -Name $name -Restart:$restart -IncludeAllSubFeature:$includesubfeatures -IncludeManagementTools:$includemanagementtools } catch { Fail-Json $result $_.Exception.Message } } Elseif ($state -eq "absent") { try { $featureresult = Remove-WindowsFeature -Name $name -Restart:$restart } catch { Fail-Json $result $_.Exception.Message } } # Loop through results and create a hash containing details about # each role/feature that is installed/removed $installed_features = @() #$featureresult.featureresult is filled if anything was changed if ($featureresult.FeatureResult) { ForEach ($item in $featureresult.FeatureResult) { $installed_features += New-Object psobject @{ id = $item.id.ToString() display_name = $item.DisplayName message = $item.Message restart_needed = $item.RestartNeeded.ToString() skip_reason = $item.SkipReason.ToString() success = $item.Success.ToString() } } Set-Attr $result "feature_result" $installed_features $result.changed = $true } Else { Set-Attr $result "feature_result" $null } Set-Attr $result "feature_success" $featureresult.Success.ToString() Set-Attr $result "feature_exitcode" $featureresult.ExitCode.ToString() Set-Attr $result "feature_restart_needed" $featureresult.RestartNeeded.ToString() Exit-Json $result;
PowerShellCorpus/GithubGist/PaulStovell_8702700_raw_4eb0e6fd3024ab06ed7164898a74af3c6baa67df_gistfile1.ps1
PaulStovell_8702700_raw_4eb0e6fd3024ab06ed7164898a74af3c6baa67df_gistfile1.ps1
## -------------------------------------------------------------------------------------- ## Configuration ## -------------------------------------------------------------------------------------- $isEnabled = $OctopusParameters["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] if (!$isEnabled -or ![Bool]::Parse($isEnabled)) { exit 0 } $WebSiteName = $OctopusParameters["Octopus.Action.IISWebSite.WebSiteName"] $ApplicationPoolName = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolName"] $bindingString = $OctopusParameters["Octopus.Action.IISWebSite.Bindings"] $appPoolFrameworkVersion = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] $webRoot = $OctopusParameters["Octopus.Action.IISWebSite.WebRoot"] $enableWindows = $OctopusParameters["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] $enableBasic = $OctopusParameters["Octopus.Action.IISWebSite.EnableBasicAuthentication"] $enableAnonymous = $OctopusParameters["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] $applicationPoolIdentityType = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] $applicationPoolUsername = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolUsername"] $applicationPoolPassword = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolPassword"] if (! $webRoot) { $webRoot = "." } $webRoot = (resolve-path $webRoot) $wsbindings = new-object System.Collections.ArrayList # Each binding string consists of a protocol/binding information (IP, port, hostname)/SSL thumbprint # Binding strings are pipe (|) separated to allow multiple to be specified $bindingString.Split("|") | foreach-object { $bindingParts = $_.split("/") $wsbindings.Add(@{ protocol=$bindingParts[0];bindingInformation=$bindingParts[1];thumbprint=$bindingParts[2] }) | Out-Null } Import-Module WebAdministration # For any HTTPS bindings, ensure the certificate is configured for the IP/port combination $wsbindings | where-object { $_.protocol -eq "https" } | foreach-object { $sslCertificateThumbprint = $_.thumbprint.Trim() Write-Host "Finding SSL certificate with thumbprint $sslCertificateThumbprint" $certificate = Get-ChildItem Cert:\LocalMachine -Recurse | Where-Object { $_.Thumbprint -eq $sslCertificateThumbprint -and $_.HasPrivateKey -eq $true } if (! $certificate) { throw "Could not find certificate under Cert:\LocalMachine with thumbprint $sslCertificateThumbprint. Make sure that the certificate is installed to the Local Machine context and that the private key is available." } Write-Host ("Found certificate: " + $certificate.Subject) $bindingInfo = $_.bindingInformation $bindingParts = $bindingInfo.split(':') $ipAddress = $bindingParts[0] if (! $ipAddress) { $ipAddress = "0.0.0.0" } $port = $bindingParts[1] $sslBindingsPath = ("IIS:\SslBindings\" + $ipAddress + "!" + $port) $sslBinding = get-item $sslBindingsPath -ErrorAction SilentlyContinue if (! $sslBinding) { new-Item $sslBindingsPath -Value $certificate | Out-Null } else { Set-Item $sslBindingsPath -Value $certificate | Out-Null } } ## -------------------------------------------------------------------------------------- ## Run ## -------------------------------------------------------------------------------------- pushd IIS:\ $appPoolPath = ("IIS:\AppPools\" + $ApplicationPoolName) $pool = Get-Item $appPoolPath -ErrorAction SilentlyContinue if (!$pool) { Write-Host "Application pool `"$ApplicationPoolName`" does not exist, creating..." new-item $appPoolPath $pool = Get-Item $appPoolPath } else { Write-Host "Application pool `"$ApplicationPoolName`" already exists" } Write-Host "Set application pool identity: $applicationPoolIdentityType" if ($applicationPoolIdentityType -eq "SpecificUser") { Set-ItemProperty $appPoolPath -name processModel -value @{identitytype="SpecificUser"; username="$applicationPoolUsername"; password="$applicationPoolPassword"} } else { Set-ItemProperty $appPoolPath -name processModel -value @{identitytype="$applicationPoolIdentityType"} } Write-Host "Set .NET framework version: $appPoolFrameworkVersion" Set-ItemProperty $appPoolPath managedRuntimeVersion $appPoolFrameworkVersion $sitePath = ("IIS:\Sites\" + $webSiteName) $site = Get-Item $sitePath -ErrorAction SilentlyContinue if (!$site) { Write-Host "Site `"$WebSiteName`" does not exist, creating..." $id = (dir iis:\sites | foreach {$_.id} | sort -Descending | select -first 1) + 1 new-item $sitePath -bindings @{protocol="http";bindingInformation=":81:od-temp.example.com"} -id $id -physicalPath $webRoot } else { Write-Host "Site `"$WebSiteName`" already exists" } Write-Host "Assigning website to application pool..." Set-ItemProperty $sitePath -name applicationPool -value $ApplicationPoolName Write-Host ("Home directory: " + $webRoot) Set-ItemProperty $sitePath -name physicalPath -value "$webRoot" Write-Host "Assigning bindings to website..." Clear-ItemProperty $sitePath -name bindings for ($i = 0; $i -lt $wsbindings.Count; $i = $i+1) { Write-Host ("Binding: " + ($wsbindings[$i].protocol + " " + $wsbindings[$i].bindingInformation)) New-ItemProperty $sitePath -name bindings -value ($wsbindings[$i]) } Write-Host "Anonymous authentication enabled: $enableAnonymous" Set-WebConfigurationProperty -filter /system.webServer/security/authentication/anonymousAuthentication -name enabled -value "$enableAnonymous" -location $WebSiteName -PSPath "IIS:\" Write-Host "Basic authentication enabled: $enableBasic" Set-WebConfigurationProperty -filter /system.webServer/security/authentication/basicAuthentication -name enabled -value "$enableBasic" -location $WebSiteName -PSPath "IIS:\" Write-Host "Windows authentication enabled: $enableWindows" Set-WebConfigurationProperty -filter /system.webServer/security/authentication/windowsAuthentication -name enabled -value "$enableWindows" -location $WebSiteName -PSPath "IIS:\" # It can take a while for the App Pool to come to life (#490) Start-Sleep -s 1 $state = Get-WebAppPoolState $ApplicationPoolName if ($state.Value -eq "Stopped") { Write-Host "Application pool is stopped. Attempting to start..." Start-WebAppPool $ApplicationPoolName } $state = Get-WebsiteState $WebSiteName if ($state.Value -eq "Stopped") { Write-Host "Web site is stopped. Attempting to start..." Start-Website $WebSiteName } popd Write-Host "IIS configuration complete"
PowerShellCorpus/GithubGist/RobertGiesecke_54397ae8e4753ac3c1e9_raw_873a9c377f5e812fe7bf6a91db83d772784f2088_removeFilesFromRep.ps1
RobertGiesecke_54397ae8e4753ac3c1e9_raw_873a9c377f5e812fe7bf6a91db83d772784f2088_removeFilesFromRep.ps1
param( [Parameter(Mandatory=$true)] [string]$patterns ); $ErrorActionPreference = 'STOP'; if(!$patterns) { return 0; } $splitted = New-Object System.Collections.Generic.HashSet[string]; ($patterns -split ';') | % { if(!$_) { return; } $text = $_ -ireplace '^\*/', ''; if($text) { [void]$splitted.Add($text); } } if(!$splitted | ? { $_ }) { return 0; } $indexFilter = [string]::Join('; ', ($splitted | % { "git rm -rf --cached --ignore-unmatch $($_)" })); $gitIgnoreScript = @' $ignoreLines = New-Object Collections.Generic.HashSet[string]; if([IO.File]::Exists('.gitignore')) { [IO.File]::ReadAllLines('.gitignore') | % { $ignoreLines.Add($_); } | Out-Null; } $w = [System.IO.File]::AppendText('.gitignore'); $w.WriteLine(); '@ + (($splitted | % { '$p = ''' + $_.Replace("'","''") + '''; if(!$ignoreLines.Contains($p)) { $w.WriteLine($p); }' } ) -join '; ') + @' $w.Close(); '@ $encodedCommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($gitIgnoreScript)); $suffix = @('--tag-name-filter', 'cat', '--force','--', '--all', '--tags'); & 'git' (('filter-branch', '--index-filter', $indexFilter) + $suffix); & 'git' (('filter-branch', '--tree-filter', '"powershell -encodedCommand ' + $encodedCommand + '"') + $suffix); git reflog expire --all git gc --aggressive --prune
PowerShellCorpus/GithubGist/peaeater_f6cd518894bc28d92001_raw_7c2eb9bfe3bd8c8bd9fac1f9d14bd3defaff6e8b_png2jpg.ps1
peaeater_f6cd518894bc28d92001_raw_7c2eb9bfe3bd8c8bd9fac1f9d14bd3defaff6e8b_png2jpg.ps1
# convert pngs to jpgs # requires imagemagick Param( [int]$size = 1000, [string]$indir = ".", [string]$outdir = $indir ) if (!(test-path $outdir)) { mkdir $outdir } $files = ls "$indir\*.*" -include *.png foreach ($file in $files) { $input = ('"{0}"' -f $file.FullName) $output = ('"{0}\{1}.jpg"' -f $outdir, $file.BaseName) $args = "$input -colorspace RGB -resize $size -colorspace sRGB $output" write-host $args start-process convert $args -wait -NoNewWindow }
PowerShellCorpus/GithubGist/sunnyc7_11102355_raw_99cc7cc040eb7b4d92839b7669eb75058a2b1ddf_monad-distilled.ps1
sunnyc7_11102355_raw_99cc7cc040eb7b4d92839b7669eb75058a2b1ddf_monad-distilled.ps1
# Monad distilled by @dfinke # Doug's comment here - http://www.jsnover.com/blog/2011/10/01/monad-manifesto/ # Monad Manifesto - http://www.jsnover.com/Docs/MonadManifesto.pdf <# Original Jeffrey Snover / Israel Gat value proposition construct. For <Customer> who <Qualifier>, <Product> <Value Statement>. Unlike <Alternative>, <Product> <Differentiator> #> <# These 6 lines of code from Doug bring clarity of thought. Clarity of thought translates into clarity in action. (Script development / Product development.) We seek clarity for our own sake when we are building things, and for our customers, so that they can understand whether our scripts and products solve their problems. Clarity is not only required, but paramount before commencing any development effort. This is pre-user stories, pre-requirements, pre-schedules and estimates. Lack of clarity translates into a muddled product, and this will show-up in your product. Get clarity before you write code. #> $Customer = “application developers” $Qualifier = “need to expose their administrative functions as command lines and GUIs” $Product = “PowerShell” $ValueStatement = “provides a highly productive development framework.” $Alternative = “building stand-alone command lines” $Differentiator = @” provides most of the common functions including a parser, a data validator/encoder, error reporting mechanisms, common functions like sorting/filtering/grouping/formatting/outputting and a set of management models which provide common verb sets, error messages and solutions to common problems and tools “@ @” For $Customer who $Qualifier, $Product $ValueStatement Unlike $Alternative, $Product $Differentiator “@
PowerShellCorpus/GithubGist/mlinnell_9733cf344bba270cc5c5_raw_d9e1c4de6bff8239bf548a1727bcac4b12c8e6d6_read_and_discard.ps1
mlinnell_9733cf344bba270cc5c5_raw_d9e1c4de6bff8239bf548a1727bcac4b12c8e6d6_read_and_discard.ps1
$env:_CLUSTER_NETWORK_NAME_ = "clustername" [Reflection.Assembly]::LoadWithPartialName("System.Messaging") $q = new-object System.Messaging.MessageQueue(".\private$\queue_name") $q.peek() for($i = 1; $i -le 10000;$i++){ $q.Receive() | out-null} # For dead letter queue, use "FORMATNAME:DIRECT=OS:.\SYSTEM$;DeadXact" # For a queues journal, use ".\private$\queue_name;journal"
PowerShellCorpus/GithubGist/SzymonPobiega_2657868_raw_7046fbb5951e52b12394a3d130c3db26e018fdfb_gistfile1.ps1
SzymonPobiega_2657868_raw_7046fbb5951e52b12394a3d130c3db26e018fdfb_gistfile1.ps1
# # The script switches IIS web applications to point to some other directory. It is very usefull when frequently changing branches. # The script assumes SVN-ish branch structure like this: # Root # | # |--Branches # | | # | |--Branch 1 # | | # | \--Branch 2 # | # \--Trunk # | # |--First.Web.Project # | # \--Second.Web.Project # # The list of web projects to use is provided via 'webapps.txt' file with following structure: # app;dir # webapp1;First.Web.Project # webapp2;Second.Web.Project # param ( [string]$Root = $(Throw "Source code root folder not specified"), [string]$Branch = $(Throw "Branch not specified") ) $websites = Import-Csv "webapps.txt" -Delimiter ";" function Execute-Cmd([string]$source, [string]$command, [string]$message) { Write-Host "${message}..." -NoNewline Write-Debug "${source}: ${command}" $output = cmd.exe /C $command if ($?) { Write-Host "OK" } else { Write-Host "Failed" throw "Failed ${message}" } } if ($Branch -eq "Trunk") { $root_dir = "${Root}\Code\Trunk\" } else { $root_dir = "${Root}\Code\Branches\${Branch}\" } $websites | ForEach-Object { $dir = $_.dir $app = $_.app $work_dir = $root_dir + $dir $params = "set app `"Default Web Site/$app`" -[path='/'].physicalpath:`"${work_dir}`"" $command = "$env:SystemRoot\system32\inetsrv\appcmd $params" $message = "Switching working directory of $app to $work_dir" Execute-Cmd "APPCMD" $command $message }
PowerShellCorpus/GithubGist/oklahomaok_3695323_raw_82892d5d9e966b24cec734db9e2fec95764a90c9_ReverseGeocoding.ps1
oklahomaok_3695323_raw_82892d5d9e966b24cec734db9e2fec95764a90c9_ReverseGeocoding.ps1
# HeartRails Geo API $uri = "http://geoapi.heartrails.com/api/json?method=searchByGeoLocation" try { # 引数取得 $input = $args[0] $output = $args[1] # CSVから緯度経度を取得してGeoAPIに問い合わせる $cities = ipcsv $input | %{ iwr ($uri + "&x=" + $_.Lon + "&y=" + $_.Lat) | ConvertFrom-Json } | %{ $_.response.location[0].prefecture + $_.response.location[0].city } # ヘッダを除いて行末に都道府県市町村区を追記する $lines = Get-Content $input for( $i = 1; $i -le $lines.Length - 1; $i++ ) { $lines[$i] + "," + $cities[$i - 1] | Out-File $output -Append } } catch { $_.exception "エラーが発生しました。終了します。" $host.UI.ReadLine() }
PowerShellCorpus/GithubGist/ritalin_6086448_raw_fcc7bdf5186fb396856a3d54054207a7d25e7ebd_test.ps1
ritalin_6086448_raw_fcc7bdf5186fb396856a3d54054207a7d25e7ebd_test.ps1
function test($v) { $v } test $(if ($true) { "A" } else { "B" })
PowerShellCorpus/GithubGist/smurawski_9352282_raw_77dd55b14d12d533902cc2a0c79792e80ae2f96a_Netbackup%20Daily%20Report.ps1
smurawski_9352282_raw_77dd55b14d12d533902cc2a0c79792e80ae2f96a_Netbackup%20Daily%20Report.ps1
<# This Gist was created by ISEGist 03/04/2014 12:15:25 #> ################################################################################################### # # NAME: NBU-DailyReport.ps1 # # AUTHOR: Martijn Jonker # # COMMENT: Script to create a backup report from Netbackup jobs on windows platform. # Adjust variables below this section. # The script generates a report every weekday. Monday report covers the weekend. # To adjust this, edit lines 94-103 and 483-490 # # The script calls Netbackup commandline tools to gather information. # Job status is checked against three different arrays (Successful, partial, failed). # Depending on Status, Client, Policy, Schedule and EndTime lines are either added to or # removed from the arrays. # The script gathers statistics per policy/server about the backup operation, # (number of files backed up,size of files backed up and elapsed time), # so servers is multiple policies will show up multiple times in the statistics. # The script reports tape media and disk storage unit usage. # The script e-mails the result # # Run the script interactively, or as a scheduled task. # # The script requires "<Programdir>\NetBackup\bin\admincmd" and # "<Programdir>\NetBackup\bin\goodies" to be in the %path% ($Env:path) environment variable # # The script was tested with NetBackup 6.5, 6.5.5 and 7.0, # in a single master/media server environment. # # VERSION HISTORY: # 1.0: Transcoded from .vbs to .ps1 # 1.1: Added E-mail notification # 2.0: Rewrote logic for better efficiency # 2.1: Minor tweaks to date/time formatting # 3.0: Added Tape Media used for backup # Added Storage Unit Status # Added Backup statictics # 3.1: Documented script # Minor efficiency tweaks ################################################################################################### # --------------------------- Adjust variables below to suit your needs --------------------------- # $StartTime = "17:00:00" # Starttime for backup operation, in NBU format $Endtime = "17:00:00" # Endtime for backup operation, in NBU format $OutputPth = "C:\scripts" # Path to $outputfile $OutputFile = "BackupReport.txt" # Name of outputfile $SmtpServer = "smtp.server" # Address of SMTP server $From = "netbackup@company.com" # From e-mail address $To = "report@company.com" # To e-mail address. Multiple addresses can be used, seperate by comma $CC = "CC-Recipients.txt" # Textfile containing e-mail addresses to CC, one per line. Located in $outputpth $ClientStringLength = 15 # Number of characters in the $client string, including whitespace $PolicyStringLength = 25 # Number of characters in the $Policy string, including whitespace $FileStringLength = 10 # Number of characters in the $Files string, including whitespace $KBStringLength = 12 # Number of characters in the $KBs string, including whitespace $ElapsedString = 10 # Number of characters in the $Elapsed string, including whitespace # # !> ---------------------------! Do not change anything beyond this point !--------------------------- <! # Switch (Test-Path $OutputPth) # Check if $OutputPth exists { False # If $OutputPth does not exist { New-Item $OutputPth -ItemType Directory | Out-Null # Create $OutputPth Write-Host "Output Path did not exist, it was created: $OutputPth" -ForegroundColor "White" # Write to console Write-Host "----------" -ForegroundColor "Yellow" # Write to console } } $OutputStr = $OutputPth + "\" + $OutputFile # Combine $OutputPth and $OutputFile to a single string # --- $JobHeader = "STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED" # General header for backup job status $ClientNotReported = @("";"Servers that did not (yet) report any activity";"----------------------------------------------";("CLIENT"+" "*($ClientStringLength-6))+("POLICY"+" "*($PolicyStringLength-6))) # initialize array for servers that did not report activity at the time of running the report and add header $TotalOK = @() # Initialize array to contain the final results for all successful jobs $TotalPartial = @() # Initialize array to contain the final results for all partially successful jobs $TotalFail = @() # Initialize array to contain the final results for all failed jobs $UsedPolSched = @() # Initialize array to contain policies and schedules used during backup operation, used to report on disk storageunits. # --- $NBU_BaseTime = get-date "1/1/1970 00:00:00" # Netbackup Basetime, used to calculate elapsed time $TotalFiles = 0 # Initialize variable to contain the total number of files backed up $TotalKB = 0 # Initialize variable to contain the total KiloBytes backed up $NBUStats = @() # Initialize array to contain the backup operation statistics $NBUStatsHeader = @("";"BACKUP STATISTICS";("CLIENT"+" "*($ClientStringLength-6))+("POLICY"+" "*($PolicyStringLength-6))+("FILES"+" "*($FileStringLength-5))+("SIZE"+" "*($KBStringLength-4))+("ELAPSED"+" "*($ElapsedString-7))) # Array containing header for backup statistics $NBUStatsHeader += @("-"*$NBUStatsHeader[2].Length) # Add separator # --------------------------- Clear-Host # Set the console foreground color [console]::ForegroundColor = "White" # --------------------------- write to console Write-Host "" Write-Host "============================================================" -ForegroundColor "Yellow" Write-Host " NetBackup - Daily Report" Write-Host "============================================================" -ForegroundColor "Yellow" Write-Host "" Write-Host "" # --------------------------- $Now = Get-date # Store current date and time If (($Now.DayOfWeek -eq "Tuesday") -OR ($Now.DayOfWeek -eq "Wednesday") -OR ($Now.DayOfWeek -eq "Thursday") -OR ($Now.DayOfWeek -eq "Friday")) # For every weekday except monday { $StartDate = "{0:MM\/dd\/yyyy $StartTime}" -f ($Now.AddDays(-1)) # set the startdate back one day, using the previously set starttime } If ($Now.DayOfWeek -eq "Monday") # For every monday { $StartDate = "{0:MM\/dd\/yyyy $StartTime}" -f ($Now.AddDays(-3)) # set the startdate back three days (to encompass the weekend), using the previously set starttime } $EndDate = "{0:MM\/dd\/yyyy $Endtime}" -f ($Now) # set the enddate to today, using the previously set endtime # --------------------------- $NbuPolicyList = Invoke-Expression "bppllist" # Using NBU cmd get a list of all policies ForEach ($Policy in $NbuPolicyList) # Process all listed policies { # --- $OKHeader = @("";"Successful jobs during the $Policy backup") # header to add to below declared array $OKHeader += @("-"*$OKHeader[1].Length) # Add variable length horizontal separator $JobOK = New-Object System.Collections.ArrayList # Array to contain successful jobs $JobOK.Add($OKHeader) | Out-Null # Add header to array $JobOK.Add($JobHeader) | Out-Null # Add general header to array $JobOKCount=1 # Record count in array # --- $PartialHeader = @("";"Partially Successful jobs during the $Policy backup") # header to add to below declared array $PartialHeader += @("-"*$PartialHeader[1].Length) # Add variable length horizontal separator $JobPartial = New-Object System.Collections.ArrayList # Array to contain partially successful jobs $JobPartial.Add($PartialHeader) | Out-Null # Add header to array $JobPartial.Add($JobHeader) | Out-Null # Add general header to array $JobPartialCount=1 # Record count in array # --- $FailHeader = @("";"Failed jobs during the $Policy backup") # header to add to below declared array $FailHeader += @("-"*$FailHeader[1].Length) #Add variable length horizontal separator $JobFail = New-Object System.Collections.ArrayList # Array to contain failed jobs $JobFail.Add($FailHeader) | Out-Null # Add header to array $JobFail.Add($JobHeader) | Out-Null # Add general header to array $JobFailCount=1 # Record count in array # --- If ($Policy.Length -gt 16) # If policy name is longer than 16 chars { $PolicyFilter = $Policy.SubString(0,16).Trim() # Trim policy name down to 16 chars } Else { $PolicyFilter = $Policy } $PolicyDetails = Invoke-Expression "bppllist $Policy -L" # Using NBU cmd get policy details $PolicyActive = $PolicyDetails | Select-String "Active" | %{$_.ToString().SubString(19).Trim()} # From policy details, get the policy status $PolicyType = $PolicyDetails | Select-String "Policy Type:" | %{$_.ToString().SubString(19).Trim()} # From policy details, get the policy type If ($PolicyActive -eq "yes") # If policy is active, process it, inactive policies are not processed { $PolicyClientList = $PolicyDetails | select-String "Client/HW/OS/Pri:" | Sort-Object # From policy details, get the list of clients ForEach ($ClientStr in $PolicyClientList) { $Client = $ClientStr.ToString().Split()[2] # Extrapolate Client name If ($Client.Length -gt $ClientStringLength) # For report makeup check lenght of the string { $ClientStringLength = $Client.Length+3 # If necessary add three characters whitespace to the string } $ClientJobList = Invoke-Expression "bperror.exe -client $Client -U -backstat -s info -d $StartDate -e $EndDate 2>&1" | Select-String " $PolicyFilter" # Using NBU cmd get the jobs for currently processing client and narrow the selection of jobs to the currently processing policy #-- Start Statistics gathering for the currently processing policy and the currently processing client $ClientImages = Invoke-Expression "bpimagelist -client $Client -d $StartDate -e $EndDate 2>&1" | Select-String $Policy # Using NBU cmd get backup images for the currently processing client narrowed by the currently processing policy If (($ClientImages) -AND ($ClientImages.GetType().Name -ne "ErrorRecord")) # If backup images are available { ForEach ($Image in $ClientImages) # Process each backup image { $Image = $Image.ToString().Split() # Convert the current backup image line to a string and split the string at every space [Int32]$Files = $Image[19] # From the split string, get the number of files at row 19 [Int32]$KBs = $Image[18] # From the split string, get the KiloBytes at row 18 [Int32]$JobStart = $Image[13] # From the split string, get the start time (relative to the NBU_BaseTime in seconds) at row 13 [Int32]$JobEnd = ($JobStart+[Int32]$Image[14]) # From the split string, add the elapsed seconds at row 14 to the jobstart variable to get the endtime (relative to the NBU_BaseTime in seconds) $JobStartTime = $NBU_BaseTime.AddSeconds($JobStart) # Add the seconds from jobstart to NBU_BaseTime to get a datetime object for starttime $JobEndTime = $NBU_BaseTime.AddSeconds($JobEnd) # Add the seconds from jobend to NBU_BaseTime to get a datetime object for endtime $ElapsedTime = New-TimeSpan $JobStartTime $JobEndTime # Get a timespan for the elapsed time $TotalElapsedTime = ($TotalElapsedTime+$ElapsedTime) # Add the timespan to the total elapsed time for this policy $TotalFiles = ($TotalFiles+$Files) # Add the number of files to the total file count for this policy $TotalKB = ($TotalKB+$KBs) # Add the KiloBytes to the total KiloBytes for this policy } $TotalKB = ($TotalKB*1024) # mulitply by 1024 $GrandTotalKB = ($GrandTotalKB+$TotalKB) # Add totalkb to GrandTotalKB, aggregate for all policies $GrandTotalFiles = ($GrandTotalFiles+$TotalFiles) # Add totalfiles to GrandTotalFiles, aggregate for all policies If ($TotalKB -lt 1048576) # Format TotalKB to reflect: { $TotalKBs = "{0:N} KB" -f $($TotalKB/1KB) # KiloBytes or, } If (($TotalKB -ge 1048576) -AND ($TotalKB -lt 1073741824)) { $TotalKBs = "{0:N} MB" -f $($TotalKB/1MB) # MegaBytes or, } If (($TotalKB -ge 1073741824) -AND ($TotalKB -lt 1099511627776)) { $TotalKBs = "{0:N} GB" -f $($TotalKB/1GB) # GigaBytes or, } If ($TotalKB -ge 1099511627776) { $TotalKBs = "{0:N} TB" -f $($TotalKB/1TB) # TeraBytes } $TotalFiles = "{0:N0}" -f $TotalFiles # format the number for further processing $StatString = ($Client+" "*($ClientStringLength-$Client.Length))+($Policy+" "*($PolicyStringLength-$Policy.Length))+($TotalFiles+" "*($FileStringLength-$TotalFiles.Length))+($TotalKBs+" "*($KBStringLength-$TotalKBs.Length))+"$TotalElapsedTime" # Create a String per server, per policy with the following fields: CLIENT,POLICY,FILES,SIZE,ELAPSED $NBUStats += @($StatString) # Add the above string to the NBUStats array $TotalFiles = 0 # Reset variable $TotalKB = 0 # Reset variable $TotalKBs = 0 # Reset variable Clear-variable TotalElapsedTime # Reset variable } # --- End Statistics gathering If ($ClientJobList) # Process backup jobs for currently processing client if they are available { $ClientReported += @("$Client`t$PolicyType") # Add the client and policy name to array for checking ForEach ($Job in $ClientJobList) # Process each job { $Job = [String]$Job # Stringify the job $StatusCode = $Job.SubString(0,7).Trim() # From string $job, extract statuscode If (($StatusCode -eq "STATUS") -OR (!$StatusCode)) # If $statuscode equals "status" or is emtpy { Continue # Skip this job } Else { $StatusCode = [Int]$StatusCode # Set statuscode as integer } $JobClient = $Job.SubString(7,14).Trim() # From string $job, extract clientname $JobPolicy = $Job.SubString(21,17).Trim() # From string $job, extract policyname $JobSchedule = $Job.SubString(38,11).Trim() # From string $job, extract schedule If ($JobSchedule -match "Default") # If schedule matches "default", { Continue # skip this job } If ($UsedPolSched -notcontains "$Policy,$JobSchedule") # If this policy and schedule are not yet registered in the array, { $UsedPolSched += @("$Policy,$JobSchedule") # Register this policy and schedule in the array } $JobNBServer = $Job.SubString(49,12).Trim() # From string $job, extract NBU master server $JobTimeComplete = $Job.SubString(61).Trim() # From string $job, extract time completed # --- $ReadOKClient = $JobOK[$JobOKCount].SubString(7,14).Trim() # From the $JobOK array read the $JobOKCount row and extract client name $ReadOKPolicy = $JobOK[$JobOKCount].SubString(21,17).Trim() # From the $JobOK array read the $JobOKCount row and extract policy name $ReadOKSchedule = $JobOK[$JobOKCount].SubString(38,11).Trim() # From the $JobOK array read the $JobOKCount row and extract schedule $ReadOKTimeStamp = $JobOK[$JobOKCount].SubString(61).Trim() # From the $JobOK array read the $JobOKCount row and extract time completed # --- $ReadPartialClient = $JobPartial[$JobPartialCount].SubString(7,14).Trim() # From the $JobPartial array read the $JobPartialCount row and extract client name $ReadPartialPolicy = $JobPartial[$JobPartialCount].SubString(21,17).Trim() # From the $JobPartial array read the $JobPartialCount row and extract policy name $ReadPartialSchedule = $JobPartial[$JobPartialCount].SubString(38,11).Trim() # From the $JobPartial array read the $JobPartialCount row and extract schedule $ReadPartialTimeStamp = $JobPartial[$JobPartialCount].SubString(61).Trim() # From the $JobPartial array read the $JobPartialCount row and extract time completed # --- $ReadFailClient = $JobFail[$JobFailCount].SubString(7,14).Trim() # From the $JobFail array read the $JobFailCount row and extract client name $ReadFailPolicy = $JobFail[$JobFailCount].SubString(21,17).Trim() # From the $JobFail array read the $JobFailCount row and extract policy name $ReadFailSchedule = $JobFail[$JobFailCount].SubString(38,11).Trim() # From the $JobFail array read the $JobFailCount row and extract schedule $ReadFailTimeStamp = $JobFail[$JobFailCount].SubString(61).Trim() # From the $JobFail array read the $JobFailCount row and extract time completed # --- Write progress to console $ClntStr = $Client+" "*($ClientStringLength-$Client.Length) # For interactive use only, get client name and add whitespace Write-Host " Client: " -NoNewLine # Write to console, Write-Host $ClntStr -NoNewLine -ForeGroundColor "Cyan" # The currently processing client Write-Host "Status: " -NoNewLine # Write to console, Switch ($StatusCode) { 0 { Write-Host $StatusCode -NoNewLine -ForeGroundColor "Green" # Status successful } 1 { Write-Host $StatusCode -NoNewLine -ForeGroundColor "Yellow" # Status partially successful } Default { Write-Host $StatusCode -NoNewLine -ForeGroundColor "Red" # Status failed } } Write-Host "`tPolicy: " -NoNewLine # Write to console, Write-Host $Policy -ForeGroundColor "Cyan" # The currently processing clients' policy # --- Switch ($StatusCode) # Process jobs by statuscode { {$StatusCode -eq 0} # If statuscode equals 0 (Successful), process job { If ($JobOKCount -eq 1) # If row count of the $JobOK array equals 1 { $JobOK.Add($Job) | Out-Null # Add the currently processing job values to the array $JobOKCount++ # Increment the row count } ElseIf (($JobClient -eq $ReadOKClient) -AND ($JobPolicy -eq $ReadOKPolicy) -AND ($JobSchedule -eq $ReadOKSchedule) -AND ($JobTimeComplete -ge $ReadOKTimeStamp)) # If Client, Policy and Schedule are the same, but the time completed is greater than the values read from the $JobOK array, { $JobOK[$JobOKCount] = $Job # Replace the read values with the currently processing job values } Else { $JobOK.Add($Job) | Out-Null # If all above logic is not true, add the currently processing job values to the array $JobOKCount++ # Increment the row count } If (($JobPartialCount -gt 1) -AND ($JobClient -eq $ReadPartialClient) -AND ($JobPolicy -eq $ReadPartialPolicy) -AND ($JobSchedule -eq $ReadPartialSchedule) -AND ($JobTimeComplete -ge $ReadPartialTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobPartial Array, if currently processing job time completed is greater than the value of time completed in $JobPartial, { $JobPartial.Remove($JobPartial[$JobPartialCount]) | Out-Null # Remove the read values from the array $JobPartialCount-- # Decrement the row count } If (($JobFailCount -gt 1) -AND ($JobClient -eq $ReadFailClient) -AND ($JobPolicy -eq $ReadFailPolicy) -AND ($JobSchedule -eq $ReadFailSchedule) -AND ($JobTimeComplete -ge $ReadFailTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobFail Array, if currently processing job time completed is greater than the value of time completed in $JobFail, { $JobFail.Remove($JobFail[$JobFailCount]) | Out-Null # Remove the read job values from the array $JobFailCount-- # Decrement the row count } } {$StatusCode -eq 1} # If statuscode equals 1 (Partially successful), process job { If ($JobPartialCount -eq 1) # If row count of the $JobPartial array equals 1 { $JobPartial.Add($Job) | Out-Null # Add the currently processing job values to the array $JobPartialCount++ # Increment the row count } Else { If (($JobClient -eq $ReadPartialClient) -AND ($JobPolicy -eq $ReadPartialPolicy) -AND ($JobSchedule -eq $ReadPartialSchedule) -AND ($JobTimeComplete -ge $ReadPartialTimeStamp)) # If Client, Policy and Schedule are the same, but the time completed is greater than the values read from the $JobPartial array, { $JobPartial[$JobPartialCount] = $Job # Replace the read values with the currently processing job values } Else { $JobPartial.Add($Job) | Out-Null # If all above logic is not true, add the currently processing job values to the array $JobPartialCount++ # Increment the row count } } If (($JobOKCount -gt 1) -AND ($JobClient -eq $ReadOKClient) -AND ($JobPolicy -eq $ReadOKPolicy) -AND ($JobSchedule -eq $ReadOKSchedule) -AND ($JobTimeComplete -ge $ReadOKTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobOK Array, if currently processing job time completed is greater than the value of time completed in $JobOK, { $JobOK.Remove($JobOK[$JobOKCount]) | Out-Null # Remove the read job $JobOK values from the array $JobOKCount-- # Decrement the row count } If (($JobFailCount -gt 1) -AND ($JobClient -eq $ReadFailClient) -AND ($JobPolicy -eq $ReadFailPolicy) -AND ($JobSchedule -eq $ReadFailSchedule) -AND ($JobTimeComplete -ge $ReadFailTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobFail Array, if currently processing job time completed is greater than the value of time completed in $JobFail, { $JobFail.Remove($JobFail[$JobFailCount]) | Out-Null # Remove the read job $JobFail values from the array $JobFailCount-- # Decrement the row count } } {$StatusCode -gt 1} # If statuscode greater than 1 (Failed), process job { If ($JobFailCount -eq 1) { $JobFail.Add($Job) | Out-Null # Add the currently processing job values to the array $JobFailCount++ # Increment the row count } Else { If (($JobClient -eq $ReadFailClient) -AND ($JobPolicy -eq $ReadFailPolicy) -AND ($JobSchedule -eq $ReadFailSchedule) -AND ($JobTimeComplete -ge $ReadFailTimeStamp)) # If Client, Policy and Schedule are the same, but the time completed is greater than the values read from the $JobFail array, { $JobFail[$JobFailCount] = $Job # Replace the read values with the currently processing job values } Else { $JobFail.Add($Job) | Out-Null # If all above logic is not true, add the currently processing job values to the array $JobFailCount++ # Increment the row count } } If (($JobOKCount -gt 1) -AND ($JobClient -eq $ReadOKClient) -AND ($JobPolicy -eq $ReadOKPolicy) -AND ($JobSchedule -eq $ReadOKSchedule) -AND ($JobTimeComplete -ge $ReadOKTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobOK Array, if currently processing job time completed is greater than the value of time completed in $JobOK, { $JobOK.Remove($JobOK[$JobOKCount]) | Out-Null # Remove the read job $JobOK values from the array $JobOKCount-- # Decrement the row count } If (($JobPartialCount -gt 1) -AND ($JobClient -eq $ReadPartialClient) -AND ($JobPolicy -eq $ReadPartialPolicy) -AND ($JobSchedule -eq $ReadPartialSchedule) -AND ($JobTimeComplete -ge $ReadPartialTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobPartial Array, if currently processing job time completed is greater than the value of time completed in $JobPartial, { $JobPartial.Remove($JobPartial[$JobPartialCount]) | Out-Null # Remove the read job $JobPartial values from the array $JobPartialCount-- # Decrement the row count } } } } } Else # If $ClientJobList is empty { If ($ClientReported -contains "$Client`t$PolicyType") # If client and schedule are present in the $ClientReported array { Continue # Continue } Else # If client and schedule are NOT present in the $ClientReported array (line 195) { $CNRString = ($Client+" "*($ClientStringLength-$Client.Length))+($Policy+" "*($PolicyStringLength-$Policy.Length)) # Format a string with client and policy values $ClientNotReported += @($CNRString) # Add the string value to the $ClientNotReported array Continue } } } If ($JobOK.Count -gt 2) # If the row count of $JobOK array is greater than 2, { $TotalOK += $JobOK # Add the values of $JobOK to $TotalOK If ($JobOK) {Clear-Variable JobOK} # Clear the array in preparation of processing the next policy } If ($JobPartial.Count -gt 2) # If the row count of $JobPartial array is greater than 2, { $TotalPartial += $JobPartial # Add the values of $JobPartial to $TotalPartial If ($JobPartial) {Clear-Variable JobPartial} # Clear the array in preparation of processing the next policy } If ($JobFail.Count -gt 2) # If the row count of $JobFail array is greater than 2, { $TotalFail += $JobFail # Add the values of $JobFail to $TotalFail If ($JobFail) {Clear-Variable JobFail} # Clear the array in preparation of processing the next policy } } } # --- $NBUStats = $NBUStats | Sort-Object # Sort the NBUStats array $GrandTotalFiles = "{0:N0}" -f $GrandTotalFiles # Format the value of GrandTotalFiles If ($GrandTotalKB -lt 1048576) # Format GrandTotalKB to reflect, { $GrandTotalKBs = "{0:N} KB" -f $($GrandTotalKB/1KB) # KiloBytes, } If (($GrandTotalKB -gt 1048576) -AND ($GrandTotalKB -lt 1073741824)) { $GrandTotalKBs = "{0:N} MB" -f $($GrandTotalKB/1MB) # MegaBytes, } If ($GrandTotalKB -gt 1073741824 -AND ($GrandTotalKB -lt 1099511627776)) { $GrandTotalKBs = "{0:N} GB" -f $($GrandTotalKB/1GB) # GigaBytes, or } If ($GrandTotalKB -gt 1099511627776) { $GrandTotalKBs = "{0:N} TB" -f $($GrandTotalKB/1TB) #TeraBytes } $NBUStats += @("";"Total Files backedup: $GrandTotalFiles";"Total Data backedup: $GrandTotalKBs") # Add the aggregate values to the NBUStats array # --------------------------- Write-Host "" # Write to console Write-Host "Checking for active jobs..." -ForegroundColor "Yellow" # Write to console $ActivejobList = Invoke-Expression "bpdbjobs -ignore_parent_jobs" | Select-String "Active" # Using NBU cmd check for active jobs at the time of reporting $ActiveJobs = @("";"Active jobs at the time of report") # Initialize ActiveJobs array and add header $ActiveJobs += @("-"*$ActiveJobs[1].Length) #Add variable length horizontal separator If ($ActivejobList) # If ActivejobList contains data { ForEach ($ActiveJob in $ActiveJobList) # Process active jobs { $ActiveClient = $Activejob.ToString().SubString(0,112) # Get the first 112 characters from the job string $ActiveJobs += @($ActiveClient) # Add it to the ActiveJobs array } } # --------------------------- Write-Host "" # Write to console Write-Host "Getting tape media used..." -ForegroundColor "Yellow" # Write to console $TapeMediaUsed = @("";"Tape Media used during backup") # Initialize array and add header $TapeMediaUsed += @("-"*$TapeMediaUsed[1].Length) # Add variable length horizontal separator $ColTapeMediaUsed = Invoke-Expression "bpimagelist -media -L -d $StartDate -e $EndDate" # Using NBU cmd get tape media used $TapeMediaUsedCount = ($ColTapeMediaUsed | Select-String "Media ID:").Count # From ColTapeMediaUsed get the number of media used [Int]$1=0 # Row number of "Media ID" in ColTapeMediaUsed [Int]$2=2 # Row number of "Last Time Written" in ColTapeMediaUsed [Int]$3=3 # Row number of "Times Written" in ColTapeMediaUsed [Int]$4=4 # Row number of "Kilobytes" in ColTapeMediaUsed For ($i=0; $i -le $TapeMediaUsedCount; $i++) # For the number of media used, { $TapeMediaUsed += @($ColTapeMediaUsed[$1,$2,$3,$4];"") # Write the values to the array $1=$1+7 # Increment the row number by 7 for the next media used $2=$2+7 # Increment the row number by 7 for the next media used $3=$3+7 # Increment the row number by 7 for the next media used $4=$4+7 # Increment the row number by 7 for the next media used } # --------------------------- Write-Host "" # Write to console Write-Host "Getting disk storage units used..." -ForegroundColor "Yellow" # Write to console $DiskStorageUnits = @("";"Disk Storage Units Status") # Initialize array and add header $DiskStorageUnits += @("-"*$DiskStorageUnits[1].Length) # Add variable length horizontal separator $ColDiskStorageUnits = Invoke-Expression "nbdevquery -listdv -stype BasicDisk -U" # Using NBU cmd to get disk storageunits ForEach ($PolSched in $UsedPolSched) # Process policies/schedules used during backup operation (see line 215,74) to extract disk storageunit usage { $PolSched=$PolSched.Split(",") # Split the $polSched string at the comma $UsedPolicy = $PolSched[0] # From the split string extract the Policyname $UsedSchedule = $PolSched[1] # From the split string extract the Schedule $UsedPolicyDetails = Invoke-Expression "bppllist $UsedPolicy -L" # Using NBU cmd get currently processing policy details $ScheduleStartLine = ($UsedPolicyDetails | Select-String "Schedule:.*$UsedSchedule").LineNumber-1 # From the policy details extract the linenumber where the used schedule details begin $Schedule = $UsedPolicyDetails[$ScheduleStartLine..$Usedpolicydetails.Count] # From above acquired linenumber select all lines to the last line of the policy details Try { $ScheduleEndLine = ($Schedule | Select-String "Schedule")[1].LineNumber-2 # Check if multiple schedule details are selected, by selecting the word "Schedule". If true acquire the linenumber of the second instance of the word "Schedule" and extract 2 lines } Catch { $ScheduleEndLine = $Usedpolicydetails.Count # If the above statement fails, it is the last schedule description in policy details, so the last line of the policydetails is also the last line of the schedule description } $Schedule = $Schedule[0..$ScheduleEndLine] # Final selection to acquire the schedule description $StorageUnitString = ($Schedule | Select-String "Residence:").ToString().SubString(19).Trim() # From the schedule details acquire the "residence" value If ($ColDiskStorageUnits -contains "Disk Pool Name : $StorageUnitString") # If previously collected disk storageunits data, contains the StorageUnitString, { [Int]$ColStorageUnitLineNumber = ($ColDiskStorageUnits | Select-String "Disk Pool Name .*$StorageUnitString").LineNumber-1 # Get the linenumber for the line that contains "Disk Pool Name .*$StorageUnitString" and extract 1 to compensate for the fact that powershell starts counting at 0 instead of 1 [Int]$1=$ColStorageUnitLineNumber # linenumber for "Disk Pool Name" [Int]$2=$ColStorageUnitLineNumber+4 # linenumber for "Total Capacity" [Int]$3=$ColStorageUnitLineNumber+5 # linenumber for "Free Space" [Int]$4=$ColStorageUnitLineNumber+6 # linenumber for "Use%" [Int]$5=$ColStorageUnitLineNumber+7 # linenumber for "Status" If ($DiskStorageUnits -notcontains "Disk Pool Name : $StorageUnitString") # If array DiskStorageUnits does not contain a line like "Disk Pool Name : $StorageUnitString", { $DiskStorageUnits += @($ColDiskStorageUnits[$1,$2,$3,$4,$5];"") # Add the disk storageunit details to the array } } } # --------------------------- Write-Host "" # Write to console Write-Host "Creating report..." -ForegroundColor "Yellow" # Write to console Set-Content $OutputStr "" # initialize the output file $ReportStart = "{0:dddd dd\-MM\-yyyy H:mm:ss}" -f $Now # Format date and time for the script start timestamp If (($Now.DayOfWeek -eq "Tuesday") -OR ($Now.DayOfWeek -eq "Wednesday") -OR ($Now.DayOfWeek -eq "Thursday") -OR ($Now.DayOfWeek -eq "Friday")) # For every weekday except monday { $ReportingDate = "{0:dddd dd\-MM\-yyyy}" -f ($Now.AddDays(-1)) # Set the date back one day and format the date for the date of the backup operation } If ($Now.DayOfWeek -eq "Monday") # For every monday { $ReportingDate = "{0:dddd dd\-MM\-yyyy}" -f ($Now.AddDays(-3)) # Set the date back three days and format the date for the date of the backup operation } $ReportHeader = @("Report Generated on $env:COMPUTERNAME, $ReportStart";"";"Backup report for $ReportingDate") # Array with multiline header Add-Content $OutputStr $ReportHeader # Add the header to the output file $ReportParts = @($TotalFail,$TotalPartial,$TotalOK) # Array containing the names of the arrays with the overall results of the backup operation ForEach ($Part in $ReportParts) # For each array, { If ($Part.Count -ge 3) # If the line count is greater than 3, { Add-Content $OutputStr $Part # Add the array to the output file } } If ($ActiveJobs.Count -gt 4) # If the line count is greater than 3, { Add-Content $OutputStr $ActiveJobs # Add the array to the output file } If ($ClientNotReported.Count -gt 4) # If the line count is greater than 4, { Add-Content $OutputStr $ClientNotReported # Add the array to the output file } If ($NBUStats.Count -ge 1) # If the line count is greater than 4, { Add-Content $OutputStr $NBUStatsHeader # Add the header array to the output file Add-Content $OutputStr $NBUStats # Add the array to the output file } If ($TapeMediaUsed.Count -gt 3) # If the line count is greater than 3, { Add-Content $OutputStr $TapeMediaUsed # Add the array to the output file } If ($DiskStorageUnits.Count -gt 3) # If the line count is greater than 3, { Add-Content $OutputStr $DiskStorageUnits # Add the array to the output file } Add-Content $OutputStr "" # Add blank line to the output file Add-Content $OutputStr "--------------------------------------------------" # Add a separator to the output file $ReportEnd = "{0:dddd dd\-MM\-yyyy H:mm:ss}" -f (Get-Date) # Get and format the current date and time $ReportFooter = @("Report finished on $env:COMPUTERNAME, $ReportEnd";"") # Array with multiline footer Add-Content $OutputStr $ReportFooter # Add the footer to the output file # --------------------------- Write-Host "" # Write to console Write-Host "Sending e-mail..." -ForegroundColor "Yellow" # Write to console $MailBody = Get-Content $OutputStr | %{ "$_`r" } # Read and parse the contents of the output file $CcRecipients = Get-Content ($OutputPth + "\" + $CC) # read the contents of the file containing CC recipients $Attachment = $OutputStr # declare variable containing the path to the output file $Msg = New-Object Net.Mail.MailMessage # Create new e-mail message object $Att = New-Object Net.Mail.Attachment($Attachment) # Create new attachment object $Smtp = New-Object Net.Mail.SmtpClient($SmtpServer) # Create new smtp client object $Msg.From = $From # Add from address to the message $Msg.To.Add($To) # Add to address to the message $Msg.CC.Add($CcRecipients) # Add CC address(es) to the message $Msg.Subject = "Backup report for last $ReportingDate" # Set the message subject $Msg.Body = $MailBody # Add the bodytext to the message $Msg.Attachments.Add($Att) # Add the attachment to the message $Smtp.Send($Msg) # Send the message $Att.Dispose() # Clear memory of the attachment # --------------------------- #Write-EventLog -LogName "Scripts" -Source "Reporting_Script" -EventID 30 -Message "Backup Report: Mail Sent" -EntryType "Information" # --------------------------- # reset the colors back to default [console]::ResetColor()
PowerShellCorpus/GithubGist/rheid_6764157_raw_847fe816c0c7f08eb003a1463883a7dd0fee6eb3_CreateWebApplication%20SharePoint%202013.ps1
rheid_6764157_raw_847fe816c0c7f08eb003a1463883a7dd0fee6eb3_CreateWebApplication%20SharePoint%202013.ps1
$ver = $host | select version if ($ver.Version.Major -gt 1) {$Host.Runspace.ThreadOptions = "ReuseThread"} Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue Import-Module WebAdministration -ErrorAction SilentlyContinue ## #This Script Creates SharePoint Web Applications ## ## #Load Script Variables ## Write-Progress -Activity "Creating Web Application" -Status "Creating Script Variables" #This is the Web Application URL $WebApplicationURL = "http://Contoso.com" #This is the Display Name for the SharePoint Web Application $WebApplicationName = "Contoso Web Application" #This is the Content Database for the Web Application $ContentDatabase = "Contoso_ContentDB" #This is the Display Name for the Application Pool $ApplicationPoolDisplayName = "Contoso App Pool" #This is identity of the Application Pool which will be used (Domain\User) $ApplicationPoolIdentity = "Contoso\ContentAppPool" #This is the password of the Appliation Pool account which will be used $ApplicationPoolPassword = "Passw0rd1" #This is the Account which will be used for the Portal Super Reader Account $PortalSuperReader = "Contoso\SuperReader" #This is the Account which will be used for the Portal Super User Account $PortalSuperUser = "Contoso\SuperUser" ## #Begin Script ## $AppPoolStatus = $False Write-Progress -Activity "Creating Web Application" -Status "Checking if Web Application Already Exists" if(get-spwebapplication $WebApplicationURL -ErrorAction SilentlyContinue) { #If a web application with the specifid URL already exists, exit Write-Progress -Activity "Aborting Web Application Creation" -Status "Web Application with URL $WebApplication Already Exists" Write-Host "Aborting: Web Application $WebApplicationURL Already Exists" -ForegroundColor Red sleep 5 } else { Write-Progress -Activity "Creating Web Application" -Status "Checking if Application Pool Already Exists" #Check to see if the specified application pool alrady exists. If it exists, use the existing app pool if($AppPool = Get-SPServiceApplicationPool $ApplicationPoolDisplayName -ErrorAction SilentlyContinue) { Write-Progress -Activity "Creating Web Application" -Status "Re-Using Existing SharePoint Application Pool" Set-Variable -Name AppPoolStatus -Value "IsSharePoint" -scope "script" } else { if((Test-Path IIS:\AppPools\$ApplicationPoolDisplayName).tostring() -eq "True") { Write-Progress -Activity "Creating Web Application" -Status "Application Pool with name $ApplicationPoolDisplayName exists and is not used by SharePoint" Set-Variable -Name AppPoolStatus -Value "IsNotSharePoint" -scope "script" } } if($AppPoolStatus -eq "IsNotSharePoint") { Write-Host "Aborting: Application Pool $ApplicationPoolDisplayName already exists on the server and is not a SharePoint Application Pool" -ForegroundColor Red Write-Progress -Activity "Creating Web Application" -Status "Aborting: SharePoint Cannot use the specified Application Pool" } elseif($AppPoolStatus -eq "IsSharePoint") { #Check to see if the URL starts with HTTP or HTTPS. This can be used to determine the appropriate host header to assign if($WebApplicationURL.StartsWith("http://")) { $HostHeader = $WebApplicationURL.Substring(7) $HTTPPort = "80" } elseif($WebApplicationURL.StartsWith("https://")) { $HostHeader = $WebApplicationURL.Substring(8) $HTTPPort = "443" } Write-Progress -Activity "Creating Web Application" -Status "Application Pool $ApplicationPoolDisplayName Already Exists, Using Existing Application Pool" #Grab the existing application pool, assign it to the AppPool variable Set-Variable -Name AppPool -Value (Get-SPServiceApplicationPool $ApplicationPoolDisplayName) -scope "script" Write-Progress -Activity "Creating Web Application" -Status "Creating Web Application $WebapplicationURL" #Create a new web application using the existing parameters, assign it to the WebApp variable such that object cache user accounts can be configured $WebApp = New-SPWebApplication -ApplicationPool $ApplicationPoolDisplayName -Name $WebApplicationName -url $WebApplicationURL -port $HTTPPort -DatabaseName $ContentDatabase -HostHeader $hostHeader Write-Progress -Activity "Creating Web Application" -Status "Configuring Object Cache Accounts" #Assign Object Cache Accounts $WebApp.Properties["portalsuperuseraccount"] = $PortalSuperUser $WebApp.Properties["portalsuperreaderaccount"] = $PortalSuperReader Write-Progress -Activity "Creating Web Application" -Status "Creating Object Cache User Policies for Web Application" #Create a New Policy for the Super User $SuperUserPolicy = $WebApp.Policies.Add($PortalSuperUser, "Portal Super User Account") #Assign Full Control To the Super User $SuperUserPolicy.PolicyRoleBindings.Add($WebApp.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullControl)) #Create a New Policy for the Super Reader $SuperReaderPolicy = $WebApp.Policies.Add($PortalSuperReader, "Portal Super Reader Account") #Assign Full Read to the Super Reader $SuperReaderPolicy.PolicyRoleBindings.Add($WebApp.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullRead)) Write-Progress -Activity "Creating Web Application" -Status "Updating Web Application Properties" #Commit changes to the web application $WebApp.update() } else { Write-Progress -Activity "Creating Web Application" -Status "Creating Application Pool" #Since we have to create a new application pool, check to see if the account specified is already a managed account if(get-spmanagedaccount $ApplicationPoolIdentity) { #If the specified account is already a managed account, use that account when creating a new application pool Set-Variable -Name AppPoolManagedAccount -Value (Get-SPManagedAccount $ApplicationPoolIdentity | select username) -scope "Script" Set-Variable -Name AppPool -Value (New-SPServiceApplicationPool -Name $ApplicationPoolDisplayName -Account $ApplicationPoolIdentity) -scope "Script" } else { #If the specified account is not already a managd account create a managed account using the credentials provided $AppPoolCredentials = New-Object System.Management.Automation.PSCredential $ApplicationPoolIdentity, (ConvertTo-SecureString $ApplicationPoolPassword -AsPlainText -Force) Set-Variable -Name AppPoolManagedAccount -Value (New-SPManagedAccount -Credential $AppPoolCredentials) -scope "Script" #Create an application pool using the new managed account Set-Variable -Name AppPool -Value (New-SPServiceApplicationPool -Name $ApplicationPoolDisplayName -Account (get-spmanagedaccount $ApplicationPoolIdentity)) -scope "Script" } #Check to see if the URL starts with HTTP or HTTPS. This can be used to determine the appropriate host header to assign if($WebApplicationURL.StartsWith("http://")) { $HostHeader = $WebApplicationURL.Substring(7) $HTTPPort = "80" } elseif($WebApplicationURL.StartsWith("https://")) { $HostHeader = $WebApplicationURL.Substring(8) $HTTPPort = "443" } Write-Progress -Activity "Creating Web Application" -Status "Creating Web Application $WebapplicationURL" #Create a new web application using the existing parameters, assign it to the WebApp variable such that object cache user accounts can be configured $WebApp = New-SPWebApplication -ApplicationPool $AppPool.Name -ApplicationPoolAccount $AppPoolManagedAccount.Username -Name $WebApplicationName -url $WebApplicationURL -port $HTTPPort -DatabaseName $ContentDatabase -HostHeader $hostHeader Write-Progress -Activity "Creating Web Application" -Status "Configuring Object Cache Accounts" #Assign Object Cache Accounts $WebApp.Properties["portalsuperuseraccount"] = $PortalSuperUser $WebApp.Properties["portalsuperreaderaccount"] = $PortalSuperReader Write-Progress -Activity "Creating Web Application" -Status "Creating Object Cache User Policies for Web Application" #Create a New Policy for the Super User $SuperUserPolicy = $WebApp.Policies.Add($PortalSuperUser, "Portal Super User Account") #Assign Full Control To the Super User $SuperUserPolicy.PolicyRoleBindings.Add($WebApp.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullControl)) #Create a New Policy for the Super Reader $SuperReaderPolicy = $WebApp.Policies.Add($PortalSuperReader, "Portal Super Reader Account") #ASsign Full Read to the Super Reader $SuperReaderPolicy.PolicyRoleBindings.Add($WebApp.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullRead)) Write-Progress -Activity "Creating Web Application" -Status "Updating Web Application Properties" #Commit changes to the web application $WebApp.update() } }
PowerShellCorpus/GithubGist/hapylestat_6230302_raw_ae193d51f8a4712742535efe3f21b092f02aaefb_ps-create-object-with-properties.ps1
hapylestat_6230302_raw_ae193d51f8a4712742535efe3f21b092f02aaefb_ps-create-object-with-properties.ps1
#1. ========object $<variable> = New-Object PSObject -Property @{ <field 1> = <value> <field 2> = <value> } #2. ========hashtable $<variable> = @{ <name> = <value> }
PowerShellCorpus/GithubGist/jonwd7_9124181_raw_be94db3329a98d26405058778f971719b6cdbfd0_MSVC-build-qt-static.ps1
jonwd7_9124181_raw_be94db3329a98d26405058778f971719b6cdbfd0_MSVC-build-qt-static.ps1
#----------------------------------------------------------------------------- # # Copyright (c) 2013, Thierry Lelegard # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. # #----------------------------------------------------------------------------- <# .SYNOPSIS Build a static version of Qt for Windows. .DESCRIPTION This scripts downloads Qt source code, compiles and installs a static version of Qt. It assumes that a prebuilt Qt / MSVC environment is already installed, typically in C:\Qt. This prebuilt environment uses shared libraries. It is supposed to remain the main development environment for Qt. This script adds a static version of the Qt libraries in order to allow the construction of standalone and self-sufficient executable. This script is typically run from the Windows Explorer. Requirements: - Windows PowerShell 3.0 or higher. - 7-zip. .PARAMETER QtSrcUrl URL of the Qt source file archive. By default, use the latest identified version. .PARAMETER QtRoot Qt root. By default, C:\Qt .PARAMETER QtStaticDir Root directory where the static versions of Qt are installed. By default, $QtRoot\Static. .PARAMETER QtVersion The Qt version. By default, this script tries to extract the version number from the Qt source file name. .PARAMETER QtToolsDir The Qt tools path. By default, $QtRoot\Tools. .PARAMETER NumJobs The number of jobs to run jom.exe with. Use your # CPU cores or higher. Default 12. .PARAMETER MSVC Imports command prompt environment for this MSVC. Default 2012 .PARAMETER Arch Set to amd64 to compile with MSVC 64-bit. Default: x86 .PARAMETER ConfigureOnly Only configure .PARAMETER NoPause Do not wait for the user to press <enter> at end of execution. By default, execute a "pause" instruction at the end of execution, which is useful when the script was run from Windows Explorer. #> [CmdletBinding()] param( $QtSrcUrl = "http://download.qt-project.org/official_releases/qt/5.3/5.3.2/single/qt-everywhere-opensource-src-5.3.2.7z", $QtVersion = "5.3.2", $QtRoot = "C:\Qt", $QtStaticDir = "$QtRoot\Static", $QtToolsDir = "$QtRoot\Tools", $NumJobs = 12, $MSVC = 2013, $Arch = "x86", $Release = "debug-and-release", # Optionally "release" [switch]$ConfigureOnly = $false, [switch]$NoPause = $false ) # PowerShell execution policy. Set-StrictMode -Version 3 #Import-Module Pscx #----------------------------------------------------------------------------- # Main code #----------------------------------------------------------------------------- function Main { # Check that 7zip is installed. We use it to expand the downloaded archive. [void] (Get-7zip) $BuildName = "" # Get Qt source file name from URL. $QtSrcFileName = Split-Path -Leaf $QtSrcUrl # If Qt version is not specified on the command line, try to extract the value. if (-not $QtVersion) { $QtVersion = $QtSrcFileName -replace "`.[^`.]*$",'' $QtVersion = $QtVersion -replace 'qt-','' $QtVersion = $QtVersion -replace 'everywhere-','' $QtVersion = $QtVersion -replace 'opensource-','' $QtVersion = $QtVersion -replace 'src-','' $QtVersion = $QtVersion -replace '-src','' } Write-Output "Building static Qt version: $QtVersion" # Qt installation directory. $QtDir = "$QtStaticDir\$QtVersion" # Initialize Visual Studio environment $platform = "win32-msvc$MSVC" $BuildName = "" if ($Arch -eq "x86") { $BuildName = "msvc${MSVC}_opengl" } elseif ($Arch -eq "amd64") { $BuildName = "msvc${MSVC}_64_opengl" } else { Exit-Script "Not a valid Arch flag. Options: x86, amd64" } Set-VsVars $MSVC $Arch Write-Output "Using: $platform" Write-Output "Build: $BuildName" $QtDir += "\$BuildName" Write-Output "Install Location: $QtDir" # Build the directory tree where the static version of Qt will be installed. if (-not (Test-Path $QtRoot\src)) { Write-Output "Creating Dir: $QtRoot\src" } if (-not (Test-Path $QtDir)) { Write-Output "Creating Dir: $QtDir" } Create-Directory $QtRoot\src Create-Directory $QtDir # Download the Qt source package if not yet done. Download-File $QtSrcUrl $QtRoot\src\$QtSrcFileName # Directory of expanded packages. $QtSrcDir = "$QtRoot\src\$((Get-Item $QtRoot\src\$QtSrcFileName).BaseName)" #$clean = $false #if (Test-Path $QtSrcDir\Makefile) { # $answer = Read-Host "Makefile already exists. Clean? (Y/N)" # #Write-Output "Clean: $answer" # # if (($answer -eq "Y") -or ($answer -eq "y")) { # $clean = $true # } #} #if ( $clean ) { # Write-Output "Build will be cleaned before configure" #} # Expand archives if not yet done Expand-Archive $QtRoot\src\$QtSrcFileName $QtRoot\src $QtSrcDir # Download and Extract Jom Download-File "http://download.qt-project.org/official_releases/jom/jom.zip" "$QtToolsDir\jom.zip" Expand-Archive "$QtToolsDir\jom.zip" "$QtToolsDir\jom" "$QtToolsDir\jom\jom.exe" # Patch Qt's mkspecs for static build. $File = "$QtSrcDir\qtbase\mkspecs\$platform\qmake.conf" if (-not (Select-String -Quiet -SimpleMatch -CaseSensitive "# [QT-STATIC-PATCH]" $File)) { Write-Output "Patching $File ..." Copy-Item $File "$File.orig" @" # [QT-STATIC-PATCH] DEFINES += QT_STATIC_BUILD "@ | Out-File -Append $File -Encoding Ascii } else { #Write-Output "Patch already exists" } # Took these out because that links MSVC statically #QMAKE_CFLAGS_RELEASE = -O2 -MT #QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO += -O2 -MT -Zi #QMAKE_CFLAGS_DEBUG = -Zi -MTd # Set a clean path. $env:Path += ";$env:SystemRoot\system32;$env:SystemRoot;$QtToolsDir\jom" # Force English locale to avoid weird effects of tools localization. $env:LANG = "en" # Set environment variable QT_INSTALL_PREFIX. Documentation says it should be # used by configure as prefix but this does not seem to work. So, we will # also specify -prefix option in configure. $env:QT_INSTALL_PREFIX = $QtDir # Configure, compile and install Qt. Push-Location $QtSrcDir # Test if build dir needs cleaned #if ( $clean ) { # jom clean # # $exit = Read-Host "Clean finished. Exit? (Y/N)" # # if (($exit -eq "Y") -or ($exit -eq "y")) { # Pop-Location # Exit-Script # } #} cmd /c "configure.bat -mp -static -$Release -platform `"$platform`" -prefix `"$QtDir`" -qt-zlib -qt-pcre -qt-libpng -qt-libjpeg -qt-freetype -no-angle -opengl desktop -qt-sql-sqlite -no-qml-debug -no-openssl -no-dbus -wmf-backend -audio-backend -opensource -make libs -make tools -nomake examples -nomake tests" if ( -not $ConfigureOnly ) { jom -j $NumJobs jom install } Pop-Location if ( $ConfigureOnly ) { Exit-Script "Configure Done" } # Patch Qt's installed mkspecs for static build of application. $File = "$QtDir\mkspecs\$platform\qmake.conf" @" CONFIG += static "@ | Out-File -Append $File -Encoding Ascii # Patch Qt's .prl files Write-Output "Patching .prl files in $QtDir" $findDir = "$QtSrcDir\qtbase\lib" # "C:\Qt\src\qt-everywhere-opensource-src-5.2.1\qtbase\lib" $findDirEsc = $findDir -replace "\\", "\\\\" #4 are necessary for the find string $repDir = "$QtDir\lib" # "C:\Qt\Static\5.2.1\msvc2012_opengl\lib" $repDirEsc = $repDir -replace "\\", "\\" #Write-Output $findDirEsc #Write-Output $repDirEsc Get-ChildItem $QtDir *.prl -recurse | Foreach-Object { $c = ($_ | Get-Content) $c = $c -replace "$findDirEsc", "$repDirEsc" [IO.File]::WriteAllText($_.FullName, ($c -join "`r`n")) } #Exit-Script "Configure Done" # Create qt.conf Write-Output "Creating qt.conf in $QtDir\bin" $QtDirFwd = $QtDir -replace "\\", "/" $confFile = "$QtDir\bin\qt.conf" @" [Paths] Prefix=$QtDirFwd Libraries=$QtDirFwd/lib "@ | Out-File $confFile -Encoding Ascii # Copy .pdb files if ( $Release -like 'debug*' ) { Copy-Item $findDir\*.pdb $repDir Copy-Item $findDir\..\plugins\platforms\*.pdb $repDir\..\plugins\platforms } Exit-Script } #----------------------------------------------------------------------------- # A function to exit this script. The Message parameter is used on error. #----------------------------------------------------------------------------- function Exit-Script ([string]$Message = "") { $Code = 0 if ($Message -ne "") { Write-Output "ERROR: $Message" $Code = 1 } if (-not $NoPause) { pause } exit $Code } #----------------------------------------------------------------------------- # Silently create a directory. #----------------------------------------------------------------------------- function Create-Directory ([string]$Directory) { [void] (New-Item -Path $Directory -ItemType "directory" -Force) } #----------------------------------------------------------------------------- # Download a file if not yet present. # Warning: If file is present but incomplete, do not download it again. #----------------------------------------------------------------------------- function Download-File ([string]$Url, [string]$OutputFile) { $FileName = Split-Path $Url -Leaf if (-not (Test-Path $OutputFile)) { # Local file not present, start download. Write-Output "Downloading $Url ..." try { $webclient = New-Object System.Net.WebClient $webclient.DownloadFile($Url, $OutputFile) } catch { # Display exception. $_ # Delete partial file, if any. if (Test-Path $OutputFile) { Remove-Item -Force $OutputFile } # Abort Exit-Script "Error downloading $FileName" } # Check that the file is present. if (-not (Test-Path $OutputFile)) { Exit-Script "Error downloading $FileName" } } } #----------------------------------------------------------------------------- # Get path name of 7zip, abort if not found. #----------------------------------------------------------------------------- function Get-7zip { $Exe = "C:\Program Files\7-Zip\7z.exe" if (-not (Test-Path $Exe)) { $Exe = "C:\Program Files (x86)\7-Zip\7z.exe" } if (-not (Test-Path $Exe)) { Exit-Script "7-zip not found, install it first, see http://www.7-zip.org/" } $Exe } #----------------------------------------------------------------------------- # Expand an archive file if not yet done. #----------------------------------------------------------------------------- function Expand-Archive ([string]$ZipFile, [string]$OutDir, [string]$CheckFile) { # Check presence of expected expanded file or directory. if (-not (Test-Path $CheckFile)) { Write-Output "Expanding $ZipFile ..." & (Get-7zip) x $ZipFile "-o$OutDir" | Select-String -Pattern "^Extracting " -CaseSensitive -NotMatch if (-not (Test-Path $CheckFile)) { Exit-Script "Error expanding $ZipFile, $OutDir\$CheckFile not found" } } } function Get-Batchfile ($file, $params) { $cmd = "`"$file`" $params & set" cmd /c $cmd | Foreach-Object { $p, $v = $_.split('=') Set-Item -path env:$p -value $v } } function Set-VsVars($vsYear, $arch) { $vstools = "" switch ($vsYear) { 2013 { $vstools = "$env:VS120COMNTOOLS\..\..\vc\vcvarsall.bat" } 2015 { $vstools = "$env:VS140COMNTOOLS\..\..\vc\vcvarsall.bat" } } #$batchFile = [System.IO.Path]::Combine($vstools, "vsvars32.bat") if (-not (Test-Path $vstools)) { Exit-Script "Visual Studio environment could not be found." } Get-Batchfile -file $vstools -params $arch Write-Host -ForegroundColor 'Yellow' "VsVars has been loaded from: $vstools ($arch)" } #----------------------------------------------------------------------------- # Execute main code. #----------------------------------------------------------------------------- . Main
PowerShellCorpus/GithubGist/jonnii_4271442_raw_e9f8b646c9e9117a1c0eab79b0893ae90a8c3b4e_quick-restart.ps1
jonnii_4271442_raw_e9f8b646c9e9117a1c0eab79b0893ae90a8c3b4e_quick-restart.ps1
$workingDirectory = $args[0] $machine = $args[1] $environment = $args[2] $configuration = $args[3] Set-Location $workingDirectory # read the version file, which indicates which version we're going to deploy $versionFile = resolve-path ../Version $version = Get-Content $versionFile Write-Host "Deploying $version" # copy the files up into the share $applicationName = $configuration['applicationName'] $copyLocation = "\\$machine\$applicationName\$environment\ComponentName\$version" robocopy .\..\targets\upload-location $copyLocation /MIR /Z /MT:88 Write-Host "Copying $applicationName/$environment/ComponentName/$version to $machine" $remoteExecutableLocation = "c:\$applicationName\$environment\ComponentName\$version" $serviceInstallerName = $configuration['serviceInstallerExecutable'] function InstallService ($p,$s,$e,$v) { $stop = "$p\$s stop --environment=$e" $uninstall = "$p\$s uninstall --environment=$e" $install = "$p\$s install --environment=$e" $start = "$p\$s start --environment=$e" $serviceName = "YourApp.Service.Name$" + $e $service = Get-WmiObject -Class Win32_Service -Filter "Name='$serviceName'" if ($service) { stop-service $serviceName $servicePath = "HKLM:\System\CurrentControlSet\services\YourApp.Service.Name`$$e\" $description = "YourApp.Service.Name $e / $v" $path = "`"$p\$s`" -instance:$e -displayname `"YourApp.Service.Name (Instance: $e)`" -servicename:YourApp.Service.Name" Set-ItemProperty -path $servicePath -name Description -value "$description" Set-ItemProperty -path $servicePath -name ImagePath -value "$path" start-service $serviceName } else { invoke-expression $install invoke-expression $start } } if($machine -eq 'localhost') { InstallService $remoteExecutableLocation $serviceInstallerName $environment $version } else { invoke-command ` -ScriptBlock ${function:InstallService} ` -computername $machine ` -ArgumentList $remoteExecutableLocation, $serviceInstallerName, $environment, $version } #clean up any old deployed versions $numVersions = (ls \\$machine\$applicationName\$environment\ComponentName).length $maxVersions = $configuration['numPreviousCopiesToKeep'] if($numVersions -gt $maxVersions){ $numVersionsToRemove = $numVersions - $maxVersions Write-Host "Cleaning up deployment directory, there are $numVersions versions available. Removing $numVersionsToRemove versions." gci \\$machine\$applicationName\$environment\ComponentName | where {$_.Name -ne $version } | sort { $_.Name -as [Version] } | select -first $numVersionsToRemove | ri -r }
PowerShellCorpus/GithubGist/alienone_34a40dc03653f9af3bc6_raw_08905b6a58d65984f72539f46b66352c2cad5f07_get_status.ps1
alienone_34a40dc03653f9af3bc6_raw_08905b6a58d65984f72539f46b66352c2cad5f07_get_status.ps1
# Global Variables $LOGPATH = "C:\Temp" $PROCESSCSV = $LOGPATH + "connector_state.csv" Function CheckRemoteConnectorState{ $count = 0 $timestamp = $((get-date).ToString("yyyyMMddThhmmss")) $uuid = Get-Random -minimum 1 -maximum 9999 $username = "username\password" $secure_file = "C:\Temp\securestring.txt" $server_array = ("jello1", "jello2", "jello3", "jello4", "jello5") If(!(Test-Path $secure_file)){$create_password = (Get-Credential -Credential $username).Password | ` ConvertFrom-SecureString | Out-File $secure_file} $password = cat "C:\Temp\securestring.txt" | convertto-securestring $credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password $QueryProcessTable = {(gwmi win32_service|?{$_.name -like "*arc_*"})} foreach ($server in $server_array) { $ps_session = New-PSSession -ComputerName $server -Credential $credential foreach ($process in Invoke-Command -Session $ps_session -ScriptBlock $QueryProcessTable -AsJob | Wait-Job | Receive-Job){ If ($process.State -eq 'Running'){ $str_array = $process.pathname.split(' ')[0] $pos = $str_array.IndexOf("\current") $processpath = $str_array.SubString(0, $pos) + "\current\" $arc_home_path = $processpath + "user\agent\" $path_hash = Invoke-Command -Session $ps_session -ScriptBlock {dir $args[0] *xml} -ArgumentList $arc_home_path $xml_file = $arc_home_path + $path_hash.Name [xml]$xml_content = Invoke-Command -Session $ps_session -ScriptBlock {Get-Content $args[0]} -ArgumentList $xml_file $agentid = $xml_content.ExtendedConfig.AgentId $agentlocation = $xml_content.ExtendedConfig.AgentLocation $agentname = $xml_content.ExtendedConfig.AgentName $agenttype = $xml_content.ExtendedConfig.AgentType $agentversion = $xml_content.ExtendedConfig.AgentVersion $devicelocation = $xml_content.ExtendedConfig.DeviceLocation $drive_mapped = "Z" $drive_path = “\\jello\network\InfoSec\SIM\SCCM Custom Code for Agents\AGENTPROPERTIES\” Invoke-Command -Session $ps_session -ScriptBlock {New-PSDrive –Name "Z" –PSProvider FileSystem –Root “\\jello\network\InfoSec\SIM\SCCM Custom Code for Agents\AGENTPROPERTIES\”} $agent_properties = $processpath + "user\agent\agent.properties" $new_filename = $process.PSComputerName + "-" + $count + "-" + $timestamp + "-" + $uuid + "-agent.properties" Invoke-Command -Session $ps_session -ScriptBlock {Copy-Item $args[0] -Destination $args[1]} -ArgumentList $agent_properties, $drive_mapped Invoke-Command -Session $ps_session -ScriptBlock {Remove-PSDrive "Z"} $count++ $pshashobj = New-Object PsObject -Property @{DateTime = $timestamp; ComputerName = $process.PSComputerName; UUID = $uuid; ProcessName = $process.Name; ` ProcessState = $process.State; ProcessStatus = $process.Status; AgentPath = $agent_properties; ` AgentId = $agentid; AgentLocation = $agentlocation; AgentName = $agentname; AgentType = $agenttype; ` AgentVersion = $agentversion; DeviceLocation = $devicelocation} $pshashobj | export-csv –Path $PROCESSCSV -Append } Exit-PSSession } } } Function MainFunction{ CheckRemoteConnectorState } MainFunction
PowerShellCorpus/GithubGist/sovanesyan_3180872_raw_85c75d57b6dd88c23ef667c9fe346d370e5c95a8_gistfile1.ps1
sovanesyan_3180872_raw_85c75d57b6dd88c23ef667c9fe346d370e5c95a8_gistfile1.ps1
# Need to load MSBuild assembly if it's not loaded yet. Add-Type -AssemblyName 'Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' # Grab the loaded MSBuild project for the project $msbuild = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName) | Select-Object -First 1 # Make the path to the targets file relative. $projectUri = new-object Uri('file://' + $project.FullName) $targetUri = new-object Uri('file://' + $targetsFile) $relativePath = $projectUri.MakeRelativeUri($targetUri).ToString().Replace([System.IO.Path]::AltDirectorySeparatorChar, [System.IO.Path]::DirectorySeparatorChar) $existsCondition = "Exists('" + $relativePath + "')" #Add the enhancer item definition # Add the import $importElement = $msbuild.Xml.AddImport($relativePath) $importElement.Condition = $existsCondition #hook the error task $beforeBuildTask = $msbuild.Xml.Targets | Where {$_.Name -eq "BeforeBuild"}| Select-Object -First 1 if( $beforeBuildTask -eq $null) { $beforeBuildTask = $msbuild.Xml.AddTarget("BeforeBuild") } $errorTask = $hookTarget.AddTask("Error") $errorTask.SetParameter("Text", "SomeText") # Save the project $project.Save()