full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/sheeeng_6932419_raw_c0f8e966aee07bd19e6e820960897b9cd6cfec98_ListGUIDs.ps1
sheeeng_6932419_raw_c0f8e966aee07bd19e6e820960897b9cd6cfec98_ListGUIDs.ps1
######################################################################## # File : ListGUIDs.ps1 # Version : 1.0.0 # Purpose : List globally unique identifier (GUID) of programs installed. # Synopsis: # Usage : .\ListGUIDs.ps1 # Author: Leonard Lee <[email protected]> ######################################################################## # References: # Filtering and Formatting Data # http://technet.microsoft.com/en-us/magazine/cc162469.aspx # http://technet.microsoft.com/en-us/magazine/2007.04.powershell.aspx ######################################################################## $uninstallRegistryKey = Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall $programsInstalled = $uninstallRegistryKey | ForEach-Object {Get-ItemProperty $_.PsPath} Foreach ($program in $programsInstalled) { #Write-Host $programsInstalled.Displayname $programsInstalled.ModifyPath $programsInstalled | Select DisplayName, ModifyPath }
PowerShellCorpus/GithubGist/Dan1el42_970e1d43b69baa9dfdfe_raw_55eb98f6b06c79f7eb993c0988003c1de90735f9_Copy-ActiveSMSEncryptionCertificate.ps1
Dan1el42_970e1d43b69baa9dfdfe_raw_55eb98f6b06c79f7eb993c0988003c1de90735f9_Copy-ActiveSMSEncryptionCertificate.ps1
<# .SYNOPSIS Copy the active SMS encryption certificate to the My store .DESCRIPTION Copy the active SMS encryption certificate to the My store to enable access to the private key for the DSC Local Configuration Manager to decrypt credentials #> Param ( [String] $SMSCertificateFriendlyName = 'SMS Encryption Certificate' ) # Get SMS encryption certificates sorted from SMS store $SMSStoreCertsArray = @(Get-ChildItem -Path Cert:\LocalMachine\SMS | Where-Object { $_.FriendlyName -eq $SMSCertificateFriendlyName } | Sort-Object -Property NotAfter -Descending) # Copy most recent certificate from SMS to My store and remove old (inactive) certificates $ActiveCertificate = $null for ($i = 0; $i -lt $SMSStoreCertsArray.Count; $i++) { $Certificate = $SMSStoreCertsArray[$i] if ($i -eq 0) { $ActiveCertificate = $Certificate # Only copy if certificate does not exist in My store if (-not (Test-Path -Path "Cert:\LocalMachine\My\$($Certificate.Thumbprint)")) { $Store = Get-Item -Path Cert:\LocalMachine\My $Store.Open('ReadWrite') try { $Store.Add($ActiveCertificate) } finally { $Store.Close() } } } else { $Certificate | Remove-Item -Force } } # Remove old (inactive) SMS encryption certificates from the My store but leave the active certificate in-place if ($ActiveCertificate) { # Get SMS encryption certificates from My/Personal store $MyStoreCertsArray = @(Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.FriendlyName -eq $SMSCertificateFriendlyName }) foreach ($Certificate in $MyStoreCertsArray) { if ($Certificate.Thumbprint -ne $ActiveCertificate.Thumbprint) { $Certificate | Remove-Item -Force } } }
PowerShellCorpus/GithubGist/andreagx_9067652_raw_e41a9d42848b8ada100ffab3fce82212bce3e800_Signature1_2.ps1
andreagx_9067652_raw_e41a9d42848b8ada100ffab3fce82212bce3e800_Signature1_2.ps1
###########################################################################” # AUTHOR: Jan Egil Ring # Modifications by Darren Kattan # # COMMENT: Script to create an Outlook signature based on user information from Active Directory. # Adjust the variables in the “Custom variables”-section # Create an Outlook-signature from Microsoft Word (logo, fonts etc) and copy this signature to \\domain\NETLOGON\sig_files\$CompanyName\$CompanyName.docx # This script supports the following keywords: # DisplayName # Title # Email # # See the following blog-posts for more information: # http://blog.powershell.no/2010/01/09/outlook-signature-based-on-user-information-from-active-directory # http://www.immense.net/deploying-unified-email-signature-template-outlook # # Tested on Office 2003, 2007 and 2010 # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 09.01.2010 – Initial release # 1.1 11.09.2010 – Modified by Darren Kattan # 1.2 11.09.2012 - Modified by Andrea Gallazzi # - Removed bookmarks. Now uses simple find and replace for DisplayName, Title, and Email. # - Email address is generated as a link # - Signature is generated from a single .docx file # - Removed version numbers for script to run. Script runs at boot up when it sees a change in the “Date Modified” property of your signature template. # ************* 1.2 ************** # - Fix signature txt format # - Add Variables TelePhoneNumber,description, facsimileTelephoneNumber, mobile, department # - Add support for OWA, the script now generate the html file by username and copy it on Exchange Server shared Directory for succeeding import (line 64) # - Changed "wdFormatHTML" with "wdFormatFilteredHTML" this last command save only HTML whitout Office TAGs. This is important because Exchange Server support only 8k for OWA Signs. # # On Exchange Server share a folder with name "Signatures" and set the write permissions to "Authenticated Users" ###########################################################################” ###########################################################################” # # COMMENT: Script to create an Outlook signature based on user information from Active Directory. # Adjust the variables in the “Custom variables”-section # Create an Outlook-signature from Microsoft Word (logo, fonts etc) and copy this signature to \\domain\NETLOGON\sig_files\$CompanyName\$CompanyName.docx # This script supports the following keywords: # DisplayName # Title # Email # # VERSION HISTORY: # 1.0 – Initial release # # # ###########################################################################” #Custom variables $CompanyName='company' $DomainName='domain.local' #test path and crete folder $TARGETDIR = $env:APPDATA + "\Microsoft\Signatures" if(!(Test-Path -Path $TARGETDIR )){ New-Item -ItemType directory -Path $TARGETDIR } $SigSource ="\\$DomainName\netlogon\sig_files\$CompanyName" $ForceSignatureNew=$true #When the signature are forced the signature are enforced as default signature for new messages the next time the script runs. 0 = no force, 1 = force $ForceSignatureReplyForward=$true #When the signature are forced the signature are enforced as default signature for reply/forward messages the next time the script runs. 0 = no force, 1 = force #Environment variables $AppData=$env:appdata $SigPath='\Microsoft\Signatures' $LocalSignaturePath=$AppData+$SigPath $RemoteSignaturePathFull="$SigSource\$CompanyName.docx" $ExchPath='\\exchangeserver\Signatures\' #Get Active Directory information for current user $UserName = $env:username $Searcher=[adsisearcher]"(&(objectCategory=User)(samAccountName=$UserName))" $ADUserPath=$Searcher.FindOne() $ADUser=$ADUserPath.GetDirectoryEntry() $ADDisplayName = $ADUser.DisplayName $ADEmailAddress = $ADUser.mail $ADTitle = $ADUser.title $ADTelePhoneNumber = $ADUser.telephoneNumber $ADdescription = $ADuser.description $ADFax = $ADuser.facsimileTelephoneNumber $ADMobile = $ADuser.mobile $ADDepartment = $ADuser.department #Setting registry information for the current user $CompanyRegPath="HKCU:\Software\$CompanyName" if(-not(Test-Path $CompanyRegPath)){ New-Item -path “HKCU:\Software” -name $CompanyName } if(-not(Test-Path "$CompanyRegPath\Outlook Signature Settings")){ New-Item -path $CompanyRegPath -name 'Outlook Signature Settings' } #$SigVersion=(gci $RemoteSignaturePathFull).LastWriteTime #When was the last time the signature was written $ForcedSignatureNew=(Get-ItemProperty "$CompanyRegPath\Outlook Signature Settings").ForcedSignatureNew $ForcedSignatureReplyForward=(Get-ItemProperty "$CompanyRegPath\Outlook Signature Settings").ForcedSignatureReplyForward $SignatureVersion=(Get-ItemProperty "$CompanyRegPath\Outlook Signature Settings").SignatureVersion Set-ItemProperty "$CompanyRegPath\Outlook Signature Settings" -name SignatureSourceFiles -Value $SigSource $SignatureSourceFiles=(Get-ItemProperty "$CompanyRegPath\Outlook Signature Settings").SignatureSourceFiles # create this once to make release easier $MSWord = New-Object -com word.application #Forcing signature for new messages if enabled if ($ForcedSignatureNew){ #Set company signature as default for New messages $MSWord.EmailOptions.EmailSignature.NewMessageSignature=$CompanyName } #Forcing signature for reply/forward messages if enabled if ($ForcedSignatureReplyForward){ #Set company signature as default for Reply/Forward messages $MSWord.EmailOptions.EmailSignature.ReplyMessageSignature=$CompanyName } #Copying signature sourcefiles and creating signature if signature-version are different from local version if ($SignatureVersion -ne $SigVersion){ #Copy signature templates from domain to local Signature-folder Copy-Item “$SignatureSourceFiles\*” $LocalSignaturePath -Recurse -Force $ReplaceAll = 2 $FindContinue = 1 $MatchCase = $False $MatchWholeWord = $True $MatchWildcards = $False $MatchSoundsLike = $False $MatchAllWordForms = $False $Forward = $True $Wrap = $FindContinue $Format = $False #assembly load Add-Type -Assembly Microsoft.Office.Interop.Word # [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Word.WdsaveFormat") #Insert variables from Active Directory to rtf signature-file $fullPath="$LocalSignaturePath\$CompanyName.docx" $MSWord.Documents.Open($fullPath) $FindText = “DisplayName” $ReplaceText = $ADDisplayName.ToString() $MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll ) $FindText = “Title” $ReplaceText = $ADTitle.ToString() $MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll ) # $MSWord.Selection.Find.Execute(“PostaEL”) $FindText = “PostaEL” $ReplaceText = $ADEmailAddress.ToString() $MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll ) $FindText = “TelePhoneNumber” $ReplaceText = $ADTelePhoneNumber.ToString() $MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll ) $FindText = “facsimileTelephoneNumber” $ReplaceText = $ADFax.ToString() $MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll ) $FindText = “BlogIQ” $ReplaceText = $ADDepartment.ToString() $MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll ) $MSWord.ActiveDocument.Save() $saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], “wdFormatFilteredHTML”); #$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], “wdFormatFilteredHTML”); [ref]$BrowserLevel = “microsoft.office.interop.word.WdBrowserLevel” -as [type] $MSWord.ActiveDocument.WebOptions.OrganizeInFolder = $true $MSWord.ActiveDocument.WebOptions.UseLongFileNames = $true $MSWord.ActiveDocument.WebOptions.BrowserLevel = $BrowserLevel::wdBrowserLevelMicrosoftInternetExplorer6 $path = $LocalSignaturePath+’\'+$CompanyName+”.htm” $MSWord.ActiveDocument.saveas($path, $saveFormat) $MSWord.ActiveDocument.saveas([ref]$path, [ref]$saveFormat) # Save html file with username from AD (OWA) $pathOWA = $LocalSignaturePath+’\'+$UserName+”.htm” $MSWord.ActiveDocument.saveas($pathOWA, $saveFormat) Copy-Item “$LocalSignaturePath\$UserName.htm” "$ExchPath" -Recurse -Force # Saving rtf and txt $path = "$LocalSignaturePath\$CompanyName.rtf" $MSWord.ActiveDocument.SaveAs($path, [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatRTF) $MSWord.ActiveDocument.SaveAs([ref]$path, [ref][Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatRTF) $path = "$LocalSignaturePath\$CompanyName.rtf" $MSWord.ActiveDocument.SaveAs($path, [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatText) $MSWord.ActiveDocument.SaveAs([ref]$path, [ref][Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatText) $path = "$LocalSignaturePath\$CompanyName.txt" $MSWord.ActiveDocument.SaveAs($path, [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatText) $MSWord.ActiveDocument.SaveAs([ref] $path, [ref][Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatText) } $MSWord.ActiveDocument.Close() $MSWord.Quit() [System.Runtime.Interopservices.Marshal]::ReleaseComObject($MSWord) Remove-Variable MSWord #Stamp registry-values for Outlook Signature Settings if they doesn`t match the initial script variables. Note that these will apply after the second script run when changes are made in the “Custom variables”-section. if ($ForcedSignatureNew -eq $ForceSignatureNew){ Set-ItemProperty $CompanyRegPath’\Outlook Signature Settings’ -name ForcedSignatureNew -Value $ForceSignatureNew } if ($ForcedSignatureReplyForward -ne $ForceSignatureReplyForward){ Set-ItemProperty "$CompanyRegPath\Outlook Signature Settings" -name ForcedSignatureReplyForward -Value $ForceSignatureReplyForward } if($SignatureVersion -ne $SigVersion){ Set-ItemProperty "$CompanyRegPath\Outlook Signature Settings" -name SignatureVersion -Value $SigVersion }
PowerShellCorpus/GithubGist/peaeater_9650933_raw_7d43a32e5695d68a7dc5fb9a17a27d526fd7530e_raw-ia.ps1
peaeater_9650933_raw_7d43a32e5695d68a7dc5fb9a17a27d526fd7530e_raw-ia.ps1
# processes Internet Archive packages, producing per page: 1 txt, 1 ocrxml, 1 jpg # requires djvulibre, imagemagick param( [string]$indir = ".", [string]$outbase = $indir ) [Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") function WebSafe([string]$s) { return $s.ToLowerInvariant().Replace(" ", "-") } $files = ls "$indir\*.*" -include *.djvu foreach ($file in $files) { $djvu = $file.FullName # extract .txt per djvu page & .\djvu2txt.ps1 -in "$djvu" # extract hidden text .xml per djvu page & .\djvu2xml.ps1 -in "$djvu" # create dir for jpgs based on djvu filename $jpgdir = ('{0}\{1}' -f $outbase, (WebSafe($file.BaseName))) if (!(test-path $jpgdir)) { mkdir $jpgdir } # extract .jp2 a la .NET 4 $zip = get-item (('{0}\{1}_jp2.zip' -f $file.DirectoryName, $file.BaseName)) $jp2dir = ('{0}\{1}_jp2' -f $file.DirectoryName, $file.BaseName) if (!(test-path $jp2dir)) { [System.IO.Compression.ZipFile]::ExtractToDirectory($zip, $file.DirectoryName) } # rename .jp2 to just page #s $jp2s = ls "$jp2dir" foreach ($jp2 in $jp2s) { $pattern = ('{0}_0*' -f $file.BaseName) $newname = [System.Text.RegularExpressions.Regex]::Replace($jp2.Name, $pattern, "") ren -path $jp2.FullName -newname $newname } # delete scan job marker images del ('{0}\.jp2' -f $jp2dir) del ('{0}\{1}' -f $jp2dir, $newname) # convert .jp2 to .jpg & .\jp22jpg.ps1 -size 1000 -in "$jp2dir" -outdir $jpgdir # clean up del -Recurse $jp2dir # convert IA metadata to manifest $metadata = ('{0}\{1}_meta.xml' -f $file.DirectoryName, $file.BaseName) $manifest = ('{0}\manifest.xml' -f $file.DirectoryName) $source = [System.IO.Directory]::GetParent($file.DirectoryName).BaseName & .\meta2manifest.ps1 -in $metadata -out $manifest -source $source }
PowerShellCorpus/GithubGist/brunomlopes_165857_raw_07fd19d556d2d4c6863e4ddf6e78b0cbe8a97f2d_archive_downloads.ps1
brunomlopes_165857_raw_07fd19d556d2d4c6863e4ddf6e78b0cbe8a97f2d_archive_downloads.ps1
$base_downloads_dir = "S:\downloads\" $base_archive_dir = "S:\downloads\archive" if(-not (Test-Path $base_archive_dir)) { [void] (mkdir $base_archive_dir) } $to_archive_files = get-childitem $base_downloads_dir | ? { $_.Name -ne "archive" -and $_.CreationTime -lt (Get-Date).AddDays(-1) } foreach($to_archive in $to_archive_files){ $name = $to_archive.Name $i = 1 while ( Test-Path "$base_archive_dir\$($name)" ) { $name = "$($to_archive.BaseName) ($i)$($to_archive.Extension)" $i+=1; } echo "Moving $($to_archive.FullName) to $base_archive_dir\$name" Move-Item "$($to_archive.FullName)" "$base_archive_dir\$name" }
PowerShellCorpus/GithubGist/pohatu_7031323_raw_6e7a2fe63c6f2f269ea8f62548a039e9681c5687_RockPaperScissors.ps1
pohatu_7031323_raw_6e7a2fe63c6f2f269ea8f62548a039e9681c5687_RockPaperScissors.ps1
# A simple Rock, Paper Scissors Game in Powershell by pohatu # Uses very cool Select-Item function by James O'Neill # Presented here: http://blogs.technet.com/b/jamesone/archive/2009/06/24/how-to-get-user-input-more-nicely-in-powershell.aspx # # Also uses a clever trick to make remainder act like modulo for negative numbers presented by StackOverflow user polygenelubricants # here: http://stackoverflow.com/questions/3417183/modulo-of-negative-numbers/3417598#3417598 # You can see the difference between columns labeled Excel:(b-a)%3 and PS:(b-a)%3 column # # # p1 p2 a-b xls:a-b%3 result PS:(b-a)%3 # rock 0 rock 0 0 0 draw 0 # rock 0 paper 1 -1 2 b 1 # rock 0 scissors 2 -2 1 a 2 # paper 1 rock 0 1 1 a -1 # paper 1 paper 1 0 0 draw 0 # paper 1 scissors 2 -1 2 b 1 # scissors 2 rock 0 2 2 b -2 # scissors 2 paper 1 1 1 a -1 # scissors 2 scissors 2 0 0 draw 0 $RPS=@{Rock=0; Paper=1; Scissors=2;} function Get-RPSWinner($p1, $p2){ #returns 1 if p1 wins, 2 if p2 wins, 0 if tie. #See table above. Hack due to remainder()<>mod(). return ($(((($p1-$p2)%3)+3)%3)) } function TestGet-RPSWinner(){ #Draw $(Get-RPSWinner $RPS.Rock $RPS.Rock) -eq 0 $(Get-RPSWinner $RPS.Paper $RPS.Paper) -eq 0 $(Get-RPSWinner $RPS.Scissors $RPS.Scissors) -eq 0 #Player 1 wins $(Get-RPSWinner $RPS.Paper $RPS.Rock) -eq 1 $(Get-RPSWinner $RPS.Scissors $RPS.Paper) -eq 1 $(Get-RPSWinner $RPS.Rock $RPS.Scissors) -eq 1 #Player 2 wins $(Get-RPSWinner $RPS.Rock $RPS.Paper) -eq 2 $(Get-RPSWinner $RPS.Paper $RPS.Scissors) -eq 2 $(Get-RPSWinner $RPS.Scissors $RPS.Rock) -eq 2 } ## ## Select-Item (C) James O'Neill ## http://blogs.technet.com/b/jamesone/archive/2009/06/24/how-to-get-user-input-more-nicely-in-powershell.aspx ## Function Select-Item { <# .Synopsis Allows the user to select simple items, returns a number to indicate the selected item. .Description Produces a list on the screen with a caption followed by a message, the options are then displayed one after the other, and the user can one. Note that help text is not supported in this version. .Example PS> select-item -Caption "Configuring RemoteDesktop" -Message "Do you want to: " -choice "&Disable Remote Desktop", "&Enable Remote Desktop","&Cancel" -default 1 Will display the following Configuring RemoteDesktop Do you want to: [D] Disable Remote Desktop [E] Enable Remote Desktop [C] Cancel [?] Help (default is "E"): .Parameter Choicelist An array of strings, each one is possible choice. The hot key in each choice must be prefixed with an & sign .Parameter Default The zero based item in the array which will be the default choice if the user hits enter. .Parameter Caption The First line of text displayed .Parameter Message The Second line of text displayed #> Param( [String[]]$choiceList, [String]$Caption="Please make a selection", [String]$Message="Choices are presented below", [int]$default=0 ) $choicedesc = New-Object System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription] $choiceList | foreach { $choicedesc.Add((New-Object "System.Management.Automation.Host.ChoiceDescription" -ArgumentList $_))} $Host.ui.PromptForChoice($caption, $message, $choicedesc, $default) } function PlayGame() { do { #$human = Read-Host -Prompt "Rock [0], Paper[1] or Scissors[2]?" $human = Select-Item -Caption "Rock Paper Scissors" -Message "Choose Rock, Paper or Scissors" -choiceList "&Rock", "&Paper", "&Scissors" $computer = $RPS.Values | Get-Random write-host "You chose $($($RPS.Keys)[$human])" write-host "Computer chose $($($RPS.Keys)[$computer])" switch($(Get-RPSWinner $human $computer)) { 0 {$caption="Tie Game."; $msg = "$caption`n$($($RPS.Keys)[$computer]) ties $($($RPS.Keys)[$human]).";} 1 {$caption="You Won."; $msg = "$caption`n$($($RPS.Keys)[$human]) beats $($($RPS.Keys)[$computer]).";} 2 {$caption="You Lost."; $msg = "$caption`n$($($RPS.Keys)[$computer]) beats $($($RPS.Keys)[$human]).";} } write-host $msg $playAgain = Select-Item -Caption "$caption" -Message $($msg + "`nPlay Again?") -choiceList "&No", "&Yes" }while ($playAgain) } TestGet-RPSWinner PlayGame
PowerShellCorpus/GithubGist/pjmagee_5659973_raw_990df12fe852523ea6946a8754c5e7c961073df5_creationdate.ps1
pjmagee_5659973_raw_990df12fe852523ea6946a8754c5e7c961073df5_creationdate.ps1
# sets the folder creation date to the specified date variable # version 0.0.1 # author: Patrick Magee ####################### $choice = "" $dir = "" $date = [datetime]::Today while ($choice -notmatch "[y|n]") { $choice = Read-Host "Set creation date? (Y/N)" if($choice -eq "y") { while(-not [System.IO.Directory]::Exists($dir)) { $dir = Read-Host "Enter valid directory. e.g 'D:\videos\Movies'" } Write-Host "Listing directories created in the past..." -ForegroundColor Green $total = (Get-ChildItem $dir | Where-Object { $_.CreationTime -lt $date }).Count Get-ChildItem $dir | Where-Object { $_.CreationTime -lt $date } | ForEach-Object { Write-Host ('{0} ({1})' -f $_.Name, $_.CreationTime) -ForegroundColor Red } $choice = "" While ($choice -notmatch "[y|n]") { $choice = read-host "Are you sure you want to set the creation date on $total items to $date" + "? (Y/N)" } if($choice -eq "y"){ Get-ChildItem $dir | where { $_.CreationTime -lt $date } | ForEach-Object { $_.CreationTime = $date } Write-Host 'Complete.' -ForegroundColor Red } else { Write-Host "Cancelled." -ForegroundColor Red } } else { Write-Host "Cancelled." -ForegroundColor Red } }
PowerShellCorpus/GithubGist/mattiasblixt_6907923_raw_34506c2336156f3a144ad443ea169079135f7c6b_mine_v131009.ps1
mattiasblixt_6907923_raw_34506c2336156f3a144ad443ea169079135f7c6b_mine_v131009.ps1
# http://soumya.wordpress.com/category/powershell/ function Get-LogDate{ $part1 = get-date -Uformat %Y%m%d $part2 = Get-Date -UFormat %H:%M:%S write-output $part1" "$part2 } function Get-LatestBuild{ param( [string]$Path, [PSCredential]$Credentials ) New-PSDrive -Name R -root $Path -scope Global -PSProvider FileSystem -Credential $Credentials -Persist | Out-null $obj = Get-ChildItem -Directory R: | select -last 1 Remove-PSDrive -Name R $strobj = $obj.tostring() $obj=$strobj.split(" ") $strobj = $obj | select -last 1 Write-output $strobj } function Set-AllkortRelease { <# .SYNOPSIS release a specified version of Allkort to one or more RD Session host Servers .DESCRIPTION Specifiera datorer via namn eller IP .PARAMETER Computer datorer .PARAMETER Domain fdqn domain .PARAMETER Revision revision som skall slappas .EXAMPLE Set-AllkortRelease -Revision NUMBER -Computer SERVER1,SERVER2,... -Domain SOMEDOMAIN.LOCAL .EXAMPLE Set-AllkortRelease -Computer SERVER1,SERVER2,... #> [CmdletBinding()] param( [string[]]$Computer = @('TS02','TS03','TS04','TS05','TS06','TS07','TS08','Monitor01','Xen01','Xen02'), [string]$Domain = 'allkort.se', [string]$Revision, [string]$LatestBuild ) $logpath = $PSScriptRoot+"\running_log.txt" $LoggedOnUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $BaseSourcePath = "\\fileprint.cnse.local\cns\Gemensam\Utveckling\Allkort 3\Builds" $currentYear = (get-date -Uformat %Y).ToString() + "*" $RunningTime = (get-date -UFormat %Y%m%d_%H%M).ToString() $preInfo = $RunningTime.ToString() + "_" $logTime = Get-LogDate Add-Content -Path $logpath -Value $logTime" "$LoggedOnUser" started to deploy" if ($LatestBuild -like "*es*"){ Add-Content -Path $logpath -Value $logTime" Release of latest build" $Computer = "alldemo" $Domain = "cnse.local" } Add-Content -Path $logpath -Value $logTime" Destination domain: "$Domain Add-Content -Path $logpath -Value $logTime" Destination server(s): "$Computer if ($Domain -like "*cnse*"){ $Domain = "cnse.local" $Credentials = $host.ui.PromptForCredential("Need credentials for domain $Domain", "Please enter your information in the form domain\user", "","NetBiosUserName") $SourceCredentials = $Credentials $DestinationCredentials = $Credentials } elseif($Domain -like "*allkort*") { $Domain = "allkort.se" $SourceCredentials = $host.ui.PromptForCredential("Need credentials for domain cnse.local", "Please enter your information in the form domain\user", "","NetBiosUserName") $DestinationCredentials = $host.ui.PromptForCredential("Need credentials for domain $Domain ", "Please enter your information in the form domain\user", "","NetBiosUserName") } else{ write-host $Domain" är inte en av domänerna 'allkort.se' eller 'cnse.local' avslutar script" $logTime = Get-LogDate Add-Content -Path $logpath -Value $logTime" "$Domain" is not a valid domain for this script - Script Terminated" Add-Content -Path $logpath " " break } if ($LatestBuild -like "*es*"){ $Revision = Get-LatestBuild -Path $BaseSourcePath -Credentials $SourceCredentials } if ($Revision -eq "") { #Fråga efter revision via GUI $logTime = Get-LogDate Add-Content -Path $logpath -Value $logTime" Revision inte angivet i parametrar start GUI" [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null $Revision = [Microsoft.VisualBasic.Interaction]::InputBox("Ange revisions nummer för release", "Ange Revisions nummer for release", "") } $logTime = Get-LogDate Add-Content -Path $logpath -Value $logTime" Revision to be released is: "$Revision $sourceFolder = $BaseSourcePath + '\Rev ' + $Revision + '\UI\Bin\Release' #rimlighetskontroller in här #Kolla om Path för källa finns # Test-Path -Path $sourceFolder -Credential $SourceCredenti #mappa source till S: New-PSDrive -Name S -root $sourceFolder -scope Global -PSProvider FileSystem -Credential $SourceCredentials -Persist | Out-null # hitta current server desintation path foreach ($currentServer in $Computer){ $mytimestart = get-date write-host "Begun working on server: " $currentServer $mytimestart.ToLongTimeString() $logTime = Get-LogDate Add-Content -Path $logpath -Value $logTime" Begun working on server: "$currentServer if($currentServer -eq "ts1"){ $installpath = "\c`$\Program Files (x86)\Testprogram\Allkort3Wpf" } elseif($currentServer -eq "intcitrix"){ $installpath = "\c`$\Program Files (x86)\Allkort" } elseif($currentServer -eq "alldemo" -and $LatestBuild -like "*es*") { $installpath = "\c`$\Program Files (x86)\Allkort3Senaste" } else{ # Assume "Correct" path \c$\Program Files (x86)\Allkort3 $installpath = "\c`$\Program Files (x86)\Allkort3" } $currentServerDestinationPath = "\\" + $currentServer + "." + $Domain + $installpath Write-Host server installation path $currentServerDestinationPath Add-Content -Path $logpath -Value $logTime" Installation path is: "$currentServerDestinationPath Add-Content -Path $logpath -Value $logTime" Begun mapping up source directory" #Mappa destintation till T: New-PSDrive -Name T -root $currentServerDestinationPath -scope Global -PSProv FileSystem -Cred $DestinationCredentials -Persist | Out-null $logTime = Get-LogDate Add-Content -Path $logpath -Value $logTime" Mapping to destination server is completed" write-host "Mapping to destination server is completed" $allNewItems = Get-ChildItem -path S: # de filer som skall läggas ut på i den nya releasen $oldReleases = Get-ChildItem -path T: | where {$_.Name -lt (get-date).adddays(-3).tostring()} #alla gamla filer från relaser mer än 3 dagar tillbaka $allOldItems = Get-ChildItem -path T: | where {$_.Name -notlike $CurrentYear} #de installerade filerna utan de filer/kataloger som börjar med årets write-host "Begun to delete releases which is released more than 3 days ago to free up space" Add-Content -Path $logpath -Value $logTime" Begun to delete releases which is released more than 3 days ago to free up space" foreach ($currentDelObj in $oldReleases){ remove-item -path $currentDelObj.fullname -Force -Recurse } write-host "Files/Folders deletion completed - Starting to rename last release" Add-Content -Path $logpath -Value $logTime" Files/Folders deletion completed - Starting to rename last release" foreach ($myOldItem in $allOldItems){ if ($myOldItem.Name -eq "sv"){ $currentServerPath = $currentServerDestinationPath + "\sv" $OldSvItems = Get-ChildItem -path $currentServerPath | where {$_.Name -notlike $CurrentYear} #de installerade filerna utan de filer/kataloger som börjar med årets foreach ($SvItem in $OldSvItems){ rename-item -path $SvItem.fullname -newname ($preInfo + $SvItem.Name) } } else{ rename-item -path $myOldItem.fullname -newname ($preInfo + $myOldItem.name) } } $logTime = Get-LogDate Add-Content -Path $logpath -Value $logTime" All files/folders from last release has been given a new names" Add-Content -Path $logpath -Value $logTime" Begun copy of the files/folders for the new release" write-host "All files/folders from last release has been given a new names" write-host "Begun copy of the files/folders for the new release" foreach ($currentNewItem in $allNewItems){ $currentItem = $sourceFolder+"\"+$currentNewItem copy-item $currentItem -Destination $currentServerDestinationPath -force -recurse } $mytimestop = get-date $logTime = Get-LogDate write-host "Completed copying new files to" $currentServer $mytimestop.ToLongTimeString() Add-Content -Path $logpath -Value $logTime" Completed copying new files to server, starting to dismount server mapping" #Maskinen klar, stäng uppmappning till T Remove-PSDrive -Name T $logTime = Get-LogDate Add-Content -Path $logpath -Value $logTime" Dismounting of Server mapping completed" } #Alla maskiner genomgångna stäng S Remove-PSDrive -Name S $logTime = Get-LogDate Add-Content -Path $logpath -Value $logTime" Deployment finished, Script Completed" Add-Content -Path $logpath " " }
PowerShellCorpus/GithubGist/IISResetMe_8917e9f47226044042f5_raw_3c376040516076199b5de33b05decb32af260b75_Find-OrphanGPTemplates.ps1
IISResetMe_8917e9f47226044042f5_raw_3c376040516076199b5de33b05decb32af260b75_Find-OrphanGPTemplates.ps1
gci "\\$(($d=$env:USERDNSDOMAIN))\sysvol\$d\Policies"|?{$_.Name-imatch"^(?<g>\{[A-F\d]{8}(-[A-F\d]{4}){3}-[A-F\d]{12}\})$"}|?{[ADSI]::Exists("LDAP://CN=$($Matched["g"]),CN=Policies,CN=System,DC=$($d-split"\."-join",DC=")")}|%{"{0} is an orphan, remove it"-f$_.FullName}
PowerShellCorpus/GithubGist/crmckenzie_4004375_raw_010a924cdac30fe2a9050889cd844336ee4fd6a5_gistfile1.ps1
crmckenzie_4004375_raw_010a924cdac30fe2a9050889cd844336ee4fd6a5_gistfile1.ps1
<# .SYNOPSIS IlMerges an assembly with its dependencies. Depends on nuget being installed in the PATH. .PARAMETER targetProject The name of the project to be ilmerged .PARAMETER outputAssembly The name of the ilmerged assembly when it is created .PARAMETER buildConfiguration The build configuration used to create the assembly. Used to locate the assembly under the project. The usual format is Project/bin/Debug .PARAMETER targetPlatform Defaults to .NET 4 .PARAMETER mvc3 If the project is an Mvc3 project, the MVC3 assemblies need to be added to the ilmerge list. The script assumes that the MVC3 assemblies are installed in the default location. .PARAMETER internalize Adds the /internalize flag to the merged assembly to prevent namespace conflicts. .EXAMPLE ilmerge.ps1 -targetProject "MyMVC3Project" -mvc3 #> param( [parameter(Mandatory=$true)] $targetProject, $outputAssembly = "$targetProject.dll", $buildConfiguration = "", $targetPlatform = "v4,c:\windows\Microsoft.NET\Framework\v4.0.30319", [switch] $mvc3, [switch] $internalize ) function Get-ScriptDirectory { $Invocation = (Get-Variable MyInvocation -Scope 1).Value Split-Path $Invocation.MyCommand.Path } function Get-Mvc3Dependencies() { $system_web_mvc = """c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll""" $system_web_webpages = """c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\System.Web.WebPages.dll""" $system_web_razor = """c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\System.Web.Razor.dll""" $system_web_webpages_razor = """c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\System.Web.WebPages.Razor.dll""" $mvc3Assemblies = "$system_web_mvc $system_web_webpages $system_web_razor $system_web_webpages_razor" return $mvc3Assemblies } function Get-InputAssemblyNames($buildDirectory) { $assemblyNames = Get-ChildItem -Path $buildDirectory -Filter *.dll | ForEach-Object { """" + $_.FullName + """" } write-host "Assemblies to merge: $assemblyNames" $inArgument = [System.String]::Join(" ", $assemblyNames) return $inArgument } function Get-BuildDirectory($solutionDirectoryFullName) { $targetProjectDirectory = "$solutionDirectoryFullName\$targetProject" $result = "$targetProjectDirectory\bin" if ($buildConfiguration -ne "") { $result = Join-Path $result $buildConfiguration } return $result } try { $scriptPath= Get-ScriptDirectory $scriptDirectory = new-object System.IO.DirectoryInfo $scriptPath $solutionDirectory = $scriptDirectory.Parent $solutionDirectoryFullName = $solutionDirectory.FullName $ilMergeAssembly = "$solutionDirectoryFullName\.ilmerge\IlMerge\IlMerge.exe" $publishDirectory = "$solutionDirectoryFullName\Publish" $outputAssemblyFullPath = "$publishDirectory\$outputAssembly" $buildDirectory = Get-BuildDirectory $solutionDirectoryFullName "Script Directory : $scriptPath" "Solution Directory: $solutionDirectoryFullName" "Build Directory : $buildDirectory" "Publish Directory : $publishDirectory" $outArgument = "/out:$publishDirectory/$outputAssembly" $inArgument = Get-InputAssemblyNames $buildDirectory # MVC3 assemblies are not a part of the .NET Framework, but neither are they a nuget package. # They have to be referenced directly. if ($mvc3 -eq $true) { $mvcAssemblies = Get-Mvc3Dependencies $inArgument = "$inArgument $mvcAssemblies" } $cmd = "$ilMergeAssembly /t:library /targetPlatform:""$targetPlatform"" $outArgument $inArgument" if ($internalize) { $cmd = $cmd + " /internalize" } "Installing ilmerge" nuget install IlMerge -outputDirectory .ilmerge -ExcludeVersion "Ensuring that publication directory exists" if ([System.IO.Directory]::Exists($publishDirectory) -eq $false) { [System.IO.Directory]::CreateDirectory($publishDirectory) } "Running Command: $cmd" $result = Invoke-Expression $cmd "Getting assembly info for $outputAssemblyFullPath" $outputAssemblyInfo = New-Object System.IO.FileInfo $outputAssemblyFullPath if ($outputAssemblyInfo.Length -eq 0) { $outputAssemblyInfo.Delete } $outputAssemblyInfo if ($outputAssemblyInfo.Exists -eq $false) { throw "Output assembly not created by ilmerge script." Exit -1 } elseif ($outputAssemblyInfo.Length -eq 0) { $outputAssemblyInfo.Delete(); Exit -1; } else { "Output assembly created successfully at $outputAssemblyFullPath." Exit 0; } } catch { throw Exit -1 }
PowerShellCorpus/GithubGist/t-mat_8771347_raw_7e40d33fd6b2d64c5278b64a995d0d80d598bc66_keyrate.ps1
t-mat_8771347_raw_7e40d33fd6b2d64c5278b64a995d0d80d598bc66_keyrate.ps1
<# /* How can I increase the key repeat rate beyond the OS's limit? http://stackoverflow.com/a/11056655 */ #> Add-Type -Type @" //" using System; using System.Runtime.InteropServices; namespace MyPrivateKeyRateSettings { public static class KeyRate { [DllImport("user32.dll", SetLastError = false)] internal static extern bool SystemParametersInfo( uint uiAction , uint uiParam , ref FILTERKEYS pvParam , uint fWinIni ); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal struct FILTERKEYS { public uint cbSize; public uint dwFlags; public uint iWaitMSec; public uint iDelayMSec; public uint iRepeatMSec; public uint iBounceMSec; } private const uint SPI_SETFILTERKEYS = 0x0033; private const uint FKF_FILTERKEYSON = 0x0001; private const uint FKF_AVAILABLE = 0x0002; private static void Usage() { Console.WriteLine("Usage: keyrate <delay ms> <repeat ms>"); } public static void Main(string[] args) { if(args.Length != 0 && args.Length != 2) { Usage(); Console.WriteLine("Call with no parameters to disable."); return; } FILTERKEYS fk; fk.cbSize = 0; fk.dwFlags = 0; fk.iWaitMSec = 0; fk.iDelayMSec = 0; fk.iRepeatMSec = 0; fk.iBounceMSec = 0; if(args.Length == 2) { fk.iDelayMSec = (uint) Math.Max(0, Convert.ToInt32(args[0])); fk.iRepeatMSec = (uint) Math.Max(0, Convert.ToInt32(args[1])); fk.dwFlags = FKF_FILTERKEYSON | FKF_AVAILABLE; Console.WriteLine("Setting keyrate: delay={0}ms, rate={1}ms" , fk.iDelayMSec, fk.iRepeatMSec); } else { Usage(); Console.WriteLine("No parameters given: disabling."); } fk.cbSize = (uint) Marshal.SizeOf(fk); if(! SystemParametersInfo(SPI_SETFILTERKEYS, 0, ref fk, 0)) { Console.WriteLine("System call failed.\nUnable to set keyrate."); } } } } "@ #" # end Add-Type [MyPrivateKeyRateSettings.KeyRate]::Main($Args)
PowerShellCorpus/GithubGist/askesian_2245880_raw_59608a104bb55b443190efd0ac43dfdc95821cf7_Get-SpecialPath.ps1
askesian_2245880_raw_59608a104bb55b443190efd0ac43dfdc95821cf7_Get-SpecialPath.ps1
# STEP 0: Declare input parameter Param([switch]$AsDrive) # STEP 1: Define hash for paths $csidl = @{ "Personal" = 0x0005; "LocalAppData" = 0x001c; "InternetCache" = 0x0020; "Cookies" = 0x0021; "History" = 0x0022; "Windows" = 0x0024; "System" = 0x0025; "ProgramFiles" = 0x0026; "ProgramFilesx86" = 0x002a; "Profile" = 0x0028; "AdminTools" = 0x0030; } # STEP 2: Set up Shell.Application COM object $sa = New-Object -ComObject Shell.Application # STEP 3: Set up hask for paths, collect with "names" $sp = @{} # the special paths collection foreach($key in $csidl.keys) { $sp[$key] = $sa.NameSpace($csidl[$key]).Self.Path; } # STEP 4: Map global drives using names from the hash if($AsDrive) # Param declared at the beginning { $keys = $sp.keys; $keys | %{ $p = $sp[$_]; if($p.Length -gt 0) { $n = $csidl[$_] # numeric to help ID the drive... New-PSDrive -Name: $_ -PSProvider:FileSystem -Root:$p ` -Scope Global -Description:"SpecialFolder$n" } } } else { return $sp; } # http://www.vistax64.com/powershell/19524-need-quick-way-get-my-documents-folder.html
PowerShellCorpus/GithubGist/flakshack_950175_raw_e840d1640c9845198100c17c9b305d00fd2ea9e7_Start-SuspendedMoveRequests.ps1
flakshack_950175_raw_e840d1640c9845198100c17c9b305d00fd2ea9e7_Start-SuspendedMoveRequests.ps1
############################################################################# # Procedure: Start-SuspendedMoveRequests.PS1 # Author: Scott Vintinner # Last Edit: 4/30/2011 # Purpose: This script will start a move request in suspended mode and # email the selected user. # # PS Notes Computers must have Powershell scripts enabled by an admin: # set-executionpolicy remotesigned ## # This work is licensed under a Creative Commons Attribution 3.0 Unported License. # http://creativecommons.org/licenses/by/3.0/ # © 2011 Scott Vintinner ############################################################################# # Parameters Param([string[]]$identities); $identities = $identities | Sort-Object; #Constants $smtpserver = '10.1.19.40'; $emailFrom = "[email protected]"; $body = " I will begin moving your mailbox in the next few minutes. Your Outlook mailbox will be offline for somewhere between 10 minutes and 2 hours depending on the amount of data. In addition, you will not be able to send or receive Blackberry emails during this time. Please contact me as soon as possible if this is a problem. "; # Submit the move requests in SUSPENDED state foreach($identity in $identities) { new-MoveRequest -Identity $identity -BadItemLimit 5 -Suspend:$true; # Email a notification to the user Write-Host "Sending 15-minute until move email notification to $identity"; $timeOfMove = ((get-date).AddMinutes(15)).toShortTimeString(); $subject = "Mailbox move starting @ $timeOfMove"; $emailAddress = (Get-Mailbox -Identity $identity | select PrimarySmtpAddress).PrimarySmtpAddress; $smtp = new-object Net.Mail.SmtpClient($smtpServer); $smtp.Send($emailFrom, $emailAddress, $subject, $body); }
PowerShellCorpus/GithubGist/jlattimer_95b4fe9d1913de018922_raw_4c18cc5aefdd1dded0ecbaf51b3c0f8accca3c93_Create%20CRM%20VM%20Static%20IP%20Existing.ps1
jlattimer_95b4fe9d1913de018922_raw_4c18cc5aefdd1dded0ecbaf51b3c0f8accca3c93_Create%20CRM%20VM%20Static%20IP%20Existing.ps1
<# Make sure you have installed the Azure PowerShell cmdlets: https://www.windowsazure.com/en-us/manage/downloads/ and then reboot #> <# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! The steps need to be run individually !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #> <# Step 1: Run this first to download your publisher file from Azure #> Get-AzurePublishSettingsFile <# Step 2: Change the path to the file you downloaded: C:\xxx\xxx.publishsettings #> $publisherFileLocation = "C:\xxx\xxx.publishsettings" Import-AzurePublishSettingsFile $publisherFileLocation <# Step 3: Input the 'Name' of the subscription from the output of the previous step #> $subscriptionName = "Visual Studio Ultimate with MSDN" Select-AzureSubscription -SubscriptionName $subscriptionName <# Step 4: Run this to output the list of Azure storage accounts associated with your account #> Get-AzureStorageAccount <# Step 5: Input the subscription 'Name' again and the 'StorageAccountName' from the output of the previous step when the VM gets created it will use that Azure Storage account #> $sortageAccountName = "portalxxxxxxxxxxxxxxxxx" Set-AzureSubscription -SubscriptionName $subscriptionName -CurrentStorageAccount $sortageAccountName <# Step 6: Create a reserved/static IP for your VM - input the name/label and the region your VM will be in #> $reservedIPName = "CRMIP" $reservedIPLabel = "CRMIP" $location = “North Central US” New-AzureReservedIP –ReservedIPName $reservedIPName –Label $reservedIPLabel –Location $location <# Use this to remove the reserved IP if you end up not needing it #> <# Remove-AzureReservedIP -ReservedIPName "CRMIP" -Force# > <# Show the list of reserved IP addresses if you are interested #> <# Get-AzureReservedIP #> <# Step 7: Use this to list your existing Azure VM images #> Get-AzureVMImage | Where-Object { $_.Category -eq "User" } <# Step 8: Input the VM & cloud service names, VM size, Image name and create the VM #> $vmName = "CRM2015" $imageName = "ExistingCRM2015-12032014" $cloudServiceName = "CRM2015" $instanceSize = "ExtraLarge" New-AzureVMConfig -Name $vmName -InstanceSize $instanceSize -Image $imageName | Add-AzureEndpoint -Name "HTTP" -Protocol "tcp" -PublicPort 80 -LocalPort 80 | Add-AzureEndpoint -Name "HTTPS" -Protocol "tcp" -PublicPort 443 -LocalPort 443 | Add-AzureEndpoint -Name "HTTPS2" -Protocol "tcp" -PublicPort 444 -LocalPort 444 | <# Only if you need ADFS on the same server #> Add-AzureEndpoint -Name "Remote Desktop" -Protocol "tcp" -PublicPort 60523 -LocalPort 3389 | New-AzureVM -ServiceName $cloudServiceName -ReservedIPName $reservedIPName -Location $location
PowerShellCorpus/GithubGist/jonschoning_1149228_raw_a665c6ad6ceb7fb1aa1a782d63d3f24a4a57b9a8_Visit-AllFiles.ps1
jonschoning_1149228_raw_a665c6ad6ceb7fb1aa1a782d63d3f24a4a57b9a8_Visit-AllFiles.ps1
# Calling Excel Math Functions From PowerShell $xl = New-Object -ComObject Excel.Application $xlprocess = Get-Process excel $worksheet_function = $xl.WorksheetFunction $data = 1,2,3,4 $matrix = ((1,2,3),(4,5,6),(7,8,10)) Write-Host -ForegroundColor green Median Write-Host -ForegroundColor red $worksheet_function.Median($data) Write-Host -ForegroundColor green StDev Write-Host -ForegroundColor red $worksheet_function.StDev($data) Write-Host -ForegroundColor green Var Write-Host -ForegroundColor red $worksheet_function.Var($data) Write-Host -ForegroundColor green MInverse Write-Host -ForegroundColor red $worksheet_function.MInverse($matrix) $xl.quit() $xlprocess | kill
PowerShellCorpus/GithubGist/breezhang_7153304_raw_00737553cc03fa3fb214ab1ef00d91a2b9325437_a.ps1
breezhang_7153304_raw_00737553cc03fa3fb214ab1ef00d91a2b9325437_a.ps1
#find -type f |xargs md5sum --binary >file.txt $db = New-Object -TypeName System.Collections.Specialized.NameValueCollection; foreach($item in (gc 'path\file.txt')){ $temp = $item.Split("*"); $db.add([string]$temp[0],[string]$temp[1]); } ; $Global:result=$db.AllKeys | %{ if($db[$_].Split(",").Length -gt 1){@{hash=$_ ;filename=@($db[$_].Split(","))}}};
PowerShellCorpus/GithubGist/axefrog_6a035b69e710f8315c24_raw_9012ec39c8d4d0c686b643cfae96beec378aeaac_build.ps1
axefrog_6a035b69e710f8315c24_raw_9012ec39c8d4d0c686b643cfae96beec378aeaac_build.ps1
$postbuild = "" foreach ($arg in $args) { switch ($arg) { "run" { $postbuild = "run" } "debug" { $postbuild = "debug" } } } if (!(test-path build)) { mkdir build } if (!(test-path build/obj)) { mkdir build/obj } if (!(test-path build/bin)) { mkdir build/bin } pushd build $opts = "/Zi","/Gm","/EHsc","/Foobj/","/I..\libs\include","/Fe./obj/MyGame.exe","../src/*.cpp" $srcdirs = get-childitem -recurse -Attribute Directory ../src foreach ($dir in $srcdirs) { foreach($file in $dir.GetFiles()) { if($file.Extension -eq ".cpp") { $opts += "`"$($dir.FullName)\*.cpp`"" break } } } $opts += "user32.lib","gdi32.lib","opengl32.lib","glu32.lib","../libs/lib/*.lib" &cl $opts if (!$LASTEXITCODE) { xcopy ..\libs\dll\*.dll bin /Y xcopy .\obj\MyGame.exe bin /Y xcopy .\obj\MyGame.pdb bin /Y robocopy /XC /NJS /NJH ../src/graphics/shaders bin/shaders switch ($postbuild) { "run" { pushd bin Start-Process MyGame.exe popd } "debug" { pushd bin Start-Process devenv -ArgumentList "MyGame.exe" popd } } } popd
PowerShellCorpus/GithubGist/tbenade_5378295_raw_9169ea70662600e50805f095cba38569e9c297c6_gistfile1.ps1
tbenade_5378295_raw_9169ea70662600e50805f095cba38569e9c297c6_gistfile1.ps1
param( $user, $app_id, $revision, $description, $api_key ) #thanks to https://gist.github.com/kfrancis/3164709 #Create a URI instance since the HttpWebRequest.Create Method will escape the URL by default. $URL = "http://api.newrelic.com/deployments.xml" $post = "deployment[user]=$user&deployment[app_id]=$app_id&deployment[revision]=$revision&deployment[description]=$description" $URI = New-Object System.Uri($URL,$true) #Create a request object using the URI $request = [System.Net.HttpWebRequest]::Create($URI) #Build up a nice User Agent $request.UserAgent = $( "{0} (PowerShell {1}; .NET CLR {2}; {3})" -f $UserAgent, $(if($Host.Version){$Host.Version}else{"1.0"}), [Environment]::Version, [Environment]::OSVersion.ToString().Replace("Microsoft Windows ", "Win") ) #Since this is a POST we need to set the method type $request.Method = "POST" $request.Headers.Add("x-api-key", $api_key); #Set the Content Type as text/xml since the content will be a block of xml. $request.ContentType = "application/x-www-form-urlencoded" $request.Accept = "text/xml" try { #Create a new stream writer to write the xml to the request stream. $stream = New-Object IO.StreamWriter $request.GetRequestStream() $stream.AutoFlush = $True $PostStr = [System.Text.Encoding]::UTF8.GetBytes($Post) $stream.Write($PostStr, 0,$PostStr.length) $stream.Close() #Make the request and get the response $response = $request.GetResponse() $response.Close() if ([int]$response.StatusCode -eq 201) { Write-Host "NewRelic Deploy API called succeeded." } else { Write-Host "NewRelic Deploy API called failed." } } catch [System.Net.WebException] { $res = $_.Exception.Response Write-Host "NewRelic Deploy API called failed." }
PowerShellCorpus/GithubGist/zachbonham_3790050_raw_23b851618aa9a39bcb5684878c49b7fa67108274_unmerged.ps1
zachbonham_3790050_raw_23b851618aa9a39bcb5684878c49b7fa67108274_unmerged.ps1
<# Report on unmerged changesets for release planning. #> function get_unmerged_changesets($source, $target) { write-host "getting unmerged changesets for $source and $target" $changesets = @() $data = tf merge /candidate $source $target /recursive <# $START_INDEX is because tf merge command returns header info we want to skip. e.g. Changeset Author Date --------- -------------------------------- ---------- #> $START_INDEX = 2 $CHANGESET_INDEX = 0 $AUTHOR_INDEX = 1 $DATE_INDEX = 2 for($i=$START_INDEX; $i -lt $data.count; $i++) { $changeset = new-object object $tokens = $data[$i].Split(" ", [StringSplitOptions]::RemoveEmptyEntries) add-member -memberType NoteProperty -name "ChangeSetId" -value $tokens[$CHANGESET_INDEX] -inputObject $changeset add-member -memberType NoteProperty -name "Author" -value $tokens[$AUTHOR_INDEX] -inputObject $changeset add-member -memberType NoteProperty -name "Date" -value $tokens[$DATE_INDEX] -inputObject $changeset $comment = get_changeset_comment $changeset.ChangeSetId add-member -memberType NoteProperty -name "Comments" -value $comment -inputObject $changeset $changesets += $changeset } return $changesets } <# grab the comment from changeset id. #> function get_changeset_comment($changeset_id) { write-debug "get_changeset_details($changeset_id)" $COMMENT_INDEX = 5 $details = tf changeset $changeset_id /noprompt return $details[$COMMENT_INDEX].Trim() } <# e.g. $changesets = @() $changesets += get_unmerged_changesets "$/dev" "$/main" $changesets | export-csv #>
PowerShellCorpus/GithubGist/takekazuomi_8130783_raw_df90ac0c4ae5c7d05016f5c92beadbd6375bb883_sample.profile.ps1
takekazuomi_8130783_raw_df90ac0c4ae5c7d05016f5c92beadbd6375bb883_sample.profile.ps1
# Load posh-git example profile . "~\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1" function Prompt{ "$ " }
PowerShellCorpus/GithubGist/gravejester_5437083f9605b604f1c2_raw_91e3311a67853f67f3de27e90d4d11716847ae89_New-MySqlConnection.ps1
gravejester_5437083f9605b604f1c2_raw_91e3311a67853f67f3de27e90d4d11716847ae89_New-MySqlConnection.ps1
function New-MySqlConnection { <# .SYNOPSIS Create a new MySQL database connection. .DESCRIPTION This function will create a new MySQL database connection and return a database connection object. .EXAMPLE New-MySqlConnection -DatabaseServer 'dbserver01' -DatabaseName 'MyDatabase' Will create a new database connection object using integrated security. .EXAMPLE New-MySqlConnection -DatabaseServer 'dbserver01' -DatabaseName 'MyDatabase' -Credential 'dbuser' Will create a new database connection object after prompting for the password to the user 'dbuser'. .LINK http://dev.mysql.com/downloads/connector/net/ .NOTES Author: Øyvind Kallstad Date: 21.01.2015 Version: 1.0 #> [CmdletBinding()] param ( # Name of server or instance. [Parameter(Mandatory = $true, Position = 0)] [Alias('Server','ComputerName','dbServer')] [string] $DatabaseServer, # Name of database. [Parameter(Mandatory = $true, Position = 1)] [string] $DatabaseName, # Port to connect to. Default is 3306. [Parameter()] [int] $Port = 3306, # Credential, if not using integrated security. [Parameter(Mandatory = $false)] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty ) try { # load MySQL .NET connector [void][System.Reflection.Assembly]::LoadWithPartialName('MySql.Data') # start building the connection string $connectionStringBuilder = New-Object 'MySql.Data.MySqlClient.MySqlConnectionStringBuilder' $connectionStringBuilder.Server = $DatabaseServer $connectionStringBuilder.Database = $DatabaseName $connectionStringBuilder.Port = $Port # if credential parameter is not used, integrated security will be used if (-not($PSBoundParameters['Credential'])) { $connectionStringBuilder.IntegratedSecurity = $true } # otherwise user user id and password else { $connectionStringBuilder.UserId = $Credential.UserName $connectionStringBuilder.Password = $Credential.GetNetworkCredential().Password } # create database connection $dbConnection = New-Object MySql.Data.MySqlClient.MySqlConnection $dbConnection.ConnectionString = $connectionStringBuilder.ToString() # open database connection [void]$dbConnection.Open() # return the connection object Write-Output $dbConnection } catch { Write-Warning "At line:$($_.InvocationInfo.ScriptLineNumber) char:$($_.InvocationInfo.OffsetInLine) Command:$($_.InvocationInfo.InvocationName), Exception: '$($_.Exception.Message.Trim())'" } }
PowerShellCorpus/GithubGist/breezhang_7233248_raw_16cf94fc79aa79a6ef99570799894f6911006b5b_checkfiletype.ps1
breezhang_7233248_raw_16cf94fc79aa79a6ef99570799894f6911006b5b_checkfiletype.ps1
function checkfiletype { $n1 = @{Expression= {$_.ToString().Split("%")[0]};Name ="most_like"}; $n2 = @{Expression= {$_.ToString().Split("%")[1]};Name ="filetype"}; $n3 = @{Expression= {[regex]::Match($_.ToString().Split("%")[1],"(?<=\(\.)\w+").Value};Name ="filetype2"}; if(!(Test-Path $args[0])){ Write-Host -ForegroundColor Red error input path; return; }else{ $name = (Resolve-Path $args[0] |Split-Path -Leaf |Split-String(".") )[0]; $ext =(Resolve-Path $args[0] |Split-Path -Leaf |Split-String(".") ) |Select-Object -Last 1; Write-Host $name; $fx =$args[0]; try{ $xx=((file $fx |Select-String "%" )|Select-Object $n1,$n2,$n3 |Sort-Object -Property most_like -Descending)[0]; $mybewill ="{0}.{1}" -f $name,$xx.filetype2; $des =$xx.filetype; Write-Host -ForegroundColor Green system guest ===> -NoNewline Write-Host -ForegroundColor Cyan $mybewill; Write-Host -ForegroundColor DarkMagenta $des; if( $xx.filetype2 -like "TXT"){ Out-File -Encoding utf8 -Force -InputObject @(gc $fx) -FilePath $fx Write-Host -ForegroundColor DarkYellow "OK"; } return; }catch{ Write-Host -ForegroundColor Red " try change gunwin32 tools" } if($ext -like "xml" ){ try{ if(Test-Xml $fx){ gc $fx |Out-File -FilePath $fx -Encoding utf8; Write-Host -ForegroundColor DarkYellow "OK"; return;} }catch{ Write-Host -ForegroundColor Red "some error"; } } $guntoolsfile ="D:\Program Files\GnuWin32\bin\file.exe"; $result =&$guntoolsfile $fx |Split-String(";") | ` Select-Object -Last 1 | ` Split-String(",") | ` Select-Object -First 1|` Select-String "text"; if($result){ Write-Host "OK" $result; Out-File -Encoding utf8 -Force -InputObject @(gc $fx) -FilePath $fx; Write-Host -ForegroundColor DarkYellow "OK"; return; } &$guntoolsfile $fx; } }
PowerShellCorpus/GithubGist/miwaniza_10784481_raw_11c89e41ffe8cf1ce535a4deb9b30334d41db899_Get-VaultGroupsAll.ps1
miwaniza_10784481_raw_11c89e41ffe8cf1ce535a4deb9b30334d41db899_Get-VaultGroupsAll.ps1
Add-Type -Path "c:\Program Files (x86)\Autodesk\Autodesk Vault 2014 SDK\bin\Autodesk.DataManagement.Client.Framework.Vault.Forms.dll" $global:g_login=[Autodesk.DataManagement.Client.Framework.Vault.Forms.Library]::Login($null) # Retreiving all groups $allGroups = $g_login.WebServiceManager.AdminService.GetAllGroups() # Fetching results $activeGroups = $allGroups | Where-Object{$_.IsActive -eq $true} # Representing results $activeGroups | Out-GridView -Title "Active groups"
PowerShellCorpus/GithubGist/oiotoxt_5586ccbce94ba7018ba4_raw_7792dea4fbbb1b40dbccc2847847d820f654af8f_txt2utf8.ps1
oiotoxt_5586ccbce94ba7018ba4_raw_7792dea4fbbb1b40dbccc2847847d820f654af8f_txt2utf8.ps1
#Requires -version 3.0 ############################################################################## # Filename : txt2utf8.ps1 # Version : v1.0 ############################################################################## # # Convert text files recursively to UTF-8 # # \ option : input directory # \ option : with or without BOM # \ option : CR+LF ==> LF # \ option : filter # # Assumption # Input-file-without-BOM is encoded in system-codepage(e.g. CP1252, CP949) # # Hint # For Remote Signed : Run <Set-ExecutionPolicy RemoteSigned> # For Unrestricted : Run <Set-ExecutionPolicy Unrestricted> ############################################################################## # config # input directory (relative or absolute. write drive-name in capital letter) $_srcDir = "TextFolder" #$_srcDir = "C:\TextFolder" # with or without BOM $_withBom = $TRUE # CR+LF ==> LF $_forceLf = $TRUE # filter [String[]] $_include = @("*.*") #[String[]] $_include = @("*.h", "*.cpp") # filter [String[]] $_exclude = @("") #[String[]] $_exclude = @("*.log") ############################################################################## # output directory $_dstDir = $_srcDir if ($_withBom) { $_dstDir = $_dstDir + ".UTF8+BOM" } else { $_dstDir = $_dstDir + ".UTF8+NOBOM" } if ($_forceLf) { $_dstDir = $_dstDir + "&LF" } ############################################################################## # converter ( any ==> UTF8 ) Function ConvertToUtf8( [String] $srcDir, [String] $dstDir, [String[]] $include, [String[]] $exclude, [bool] $withBom, [bool] $forceLF) { $cnt = 0 $encoding = New-Object System.Text.UTF8Encoding($withBom) foreach($item in Get-ChildItem $srcDir -Include $include -Exclude $exclude -Recurse) { if ($item.PSIsContainer) { continue } if (!$item.Fullname.Contains($srcDir)) { Write-Host "Error. Please compare the following two lines." Write-Host ">> `$item.Fullname :" $item.Fullname Write-Host ">> `$srcDir :" $srcDir return } $dst = $item.Fullname.Replace($srcDir, $dstDir) if (!(Test-Path $(Split-Path $dst -Parent))) { New-Item $(Split-Path $dst -Parent) -type Directory } Get-Content $item | Out-File -Filepath $dst -Encoding utf8 if ($forceLF) { $fileContents = [IO.File]::ReadAllText($dst) -Replace "`r`n", "`n" } else { $fileContents = [IO.File]::ReadAllText($dst) } [System.IO.File]::WriteAllText($dst, $fileContents, $encoding) Write-Host "------------------------------------------------------------------------------" Write-Host "`$src :" $item Write-Host "`$dst :" $dst Write-Host "LENGTH :" $item.Length "==>" (Get-Item $dst).Length $cnt++ } Write-Host "`n* * * * * * * *" $cnt "file(s) converted * * * * * * * *" } ############################################################################## # run ConvertToUtf8 $_srcDir $_dstDir $_include $_exclude $_withBom $_forceLf
PowerShellCorpus/GithubGist/rossnz_8519834_raw_919015b22d05333df0b59d66da653610ad728502_gistfile1.ps1
rossnz_8519834_raw_919015b22d05333df0b59d66da653610ad728502_gistfile1.ps1
$myString = "99 Bottles of beer on the wall!" $myValue = $myString -replace '[ !,.a-zA-Z]' Write-Host $myValue
PowerShellCorpus/GithubGist/Iristyle_3407847_raw_d6dc8c4d366803e8546b7b2d9bd8ac49e95cac1e_BootstrapCanary.ps1
Iristyle_3407847_raw_d6dc8c4d366803e8546b7b2d9bd8ac49e95cac1e_BootstrapCanary.ps1
$chromeExtensions = @' { "extensions": { "settings": { "fdmmgilgnpjigdojojpjoooidkmcomcm": { "active_permissions": { "api": [ "cookies" ], "explicit_host": [ "http://*/*", "https://*/*" ], "scriptable_host": [ "http://getpostman.com/*", "https://getpostman.com/*" ] }, "app_launcher_ordinal": "y", "events": [ "runtime.onInstalled" ], "from_bookmark": false, "from_webstore": true, "granted_permissions": { "api": [ "cookies" ], "explicit_host": [ "http://*/*", "https://*/*" ], "scriptable_host": [ "http://getpostman.com/*", "https://getpostman.com/*" ] }, "install_time": "12989963420177049", "location": 1, "manifest": { "app": { "launch": { "local_path": "index.html" } }, "content_scripts": [ { "js": [ "js/listener.js" ], "matches": [ "http://getpostman.com/*", "https://getpostman.com/*" ], "run_at": "document_end" } ], "content_security_policy": "default-src 'self'; connect-src *; script-src 'self' https://ssl.google-analytics.com https://platform.twitter.com https://apis.google.com; style-src 'self' blob: data: filesystem: 'unsafe-inline'; img-src *; frame-src 'self' http://www.facebook.com https://plusone.google.com https://platform.twitter.com blob: data: filesystem:; font-src '*' blob: data: filesystem:; media-src *;", "current_locale": "en_US", "default_locale": "en", "icons": { "128": "icon_128.png", "16": "icon_16.png", "32": "icon_32.png", "48": "icon_48.png" }, "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaSf2+peSwtoCNF1vzjLfc2zxbiDtfmjc4iGp2FmKBmMVYF7TeIoLJn78Reg8rZiSgk27ay8jEdjRLCtR/jdBxejKyIG9Wu5lfkleL1Bv+0vIx67ykDP3hAa5uAlUW8rlJH3rE8ht2K6HpSNgRolYE1/UFcGDDuMKWSnojSR7u1QIDAQAB", "manifest_version": 2, "name": "Postman - REST Client - Installing...", "offline_enabled": true, "permissions": [ "cookies", "http://*/*", "https://*/*" ], "update_url": "http://clients2.google.com/service/update2/crx", "version": "0.0" }, "page_ordinal": "n", "path": "fdmmgilgnpjigdojojpjoooidkmcomcm\\0.0", "state": 1 }, "gplegfbjlmmehdoakndmohflojccocli": { "active_permissions": { "api": [ "devtools", "tabs", "unlimitedStorage", "webNavigation" ], "explicit_host": [ "http://*/*", "https://*/*" ], "scriptable_host": [ "http://chrome-devtools-frontend.appspot.com/*/devtools.html?*", "https://chrome-devtools-frontend.appspot.com/*/devtools.html?*" ] }, "events": [ "runtime.onInstalled" ], "from_bookmark": false, "from_webstore": true, "granted_permissions": { "api": [ "devtools", "tabs", "unlimitedStorage", "webNavigation" ], "explicit_host": [ "http://*/*", "https://*/*" ], "scriptable_host": [ "http://chrome-devtools-frontend.appspot.com/*/devtools.html?*", "https://chrome-devtools-frontend.appspot.com/*/devtools.html?*" ] }, "install_time": "12989044209319842", "lastpingday": "12989055688643437", "location": 1, "manifest": { "background": { "page": "BackgroundPage.html" }, "browser_action": { "default_icon": "pagespeed-19.png", "default_popup": "guide.html", "default_title": "PageSpeed Insights" }, "content_scripts": [ { "js": [ "inject_pagespeed.js" ], "matches": [ "http://chrome-devtools-frontend.appspot.com/*/devtools.html?*", "https://chrome-devtools-frontend.appspot.com/*/devtools.html?*" ] } ], "content_security_policy": "default-src 'self'; connect-src http: https:; script-src 'self' https://chrome-devtools-frontend.appspot.com; img-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-src 'self' about: ", "current_locale": "en_US", "default_locale": "en", "description": "PageSpeed Insights analyzes the performance of your web pages and provides suggestions to make them faster.", "devtools_page": "devtools-page.html", "homepage_url": "https://developers.google.com/speed/docs/insights/using_chrome", "icons": { "128": "pagespeed-128.png", "16": "pagespeed-16.png", "32": "pagespeed-32.png", "48": "pagespeed-48.png", "64": "pagespeed-64.png" }, "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCtHX1f891iqStUrTSjgXk3mNj9ivS9qO/tIt5SKSTpLd9Hs4lF1UzAHMHFN84yCOSNfO9rEe6JKzR7LDWQNVNyLkIIw9UD01PeJga0Yu/P9BKpGzNnCoctGgPPrcdUUCy0F8kz/6GPZSp10sMoQuvip8MTpBFzp5oM7BAum+vqpwIDAQAB", "manifest_version": 2, "minimum_chrome_version": "19.0", "name": "PageSpeed Insights (by Google) - Installing...", "options_page": "options.html", "permissions": [ "tabs", "unlimitedStorage", "webNavigation", "http://*/*", "https://*/*" ], "update_url": "http://clients2.google.com/service/update2/crx", "version": "0.0" }, "path": "gplegfbjlmmehdoakndmohflojccocli\\0.0", "state": 1 }, "ighdmehidhipcmcojjgiloacoafjmpfk": { "active_permissions": { "api": [ "devtools", "tabs" ], "explicit_host": [ "\u003Call_urls\u003E" ], "scriptable_host": [ "\u003Call_urls\u003E" ] }, "events": [ "runtime.onInstalled" ], "from_bookmark": false, "from_webstore": true, "granted_permissions": { "api": [ "devtools", "tabs" ], "explicit_host": [ "\u003Call_urls\u003E" ], "scriptable_host": [ "\u003Call_urls\u003E" ] }, "install_time": "12989044047149862", "lastpingday": "12989055688643437", "location": 1, "manifest": { "background": { "page": "background.html" }, "content_scripts": [ { "js": [ "js/inject/debug.js" ], "matches": [ "\u003Call_urls\u003E" ], "run_at": "document_start" } ], "description": "Extends the Developer Tools, adding tools for debugging and profiling AngularJS applications.", "devtools_page": "devtoolsBackground.html", "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9hsXx3+F75DyGto3mkm0FB2sycQzyMqXQAySn2Qj67vIHFMSrVZ0ItPzGnWJwoRoaDI7cQF9c/WLDpLJQwGe5CV5z84MueOME3e45JJEwN+YsW5ufEavmp+pk1c9h/Wyi8bMoSWJGIrOG72wCTFOdnyN6nocA0dm4w7UWsxLLEQIDAQAB", "manifest_version": 2, "name": "AngularJS Batarang - Installing...", "permissions": [ "tabs", "\u003Call_urls\u003E" ], "update_url": "http://clients2.google.com/service/update2/crx", "version": "0.0" }, "path": "ighdmehidhipcmcojjgiloacoafjmpfk\\0.0", "state": 1 }, "jnihajbhpnppcggbcgedagnkighmdlei": { "active_permissions": { "api": [ "tabs" ], "explicit_host": [ "http://*/*" ], "scriptable_host": [ "\u003Call_urls\u003E" ] }, "events": [ "runtime.onInstalled" ], "from_bookmark": false, "from_webstore": true, "granted_permissions": { "api": [ "tabs" ], "explicit_host": [ "http://*/*" ], "scriptable_host": [ "\u003Call_urls\u003E" ] }, "install_time": "12989962557323587", "location": 1, "manifest": { "background_page": "background.html", "browser_action": { "default_icon": "icon19.png", "default_title": "Enable LiveReload" }, "content_scripts": [ { "js": [ "LiveReload-content.js" ], "matches": [ "\u003Call_urls\u003E" ] } ], "icons": { "128": "icon128.png", "48": "icon48.png" }, "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDrOgODVyBNTQqWv0iT9lwzEgpXFyNeUC6/JAjfKV4Zg4PAIhKOAYUQQcE1UI+s1cxF4GgZpfg9ybAlbu1MOWoi7HBuFAvA/BIJ8YTfM6OISVptHL2AsAbxmKP59iGDgJohgt2wuibclPZjoKTyLNm1x3C4VRErSs9prJGPsyM3DwIDAQAB", "name": "LiveReload - Installing...", "options_page": "options.html", "permissions": [ "tabs", "http://*/*" ], "update_url": "http://clients2.google.com/service/update2/crx", "version": "0.0" }, "path": "jnihajbhpnppcggbcgedagnkighmdlei\\0.0", "state": 1 }, "lfjbhpnjiajjgnjganiaggebdhhpnbih": { "active_permissions": { "api": [ "devtools", "plugin" ], "explicit_host": [ "http://*/*", "https://*/*" ] }, "events": [ "runtime.onInstalled" ], "from_bookmark": false, "from_webstore": true, "granted_permissions": { "api": [ "devtools", "plugin" ], "explicit_host": [ "http://*/*", "https://*/*" ] }, "install_time": "12989962861332399", "location": 1, "manifest": { "background": { "page": "background.html" }, "description": "Extension to allow editing and fast reloading of local files from Chrome developer tools", "devtools_page": "devtools.html", "icons": { "128": "tools.png", "48": "tools_small.png" }, "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA3lMdctvLLk67/Tn6C7v3wc7owH0eDZNheD+mCSPz/dIJD6xpEdPC/dD/ctdLahtPC37me1q0JkS9Z0MF3Xz6+C0gZedmphGon73Isf1dFaGfqWf/6DUZ7bZvhOIAJiJgcUNRGaQcvz0cCEfgc7w6UiJu/zZgYoBoskyOMBoPlQIDAQAB", "manifest_version": 2, "name": "Tincr - Installing...", "permissions": [ "http://*/", "https://*/" ], "plugins": [ { "path": "NPAPIFileIOforChrome.plugin", "public": false }, { "path": "npNPAPIFileIOforChrome.dll", "public": false }, { "path": "npNPAPIFileIOforChrome.so", "public": false }, { "path": "npNPAPIFileIOforChromex64.so", "public": false } ], "update_url": "http://clients2.google.com/service/update2/crx", "version": "0.0" }, "path": "lfjbhpnjiajjgnjganiaggebdhhpnbih\\0.0", "state": 1 }, "mlejngncgiocofkcbnnpaieapabmanfl": { "active_permissions": { "api": [ "devtools", "notifications" ], "explicit_host": [ "http://*/*" ] }, "events": [ "runtime.onInstalled" ], "from_bookmark": false, "from_webstore": true, "granted_permissions": { "api": [ "devtools", "notifications" ], "explicit_host": [ "http://*/*" ] }, "install_time": "12989962505148734", "location": 1, "manifest": { "background": { "scripts": [ "background.js" ] }, "description": "Saves changes in CSS and JS that was made via Chrome DevTools", "devtools_page": "devtools.html", "icons": { "128": "icon_128.png", "16": "icon_16.png", "48": "icon_48.png" }, "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRWX93rVhrtZ0GEM7RTJI9pGX2Ql9NoVSvWKr6b2xGNHJJCM5BTvGF1xCqnGzrjU2Yhbf4bDcusiRz53RCRSSpC3wpATM3pLFQ6ubVgH8vVAxW5zmHCnuoZlLp0GNW5h5Jq6tFYN3yFyctFW2NXRkLtpRkCH6eqhvLWCLxzNATowIDAQAB", "manifest_version": 2, "minimum_chrome_version": "17", "name": "DevTools Autosave - Installing...", "options_page": "options.html", "permissions": [ "notifications", "http://*/" ], "update_url": "http://clients2.google.com/service/update2/crx", "version": "0.0" }, "path": "mlejngncgiocofkcbnnpaieapabmanfl\\0.0", "state": 1 }, "ninejjcohidippngpapiilnmkgllmakh": { "active_permissions": { "api": [ "cookies", "tabs" ], "explicit_host": [ "http://*/*", "https://*/*" ], "scriptable_host": [ "http://*/*", "https://*/*" ] }, "disable_reasons": 1, "events": [ "runtime.onInstalled" ], "from_bookmark": false, "from_webstore": true, "granted_permissions": { "api": [ "cookies", "tabs" ], "explicit_host": [ "http://*/*", "https://*/*" ], "scriptable_host": [ "http://*/*", "https://*/*" ] }, "install_time": "12989962642966537", "location": 1, "manifest": { "background_page": "background.html", "browser_action": { "default_icon": "icon.png", "name": "YSlow" }, "content_scripts": [ { "js": [ "content.js", "yslow-chrome.js" ], "matches": [ "http://*/*", "https://*/*" ] } ], "description": "Make your pages faster with Yahoo!'s page performance tool", "icons": { "128": "128.png", "16": "16.png", "32": "32.png", "48": "48.png" }, "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRNg9Yw2+0MeiuqE4aDXWicL46yILo3cf8YMwZvPvtQPvD76csVkLwN3LOcVwsZmBKHREfWM50oa5GfnLuOTX1L7Usk0VmC5DXrZUkdV9ouaF47eMTiXHpgZsLc04COMdW3rskGgv8srL1LQCKn+YZE3AY/2TQ60dplC0X16n2mQIDAQAB", "name": "YSlow - Installing...", "options_page": "options.html", "permissions": [ "tabs", "cookies", "http://*/*", "https://*/*" ], "update_url": "http://clients2.google.com/service/update2/crx", "version": "0.0" }, "path": "ninejjcohidippngpapiilnmkgllmakh\\0.0", "state": 1 }, "ognampngfcbddbfemdapefohjiobgbdl": { "active_permissions": { "api": [ "debugger", "tabs" ], "explicit_host": [ "http://*/*", "https://*/*" ], "scriptable_host": [ "file:///*", "http://*/*", "https://*/*" ] }, "events": [ "runtime.onInstalled" ], "from_bookmark": false, "from_webstore": true, "granted_permissions": { "api": [ "debugger", "tabs" ], "explicit_host": [ "http://*/*", "https://*/*" ], "scriptable_host": [ "file:///*", "http://*/*", "https://*/*" ] }, "install_time": "12989044035404203", "lastpingday": "12989055688643437", "location": 1, "manifest": { "background_page": "extension.html", "browser_action": { "default_icon": "mt-icon.png", "icons": [ "mt-icon.png", "mt-icon-active.png", "mt-icon-disabled.png" ], "name": "MonitorTab" }, "content_scripts": [ { "js": [ "data_loader.js" ], "matches": [ "http://*/*", "https://*/*", "file:///*" ], "run_at": "document_end" } ], "description": "Get insight into the performance of your web applications.", "icons": { "128": "7271B57BF73ED8DD39E62247C6E55B11.png", "16": "9478EDE0A0F397A1B9CFE9A268895DB7.png", "32": "EAB84AFC4392F30491367F7CE3E8D498.png", "48": "B8D870CF42A2D08DBF33031604F51CC1.png" }, "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDm+jz32G1duFpqC9Gvkx3sxjCapLPeTrLqAxpUfTMUtpE8kmwEYc92LDOPzWooPzLINwqpNJNANQyvrJufzNENBDiDWY5QtHt/vXf25BM71Um+HistVJ35Cxg/wcmBXI/fi5qt7EQUDRW0hd0Bwo2m+mXiv4QGZNVz5Q8SaGG2tQIDAQAB", "name": "Speed Tracer (by Google) - Installing...", "permissions": [ "tabs", "http://*/*", "https://*/*", "debugger" ], "update_url": "http://clients2.google.com/service/update2/crx", "version": "0.0" }, "path": "ognampngfcbddbfemdapefohjiobgbdl\\0.0", "state": 1 }, }, "toolbar": [ "ognampngfcbddbfemdapefohjiobgbdl", "gplegfbjlmmehdoakndmohflojccocli", "jnihajbhpnppcggbcgedagnkighmdlei" ], "toolbarsize": -1, "ui": { "developer_mode": true } } } '@ $canaryDataPath = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) ` 'Google\Chrome SxS\User Data\Default' if (!(Test-Path $canaryDataPath)) { New-Item $canaryDataPath -Type Directory } $chromeExtensions | Out-File (Join-Path $canaryDataPath 'Master_Preferences') -Encoding UTF8 #download Chrome Canary (New-Object Net.WebClient).DownloadFile('https://dl.google.com/tag/s/appguid%3D%7B4ea16ac7-fd5a-47c3-875b-dbf4a2008c20%7D%26iid%3D%7B0281A7E2-6043-D983-8BBA-7FD622493C9D%7D%26lang%3Den%26browser%3D4%26usagestats%3D1%26appname%3DGoogle%2520Chrome%2520Canary%26needsadmin%3Dfalse/update2/installers/ChromeSetup.exe',"${env:\temp}\ChromeSetup.exe") &"${env:\temp}\ChromeSetup.exe" #run the installer ( | Out-Null waits for the process to exit) &"${env:\temp}\ChromeSetup.exe" | Out-Null
PowerShellCorpus/GithubGist/al3xisb_7703446_raw_e77024fd6c985a8915f5880174c3566cdfdf7408_copyFiles.ps1
al3xisb_7703446_raw_e77024fd6c985a8915f5880174c3566cdfdf7408_copyFiles.ps1
# Copy all documents from a library to another $source = Get-SPWeb "https://server/source" $destination = Get-SPWeb "https://server/destination" $files = $source.Lists["Source Library"].RootFolder.Files $to = $destination.Lists["Destination Library"].RootFolder foreach($item in $srcFiles) { if ($item.File) { $new = $to.Files.Add($item.Name, $item.OpenBinary(), $true) $fields = $item.Item.Fields | ? {!($_.sealed)} foreach($property in $fields) { if($item.Properties[$property.Title]) { if(!($new.Properties[$property.Title)) { $new.AddProperty($property.Title, $item.Properties[$property.Title]) } else { $new.Properties[$property.Title] = $item.Properties[$property.Title] } } } } } $destination.Dispose() $source.Dispose()
PowerShellCorpus/GithubGist/vktr_bfc18478bc73662f88e1_raw_2c0f70920a235591310ae04c13501651081e2dc7_install.ps1
vktr_bfc18478bc73662f88e1_raw_2c0f70920a235591310ae04c13501651081e2dc7_install.ps1
<# Copyright (C) 2014 Viktor Elofsson 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. #> $DOWNLOAD_URL = "http://www.hdkn.net/download/latest" $TEMP_DIR = Join-Path $env:TEMP "Hadouken" $INSTALLER = Join-Path $TEMP_DIR "installer.msi" function Download-File { param ( [string]$url, [string]$target ) Write-Host "Downloading $url to $target" $webClient = new-object System.Net.WebClient $webClient.DownloadFile($url, $target) } # Create temp directory if it does not exist if (!(Test-Path $TEMP_DIR)) { New-Item -ItemType Directory -Path $TEMP_DIR | Out-Null } # Download the Hadouken installer Download-File $DOWNLOAD_URL $INSTALLER # Execute installer silently $log = Join-Path $TEMP_DIR "install.log" $args = "/l*v $log /quiet /i $INSTALLER" Write-Host "Installing Hadouken" $pinfo = New-Object System.Diagnostics.ProcessStartInfo $pinfo.FileName = "msiexec.exe" $pinfo.Verb = "RunAs" $pinfo.Arguments = $args $process = [System.Diagnostics.Process]::Start($pinfo) $process.WaitForExit(); if ($process.ExitCode -ne 0) { Write-Error "Failed to install Hadouken. Check $log file." } else { Write-Host "Hadouken is installed. Point your browser to http://localhost:7890/ to access." }
PowerShellCorpus/GithubGist/rcurlette_7906029_raw_a73ed3e29c1226ac745510da3a65e771c0ad63d9_tridion-gui-extension-installer.ps1
rcurlette_7906029_raw_a73ed3e29c1226ac745510da3a65e771c0ad63d9_tridion-gui-extension-installer.ps1
write-output "/*** * _____ _ _ _____ ______ _ _ _____ _ _ _ * / ____| | | |_ _| | ____| | | (_) |_ _| | | | | | * | | __| | | | | | | |__ __ _| |_ ___ _ __ ___ _ ___ _ __ | | _ __ ___| |_ __ _| | | ___ _ __ * | | |_ | | | | | | | __| \ \/ / __/ _ \ '_ \/ __| |/ _ \| '_ \ | | | '_ \/ __| __/ _` | | |/ _ \ '__| * | |__| | |__| |_| |_ | |____ > <| || __/ | | \__ \ | (_) | | | | _| |_| | | \__ \ || (_| | | | __/ | * \_____|\____/|_____| |______/_/\_\\__\___|_| |_|___/_|\___/|_| |_| |_____|_| |_|___/\__\__,_|_|_|\___|_| * * " write-output "1********************************************************************" write-output "* Tridion GUI Extensions Installer 1.2 *" write-output "* Created by Robert Curlette, Yabolka *" write-output "* *" write-output "* Info: Installs a Tridion GUI Extension by doing the following: *" write-output "* - Copy Editor folder to Webroot/Editors *" write-output "* - Create VDir in Editors section in Tridion IIS *" write-output "* - Update System.config *" write-output "* *" write-output "* Optional, if existing: *" write-output "* - Copy dll files to WebRoot bin *" write-output "* - Copy Model Folder and files *" write-output "* *" write-output "* Assumes the following folders exist: *" write-output "* /Editor/ *" write-output "* /Editor/Configuration/editor.config *" write-output "* *" write-output "* Optional: *" write-output "* /Model/ *" write-output "* /Model/Configuration/model.config *" write-output "* /dlls/ *" write-output "* *" write-output "********************************************************************" # import various stuff we need [Reflection.Assembly]::LoadWithpartialName("System.Xml.Linq") | Out-Null [string]$filename #= $args[0] # Get zip file with GUI Extension - 2 formats, normal and Github $filename=$args[0] if($filename -eq $null) { $filename = Read-Host "Name of GUI Extension folder or .zip?" } if($filename -eq "") { write-output 'No GUI Extension specified, exiting' exit } if(!(Test-Path $filename)) { write-output("Warning: No file with name '" + $filename + "'. Please check filename and try again.") exit } Write-Output("GUI Extension " + $filename + " installation beginning..."); #************* Unzip files ******************* $shell_app=new-object -com shell.application if($filename.EndsWith(".zip")) { $zip_file = $shell_app.namespace((Get-Location).Path + "\$filename") Write-Output(" Unzipping " + $filename) $destination = $shell_app.namespace((Get-Location).Path) $destination.Copyhere($zip_file.items()) } if($filename.Contains(".")) { $guiExtensionName = $filename.Split(".")[0] } else { $guiExtensionName = $filename } $editorPath = ".\Editor" # Exit if no Editor folder found if(!(Test-Path Editor -pathType container)) { # Github format if(Test-Path $guiExtensionName\Editor -pathType container) { $editorPath = $guiExtensionName + '\Editor' } else { write-output ("Error: No 'Editor' folder found. Please make sure your .zip file contans an 'Editor' folder.") exit } } write-output(" Editor folder found at " + $editorPath) #************* Editor - Get Install location ******************* $tridionInstallLocationUser = Read-Host "Where is Tridion installed? (Default is C:\Program Files (x86)\Tridion)" [string]$tridionInstallLocation = "C:\Program Files (x86)\Tridion\" if($tridionInstallLocationUser -ne "") { $tridionInstallLocation = $tridionInstallLocationUser } [string]$editorInstallLocation = $tridionInstallLocation + "web\WebUI\Editors\" + $guiExtensionName + "\Editor" [string]$modelInstallLocation = $tridionInstallLocation + "web\WebUI\Models\" + $guiExtensionName + "\Model" write-output ("-> Begin Installing GUI Extension Editor to " + $editorInstallLocation) $editorConfigFile = "Configuration\editor.config" $modelConfigFile = "Configuration\model.config" write-output " Editor config @" + $editorInstallLocation\Configuration\editor.config #************* Copy Editor and Model files ******************* Copy-Item -Path $editorPath $editorInstallLocation -recurse if((Test-Path $editorInstallLocation\Configuration\Editor -pathType container)) { write-output (" Success: GUI Extension Editor Files copied to " + $editorInstallLocation) } if(!(Test-Path $editorInstallLocation\Configuration\editor.config)) { write-output(" Error: No editor config found at " + $editorInstallLocation + "\Configuration\editor.config + , exiting.") exit } if($hasModel) { write-output ("Begin Copying Model files to " + $modelInstallLocation) Copy-Item -Path ".\Model" $modelInstallLocation -recurse write-output (" Success: GUI Extension Model Files copied to " + $modelInstallLocation) } #************* Copy DLLs ******************* if(Test-Path dlls -pathType container) { $webRootBin = $tridionInstallLocation + "\web\WebUI\WebRoot\bin" write-output ("Begin Copying DLLs to " + $webRoot) Copy-Item -Path "dlls\*" $webRootBin -recurse write-output (" Success: Copied DLLs to " + $webRoot) } #************* Update Config ******************* # Update System.config write-output ("Begin updating system.config") $configFilename = $tridionInstallLocation + '\web\WebUI\WebRoot\Configuration\System.config' $conf = [xml](gc $configFilename) # "http://www.sdltridion.com/2009/GUI/Configuration" <-- Correct for 2011 and 2013?? # specify some namespace so we don't have empty xmlns in the children # Editor write-output ("Begin adding Editor to system.config") $editors = [System.Xml.XmlElement]$conf.Configuration.editors $myElement = $conf.CreateElement("editor", "http://www.sdltridion.com/2009/GUI/Configuration") $filenameAttr = $myElement.SetAttribute("name", $guiExtensionName) $installPathElement = $conf.CreateElement("installpath", "http://www.sdltridion.com/2009/GUI/Configuration") $installPathElement.InnerText = $editorInstallLocation $myElement.AppendChild($installPathElement) $configurationElement = $conf.CreateElement("configuration", "http://www.sdltridion.com/2009/GUI/Configuration") $configurationElement.InnerText = $editorConfigFile $myElement.AppendChild($configurationElement) $vdirElement = $conf.CreateElement("vdir", "http://www.sdltridion.com/2009/GUI/Configuration") $vdirElement.InnerText = $guiExtensionName $myElement.AppendChild($vdirElement) # $myElement.InnerXml = "<installpath>" + $editorInstallLocation + "</installpath><configuration>" + $editorConfigFile + "</configuration><vdir>" + $guiExtensionName + "</vdir>" $editors.AppendChild($myElement) write-output (" Success: Editor added to system.config") #Model if(Test-Path Model -pathType container) { [bool]$hasModel = 1 } if($hasModel) { write-output ("Begin adding Model to system.config") $models = [System.Xml.XmlElement]$conf.Configuration.models $myModelElement = $conf.CreateElement("model") $filenameAttr = $myModelElement.SetAttribute("name", $guiExtensionName) $installPathElement = $conf.CreateElement("installpath", "http://www.sdltridion.com/2009/GUI/Configuration") $installPathElement.InnerText = $modelInstallLocation $myModelElement.AppendChild($installPathElement) $configurationElement = $conf.CreateElement("configuration", "http://www.sdltridion.com/2009/GUI/Configuration") $configurationElement.InnerText = $modelConfigFile $myModelElement.AppendChild($configurationElement) $vdirElement = $conf.CreateElement("vdir", "http://www.sdltridion.com/2009/GUI/Configuration") $vdirElement.InnerText = $guiExtensionName $myModelElement.AppendChild($vdirElement) $models.AppendChild($myModelElement) write-output (" Success: Model added to system.config") } $conf.Save($configFilename) write-output (" Success: Updated and saved system.config") #************* Update IIS ******************* # Create VDIR in Tridion/WebUI/Editors and Models 2011 / 2013 need input $tridionVersion = Read-Host "Which version of Tridion do you use? (2011 or 2013. Default is 2013)" if(($tridionVersion -ne "2011") -and($tridionVersion -ne "2013")) { $tridionVersion = "2013" } write-output ("Begin updating IIS, adding Editor") $vdirPathEditor = 'IIS:\Sites\SDL Tridion ' + $tridionVersion + '\WebUI\Editors\' + $guiExtensionName New-Item $vdirPathEditor -type VirtualDirectory -physicalPath $editorInstallLocation write-output (" Success: Updating IIS and added new Virtual Dir at " + $vdirPathEditor) # Model if($hasModel) { write-output ("Begin updating IIS, adding Model") $vdirPathModel = 'IIS:\Sites\SDL Tridion ' + $tridionVersion + '\WebUI\Models\' + $guiExtensionName New-Item $vdirPathModel -type VirtualDirectory -physicalPath $modelInstallLocation write-output (" Success: Updating IIS and added new Virtual Dir at " + $vdirPathModel) } write-output ("============================================") write-output ("Finished successfully installing and configuring GUI Extenion " + $guiExtensionName )
PowerShellCorpus/GithubGist/Red-Folder_6643225_raw_2c3c214e839c463bbfef902a9e8043160996be92_HelperScripts.ps1
Red-Folder_6643225_raw_2c3c214e839c463bbfef902a9e8043160996be92_HelperScripts.ps1
function filesDifferent($sourceFilename, $targetFilename) { $targetFileExists = fileExists $targetFilename if (!($targetFileExists)) { return $TRUE } if ($sourceFilename.Contains(".jar")) { removeFolder "c:\tmp\jartest\source" removeFolder "c:\tmp\jartest\target" $extractSource = 'mkdir c:\tmp\jartest\source && cd c:\tmp\jartest\source && jar xvf "' + $sourceFilename + '"' #Write-Host $extractSource cmd /C $extractSource 2>&1 | Out-Null $extractTarget = 'mkdir c:\tmp\jartest\target && cd c:\tmp\jartest\target && jar xvf "' + $targetFilename + '"' #Write-Host $extractTarget cmd /C $extractTarget 2>&1 | Out-Null removeFolder "c:\tmp\jartest\source\META-INF" removeFolder "c:\tmp\jartest\target\META-INF" $result = foldersDifferent "c:\tmp\jartest\source" "c:\tmp\jartest\target" $FALSE #Write-Host "result = " $result removeFolder "c:\tmp\jartest\source" removeFolder "c:\tmp\jartest\target" return $result } else { if (@(Compare-Object $(Get-Content $sourceFilename -encoding byte) $(Get-Content $targetFilename -encoding byte) -sync 0).length -eq 0) { return $FALSE } else { return $TRUE } } } function fileExists($filename) { $targetFileExists = (Test-Path $targetFilename -PathType Leaf) if ($targetFileExists) { return $TRUE } else { return $FALSE } } function foldersDifferent($sourcePath, $targetPath, $syncFile) { $result = $FALSE #Write-Host "" #Write-Host "Comparing:" #Write-Host $sourceFolder.path #Write-Host $targetPath #Write-Host "" $sourceFolder = getFolderFromPath($sourcePath) foreach ($sourcefile in $sourceFolder.files) { #Write-Host "" #Write-Host "Found file = {0}", $sourceFile.name if (processFile $sourceFile $targetPath $syncFile) { #Write-Host "Different (1)" $result = $TRUE } } foreach ($subFolder in $sourceFolder.subfolders) { #Write-Host "" #Write-Host "Found subfolder = {0}", $subFolder.name $result = foldersDifferent $subFolder.path ($targetPath + "\" + $subFolder.name) $syncFile } return $result } function removeFolder($path) { if ((Test-Path -path $path)) { #Write-Host "Removing: {0}" $path Get-ChildItem -Path $path -Recurse | Remove-Item -force -recurse Remove-Item $path } } function processFile($sourceFile, $targetPath, $syncFile) { $result = $FALSE $sourceFilename = $sourceFile.path $targetFilename = $targetPath + "\" + $sourceFile.name #Write-Host "sourceFilename = {0}" $sourceFilename #Write-Host "targetFilename = {0}" $targetFilename $result = filesDifferent $sourceFilename $targetFilename #Write-Host "result = " $result if ($result) { #Write-Host "Different (2)" #$result = $TRUE if ($syncFile) { Write-Host("{0} Different", $sourceFilename) # Copy new over original $targetFileExists = fileExists $targetFilename if ($targetFileExists) { remove-item $targetFilename } New-Item -ItemType File -Path $targetFilename -Force copy-item $sourceFilename $targetFilename -Force } } return $result } function getParentFolderName($file) { $parentFolderName = $file.ParentFolder.name return $parentFolderName } function dump($obj) { foreach ($property in $obj.PSObject.Properties) { Write-Host "$($property.Name)=$($obj.PSObject.properties[$property.Name].Value)" } } function getFolderFromPath($path) { $fc = new-object -com scripting.filesystemobject $folder = $fc.getfolder($path) return $folder } function syncFolders($sourcePath, $targetPath) { Write-Host "sourcePath = {0}", $sourcePath Write-Host "targetPath = {0}", $targetPath Write-Host "===================================================================" Write-Host "Starting to process the plugin folder" Write-Host "===================================================================" $result = foldersDifferent $sourcePath $targetPath $TRUE if (!$result) { Write-Host "No differences found" } Write-Host "===================================================================" Write-Host "Completed processing the plugin folder" Write-Host "===================================================================" }
PowerShellCorpus/GithubGist/mbourgon_6873071_raw_7d7a8de12022a21eb8c319ff4e926a593c3e8319_sql_script_to_TFS.ps1
mbourgon_6873071_raw_7d7a8de12022a21eb8c319ff4e926a593c3e8319_sql_script_to_TFS.ps1
<# .SYNOPSIS Will script an object from SQL Server and CHECKIN/ADD to TFS. .EXAMPLE sql_script_to_TFS.ps1 -server yourservername -Database yourdatabasname -ScriptType "FULL" -Author yourTFSname -Comment "full checkin of database" #> # Purpose - given parameters, script out an object from a SQL Server, using SMO, then check it into TFS. #Scripting code gleefully copied from Phil Factor - the great parts that work are his, the errors are mine # https://www.simple-talk.com/sql/database-administration/automated-script-generation-with-powershell-and-smo/ #Other code from others copied and attributed below. #mdb 2013/12/03 adding ScriptType so that we can add "create database"-specific changes ONLY. # To do FULLs you will have to have -ScriptType = 'Full' parameter. By default it will do objects. #mdb 2013/12/05 trying to better bullet-proof the app against TF failures, which appear to occur randomly #mdb 2013/12/07 works great, though occasionally it cant script out an item. Trying to bulletproof that #mdb 2013/12/16 broke the individual-item portion, fixed. #mdb 2013/12/17 more cleanup and dealing with no objects found. #mdb 2014/09/08 removing .exe references, and changing folder name, so 2013 works. #param has to be the first line of the script. param( [Parameter(Mandatory=$true,Position=1)] [string]$Server, [Parameter(Mandatory=$true,Position=2)] [string]$Database, [string]$ScriptType ='Object', [string]$SchemaToScript, [string]$ObjectToScript, [string]$Author, [string]$Comment ) #make sure not ObjectToScript blank if scripting out the entire DB; makes checkin better #these are the parameters for testing #$Server='sql_repository'# the server it is on #$Database='model' # the name of the database you want to script as objects #$SchemaToScript = 'dbo' #$ObjectToScript = 'spy_tempdef' #$Author = 'michael.bourgon' #$ScriptType ='Object' #$Comment = 'bourgon_test' #setting up an error code for later $myerror = 0 cd c:\tfs_cli\en_workspace if ($comment -eq '') { $comment = "generic EN checkin"} if ($author -eq '') { $author = "erxnetwork\sqlservice"} #field is mandatory, if we dont know, use a known-valid. $ServerNameClean = "$($Server -replace '[\\\/]','__')" clear #writing this out for logging and troubleshooting. These are all the parameters except ScriptType write-host $Server, $Database, $SchemaToScript, $ObjectToScript, $Author, $Comment #TFS workspace folder - whatever you set it up as on your server $DirectoryToSaveTo='C:\TFS_CLI\EN_Workspace' # the directory where you want to store them # Load SMO assembly, and if we are running SQL 2008 DLLs load the SMOExtended and SQLWMIManagement libraries $v = [System.Reflection.Assembly]::LoadWithPartialName( 'Microsoft.SqlServer.SMO') if ((($v.FullName.Split(','))[1].Split('='))[1].Split('.')[0] -ne '9') { [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended') | out-null } [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SmoEnum') | out-null set-psdebug -strict # catch a few extra bugs $ErrorActionPreference = "stop" $My='Microsoft.SqlServer.Management.Smo' $srv = new-object ("$My.Server") $Server # attach to the server if ($srv.ServerType-eq $null) # if it managed to find a server { Write-Error "Sorry, but I could not find Server '$Server' " return } $scripter = new-object ("$My.Scripter") $srv # create the scripter #Add the various options we care about $scripter.Options.ToFileOnly = $true $scripter.Options.ExtendedProperties= $true # yes, we want these $scripter.Options.DRIAll= $true # and all the constraints $scripter.Options.Indexes= $true # Yup, these would be nice $scripter.Options.Triggers= $true # This should be includede $scripter.Options.AppendToFile = $False $scripter.Options.AllowSystemObjects = $False $scripter.Options.ClusteredIndexes = $True $scripter.Options.DriAll = $True $scripter.Options.ScriptDrops = $False $scripter.Options.IncludeHeaders = $False #so you do not get the one line "scripted at..." which would be NOW. #$scripter.Options.ToFileOnly = $True #$scripter.Options.Indexes = $True $scripter.Options.Permissions = $True $scripter.Options.WithDependencies = $False $scripter.Options.Bindings = $true $scripter.Options.IncludeDatabaseRoleMemberships = $true ################################################# #First, script out the database "create" itself.# ################################################# if (($Database) -and $ObjectToScript -eq '') #if database has a value but there is no object, script out the DB. { $db_scripter = new-object ("$My.Scripter") $srv # script out the database creation $db_scripter.options=$scripter.options # with the same options $db_scripter.options.filename="$($DirectoryToSaveTo)\$($ServerNameClean)\$($Database)\$($Database)_database_create.sql" # with the same options #explcitly creating the path for the DB script here. We still need to do it for all the sub-types. # Could probably move the $d declaration up here, but leaving it here for readability. $SavePath="$($DirectoryToSaveTo)\$($ServerNameClean)\$($Database)" # create the directory if necessary (SMO does not). if (!( Test-Path -path $SavePath )) # create it if not existing {Try { New-Item $SavePath -type directory | out-null } Catch [system.exception]{ Write-Error "error while creating '$SavePath' $_" return } } #Use TF to see if the object exists on our TFS server. # Optimization idea: DIR the entire subfolder on a FULL and compare all at once. $tf = &cmd /c "c:\TFS_CLI\App_2013\TF dir $/Randolph/$ServerNameClean/$Database/$($Database)_database_create.sql 2>&1" # Running the TF calls this way as per Simon Ejsing to ignore the error state and capture the actual error message # http://stackoverflow.com/questions/2095088/error-when-calling-3rd-party-executable-from-powershell-when-using-an-ide # However, that also means we need #Note that if the database create has not changed, it will still attempt to CHECKIN, but TFS will ignore as it is the same. if ($tf -like "No items match*" -or $tf -like "*is not found or not supported*") { "database script does not exist; scripting out and ADDing to TFS" if(Test-Path -Path $db_scripter.options.filename) { #delete the file manually, since we have seen permission issues where the $script cannot overwrite. $deleteme = "$SavePath\$($Database)_database_create.sql" $deleteme try { remove-item "$SavePath\$($Database)_database_create.sql" -force } catch { $error[0].Exception } } #putting in a try/catch so we get error messages if it breaks, and it can continue. try { $db_scripter.Script($srv.Databases[$Database]) # do it } Catch { "Error Message trying to script out $SavePath\$Filename" $error[0].Exception } "database create script done" $tf = &cmd /c "c:\TFS_CLI\App_2013\TF add $/Randolph/$ServerNameClean/$Database/$($Database)_database_create.sql 2>&1" $tf #use mass checkin at the end } else { "database script exists; get, check out, script to override, check in" $tf = &cmd /c "c:\TFS_CLI\App_2013\TF get ""$/Randolph/$ServerNameClean/$Database/$($Database)_database_create.sql"" /noprompt 2>&1" "database script GET results" $tf $tf = &cmd /c "c:\TFS_CLI\App_2013\TF checkout ""$/Randolph/$ServerNameClean/$Database/$($Database)_database_create.sql"" 2>&1" "database script CHECKOUT results" $tf "database checkout done" #If the file exists, manually delete; we have seen permission issues where $script cannot overwrite. if(Test-Path -Path $db_scripter.options.filename) { $deleteme = "$SavePath\$($Database)_database_create.sql" $deleteme try { #bug exists with standard remove - if there are read-only items in the same folder, -force is required remove-item "$SavePath\$($Database)_database_create.sql" -force } catch { $error[0].Exception } } #putting in a try/catch so we get error messages if it breaks, and it can continue. try { $db_scripter.Script($srv.Databases[$Database]) # do it } Catch { "Error Message trying to script out $SavePath\$Filename" $error[0].Exception } "database script out done" #use mass checkin at the end } } ########################### ## Scripting out Objects ## ########################### # we now get all the object types except extended stored procedures # first we get the bitmap of all the object types we want $all =[long] [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::all ` -bxor [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::ExtendedStoredProcedure # and we store them in a datatable $d = new-object System.Data.Datatable # get almost everything; skipping most service broker, information_schema, system_views, certificates (cannot be scripted) # there are other items that may need to be skipped, like SymmetricKeys in SSISDB # Yes, I realize the irony in skipping SB given that it is powering this. #putting in a try/catch so we get error messages if it breaks, and it can continue. try { $d=$srv.databases[$Database].EnumObjects([long]0x1FFFFFFF -band $all) | ` Where-Object {$_.Schema -ne 'sys'-and $_.Schema -ne "information_schema" -and $_.DatabaseObjectTypes -ne 'ServiceBroker' ` -and $_.DatabaseObjectTypes -ne 'Certificate' ` -and $_.DatabaseObjectTypes -ne 'MessageType' ` -and $_.DatabaseObjectTypes -ne 'ServiceContract' ` -and $_.DatabaseObjectTypes -ne 'ServiceQueue' ` -and $_.DatabaseObjectTypes -ne 'ServiceRoute' ` -and ($SchemaToScript -eq '' -or $_.Schema -eq $SchemaToScript) ` -and (($ObjectToScript -eq '' -and $ScriptType -eq 'Full') -or $_.Name -eq $ObjectToScript) ` -and ($_.Name -notmatch 'sp_MS*') } # mdb 2013/11/07 previous line skips replication objects. This comment below code as comment lines break extended 1-liner. } Catch { "Error Message trying to enumerate the database - may be logshipped or being restored" $myerror = 1 $error[0].Exception } # List every item that we are going to do $d = $d | sort $d | select databaseobjecttypes, schema, name if ($d.Count -gt 10000) { "skipping the database objects - more than 10000" } # Now write out each scriptable object as a file in the directory you specify #it appears that an empty array never actually enters the FOREACH, leaving variables unset # -and -$d.Count -ne 0 if ($myerror -eq 0 -and $d.Count -lt 10001) #20k of objects takes up 5gb of RAM in the PS script and causes problems { $d| FOREACH-OBJECT { # for every object we have in the datatable. "" #blank line so each block of error messages is separated out $SavePath="$($DirectoryToSaveTo)\$ServerNameClean\$Database\$($_.DatabaseObjectTypes)" # create the directory if necessary (SMO does not). if (!( Test-Path -path $SavePath )) # create it if not existing {Try { New-Item $SavePath -type directory | out-null } Catch [system.exception]{ Write-Error "error while creating '$SavePath' $_" return } } # tell the scripter object where to write it, and make sure it is actually writeable if ($_.schema) { $Filename = "$($_.schema -replace '[\\\/\:\.]','-').$($_.name -replace '[\\\/\:\.\ ]','-').sql"; } else { $Filename = "$($_.name -replace '[\\\/\:\.]','-').sql"; } $scripter.Options.FileName = "$SavePath\$Filename" $scripter.Options.FileName #print it out so we know what is being done $UrnCollection = new-object ('Microsoft.SqlServer.Management.Smo.urnCollection') $URNCollection.add($_.urn) ############################ # TFS code for each object # ############################ #Use TF to see if the object exists on our TFS server "checking to see if object exists" $tf = &cmd /c "c:\TFS_CLI\App_2013\TF dir $/Randolph/$ServerNameClean/$Database/$($_.DatabaseObjectTypes)/$Filename 2>&1" # Running all the TF commands this way as per Simon Ejsing to ignore the error state and capture the actual error message. # http://stackoverflow.com/questions/2095088/error-when-calling-3rd-party-executable-from-powershell-when-using-an-ide if ($tf -like "No items match*" -or $tf -like "*is not found or not supported*") { "no items match; scripting out and ADDing to TFS" try { $scripter.script($URNCollection) } Catch { "Error Message trying to script out $SavePath\$Filename" $error[0].Exception } "script done" $tf = &cmd /c "c:\TFS_CLI\App_2013\TF add /noprompt ""$/Randolph/$ServerNameClean/$Database/$($_.DatabaseObjectTypes)/$Filename"" 2>&1" $tf #mdb 2013/11/07 only do ONE checkin at the end if we are doing an entire database; all will have the same comment if ($ObjectToScript -ne '') { $tf = &cmd /c "c:\TFS_CLI\App_2013\TF checkin /author:$author /comment:""$comment"" /noprompt 2>&1" $tf } } else { "item exists; get, check out, script to override, check in" #noprompt causes it to crash, virtually every time $tf = &cmd /c "c:\TFS_CLI\App_2013\TF get ""$/Randolph/$ServerNameClean/$Database/$($_.DatabaseObjectTypes)/$Filename"" 2>&1" $tf $tf = &cmd /c "c:\TFS_CLI\App_2013\TF checkout ""$/Randolph/$ServerNameClean/$Database/$($_.DatabaseObjectTypes)/$Filename"" 2>&1" $tf #Delete file before scripting; we have seen permission issues. if(Test-Path -Path $scripter.options.filename) { try { remove-item "$SavePath\$Filename" -force } catch { $error[0].Exception } } try { $scripter.script($URNCollection) } Catch { "Error Message trying to script out $SavePath\$Filename" $error[0].Exception } #mdb 2013/12/03 making this part only run if it is a specific object; that way we can rerun an entire database if ($ObjectToScript -ne '') { $tf = &cmd /c "c:\TFS_CLI\App_2013\TF checkin /author:$author /noprompt /comment:""$comment"" ""$/Randolph/$ServerNameClean/$Database/$($_.DatabaseObjectTypes)/$Filename"" 2>&1" $tf } } } } #If it is a mass add or a database-specific, CHECKIN now. if ($ObjectToScript -eq '') { "final mass checkin" $tf = &cmd /c "c:\TFS_CLI\App_2013\TF checkin /author:$author /comment:""$comment"" /noprompt 2>&1" #$tf we do not need this one here because it will be shown below #$tf "mass checkin done" } "--------------------------------------------------------------------------" #if the checkin failed, UNDO so the next one does not make it worse. #The next checkin would probably fix it, but I have had to go back and manually undo. Not fun. #mdb 20131107 If there were any items to check in, get the results. Throws an error otherwise. #using Stej code to verify the variable exists; if no objects, $tf is never set, so it bombs here # http://stackoverflow.com/questions/3159949/in-powershell-how-do-i-test-whether-or-not-a-specific-variable-exists-in-global if (Test-Path variable:local:tf) { if ($tf -like "Changeset * checked in." -or $tf -like "There are no remaining changes to check in.") { #mdb 20131107 If there were any items to check in, get the results. Throws an error otherwise. if ((Test-Path variable:local:d) -and $ObjectToScript -eq '') { $tf } } else { "changes not made - errorlog follows" $tf "================================UNDO BEGINS==================================" $tf = &cmd /c "c:\TFS_CLI\App_2013\TF undo ""$/Randolph/$ServerNameClean/$Database/*.*"" /recursive 2>&1" $tf "=================================UNDO ENDS===================================" } } else { "No objects found, nothing done" } #TFS rollback code, should look something like this #c:\TFS_CLI\App_2013\TF undo $/Randolph/$ServerNameClean/VOAgent/DatabaseRole/*.* #No files checked in due to conflicting changes. These conflicting changes have been automatically resolved. Please try the check-in again. #rolling back code: c:\TFS_CLI\App_2013\TF undo $/Randolph/cm-01/VOAgent/DatabaseRole/*.* #for some reason "override:" did not work. #C:\TFS_CLI\EN_Workspace\server\file.sql #item exists; get, check out, script to override, check in #All files are up to date.
PowerShellCorpus/GithubGist/pbrumblay_6551936_raw_e6d72504186b2b1761a5cdca22c1ca0a8f75b75f_ftpsupload.ps1
pbrumblay_6551936_raw_e6d72504186b2b1761a5cdca22c1ca0a8f75b75f_ftpsupload.ps1
param ( [string]$file = $(throw "-file is required"), [string]$ftphostpath = $(throw "-ftphostpath is required"), [string]$username = $(throw "-username is required"), [string]$password = $(throw "-password is required") ) $f = dir $file $req = [System.Net.FtpWebRequest]::Create("ftp://$ftphostpath/" + $f.Name); $req.Credentials = New-Object System.Net.NetworkCredential($username, $password); $req.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile; $req.EnableSsl = $True; $req.UseBinary = $True $req.UsePassive = $True $req.KeepAlive = $True $req.ConnectionGroupName = "FTPS$username"; $fs = new-object IO.FileStream $f.FullName, 'Open', 'Read' $ftpStream = $req.GetRequestStream(); $req.ContentLength = $f.Length; try { $b = new-object Byte[](10000) while($true) { $r = $fs.Read($b, 0, 10000); if($r -eq 0) { break; } $ftpStream.Write($b, 0, $r); } } finally { if ($fs -ne $null) { $fs.Dispose(); } $ftpStream.Close(); $resp = $req.GetResponse(); $resp.StatusDescription; $resp.Close(); }
PowerShellCorpus/GithubGist/PaulStovell_10638996_raw_9ab5354b328dfef4675556455a89fd5cac012a99_gistfile1.ps1
PaulStovell_10638996_raw_9ab5354b328dfef4675556455a89fd5cac012a99_gistfile1.ps1
# Assumes that $appPoolName is set to the name of the application pool you want to modify. For example: # # $appPoolName = "DefaultAppPool" # $appPoolName = $OctopusParameters["YourVariable"] Import-Module WebAdministration $appPoolStatus = Get-WebAppPoolState $appPoolName if ($appPoolStatus.Value -eq "Stopped") { Write-Host "Service is already stopped" } else { Stop-WebAppPool $appPoolName Write-Host "Application pool is stopped" }
PowerShellCorpus/GithubGist/altrive_8425136_raw_68266ab3122945ad57acb81dabfb024e8fdd37c2_ToastNotification.ps1
altrive_8425136_raw_68266ab3122945ad57acb81dabfb024e8fdd37c2_ToastNotification.ps1
$ErrorActionPreference = "Stop" #Need to install Nuget packages before execute Add-Type -Path (Join-Path (Split-Path $profile -Parent) "packages\Windows7APICodePack-Core.1.1.0.0\lib\Microsoft.WindowsAPICodePack.dll" -Resolve) Add-Type -Path (Join-Path (Split-Path $profile -Parent) "\packages\Windows7APICodePack-Shell.1.1.0.0\lib\Microsoft.WindowsAPICodePack.Shell.dll" -Resolve) <# #TODO: Define Interop code to register shortcut with appid $referencedAssemblies = @( [MS.WindowsAPICodePack.Internal.PropVariant].Assembly.FullName, [Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties].Assembly.FullName ) Add-Type -ReferencedAssemblies @([MS.WindowsAPICodePack.Internal.PropVariant].Assembly.FullName) -TypeDefinition @" //省略 "@ #> $APP_ID = "ISEToast" $shortcutPath = [Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData) + "\Microsoft\Windows\Start Menu\Programs\ISEToast.lnk"; if (![IO.File]::Exists($shortcutPath)) { #TODO: Create shortcut <# #Create shortcut to StartMenu with AppId(ISEToast) $exePath = [Diagnostics.Process]::GetCurrentProcess().MainModule.FileName #$newShortcut = [IShellLinkW](New-Object CShellLink) [IShellLinkW]$newShortcut = [Utility]::GetShellLinkW() $newShortcut.SetPath($exePath) $newShortcut.SetArguments("") $newShortcutProperties = [IPropertyStore] $newShortcut; try { $appId = new PropVariant($APP_ID) $newShortcutProperties.SetValue([Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties]::System.AppUserModel.ID, $appId); $newShortcutProperties.Commit() } finally { if ($appId -ne $null){ $appId.Dispose() } } $newShortcutSave = [IPersistFile] $newShortcut; $newShortcutSave.Save($shortcutPath, $true); #> } $title = "タイトル" $message = "メッセージ。。。。。" #Load WinRT types [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null #ToastTemplateType <http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.notifications.toasttemplatetype.aspx> $toastXml = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastImageAndText04) #Convert to .NET type $toastXml = [xml] $toastXml.GetXml() $imageElements = $toastXml.GetElementsByTagName("image"); $imageElements[0].Attributes.GetNamedItem("src").Value = "file:///" + ""; #Fill in the text elements $stringElements = $toastXml.GetElementsByTagName("text") $stringElements[0].AppendChild($toastXml.CreateTextNode($title)) > $null $stringElements[1].AppendChild($toastXml.CreateTextNode($message)) > $null #Convert to WinRT type $x = New-Object Windows.Data.Xml.Dom.XmlDocument $x.LoadXml($toastXml.OuterXml) $toast = New-Object Windows.UI.Notifications.ToastNotification($x) <# $toast.add_Activated({ param ($object, $args) Write-Host "Toast notification activated" }) > $null $toast.add_Dismissed({ param ($object, $args) Write-Host "Toast notification dismissed" }) > $null $toast.add_Failed({ param ($object, $args) Write-Host "Toast notification failed" }) > $null #> $notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($APP_ID) $notifier.Show($toast)
PowerShellCorpus/GithubGist/JayBazuzi_c2a6650657acf9f82a0f_raw_ac9d1922a017e96c2ec7b03352854e5bd9c1050e_BoxStarters.ps1
JayBazuzi_c2a6650657acf9f82a0f_raw_ac9d1922a017e96c2ec7b03352854e5bd9c1050e_BoxStarters.ps1
# dev http://boxstarter.org/package/sysinternals,resharper,ncrunch,git,poshgit # desktop http://boxstarter.org/package/lastpass,googlechrome,skype,steam,putty,dotnet35 # kids http://boxstarter.org/package/minecraft,vlc
PowerShellCorpus/GithubGist/jrnold_4327373_raw_446d86154e28e6d82709a5c139d5e62b0069dbc5_gistfile1.ps1
jrnold_4327373_raw_446d86154e28e6d82709a5c139d5e62b0069dbc5_gistfile1.ps1
For ($i=1; $i -le 4; $i++) { model --refresh=0 --seed=12345 --chain_id=$i --samples=samples$i.csv }
PowerShellCorpus/GithubGist/ebibibi_7426819_raw_ae9760e88bb72bb802de3c7e9460a1a49c2e9017_Install-SCOMAgents.ps1
ebibibi_7426819_raw_ae9760e88bb72bb802de3c7e9460a1a49c2e9017_Install-SCOMAgents.ps1
#This script installs SCOM agents to several clients. # #ex) #.\Install-SCOMAgent.ps1 -ServerName scomserver.domain.name -Targets @("client1.domain.name", "client2.domain.name") Param( [parameter(mandatory=$true)]$ServerName, [parameter(mandatory=$true)]$Targets ) $InstallAccount = Get-Credential $session = New-PSSession -ComputerName $ServerName -Credential $InstallAccount Invoke-Command -Session $session -ScriptBlock { Import-Module OperationsManager foreach($Target in $using:Targets) { Write-Host "Install SCOM Agent to $Target ..." $PrimaryMgmtServer = Get-SCOMManagementServer -Name $using:ServerName Install-SCOMAgent -Name $Target -PrimaryManagementServer $PrimaryMgmtServer -ActionAccount $using:InstallAccount } }
PowerShellCorpus/GithubGist/obscuresec_25e8a142eb08bf237799_raw_3748b5b7a50ea148c00ebea6f94f06ed22eaafac_gistfile1.ps1
obscuresec_25e8a142eb08bf237799_raw_3748b5b7a50ea148c00ebea6f94f06ed22eaafac_gistfile1.ps1
function Set-MacAttribute { <# .SYNOPSIS Sets the modified, accessed and created (Mac) attributes for a file based on another file or input. PowerSploit Function: Set-MacAttribute Author: Chris Campbell (@obscuresec) License: BSD 3-Clause Required Dependencies: None Optional Dependencies: None Version: 1.0.0 .DESCRIPTION Set-MacAttribute sets one or more Mac attributes and returns the new attribute values of the file. .EXAMPLE PS C:\> Set-MacAttribute -FilePath c:\test\newfile -OldFilePath c:\test\oldfile .EXAMPLE PS C:\> Set-MacAttribute -FilePath c:\demo\test.xt -All "01/03/2006 12:12 pm" .EXAMPLE PS C:\> Set-MacAttribute -FilePath c:\demo\test.txt -Modified "01/03/2006 12:12 pm" -Accessed "01/03/2006 12:11 pm" -Created "01/03/2006 12:10 pm" .LINK http://www.obscuresec.com/2014/05/touch.html #> [CmdletBinding(DefaultParameterSetName = 'Touch')] Param ( [Parameter(Position = 1,Mandatory = $True)] [ValidateNotNullOrEmpty()] [String] $FilePath, [Parameter(ParameterSetName = 'Touch')] [ValidateNotNullOrEmpty()] [String] $OldFilePath, [Parameter(ParameterSetName = 'Individual')] [DateTime] $Modified, [Parameter(ParameterSetName = 'Individual')] [DateTime] $Accessed, [Parameter(ParameterSetName = 'Individual')] [DateTime] $Created, [Parameter(ParameterSetName = 'All')] [DateTime] $AllMacAttributes ) Set-StrictMode -Version 2.0 #Helper function that returns an object with the MAC attributes of a file. function Get-MacAttribute { param($OldFileName) if (!(Test-Path $OldFileName)){Throw "File Not Found"} $FileInfoObject = (Get-Item $OldFileName) $ObjectProperties = @{'Modified' = ($FileInfoObject.LastWriteTime); 'Accessed' = ($FileInfoObject.LastAccessTime); 'Created' = ($FileInfoObject.CreationTime)}; $ResultObject = New-Object -TypeName PSObject -Property $ObjectProperties Return $ResultObject } #test and set variables if (!(Test-Path $FilePath)){Throw "$FilePath not found"} $FileInfoObject = (Get-Item $FilePath) if ($PSBoundParameters['AllMacAttributes']){ $Modified = $AllMacAttributes $Accessed = $AllMacAttributes $Created = $AllMacAttributes } if ($PSBoundParameters['OldFilePath']){ if (!(Test-Path $OldFilePath)){Write-Error "$OldFilePath not found."} $CopyFileMac = (Get-MacAttribute $OldFilePath) $Modified = $CopyFileMac.Modified $Accessed = $CopyFileMac.Accessed $Created = $CopyFileMac.Created } if ($Modified) {$FileInfoObject.LastWriteTime = $Modified} if ($Accessed) {$FileInfoObject.LastAccessTime = $Accessed} if ($Created) {$FileInfoObject.CreationTime = $Created} Return (Get-MacAttribute $FilePath) }
PowerShellCorpus/GithubGist/urasandesu_51e7d31b9fa3e53489a7_raw_ceafe2b144a6394fa82bf9863f0f42eee29752b4_Get-HelpByMarkdown.ps1
urasandesu_51e7d31b9fa3e53489a7_raw_ceafe2b144a6394fa82bf9863f0f42eee29752b4_Get-HelpByMarkdown.ps1
# # File: Get-HelpByMarkdown.ps1 # # Author: Akira Sugiura ([email protected]) # # # Copyright (c) 2014 Akira Sugiura # # This software is MIT License. # # 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. # <# .SYNOPSIS Gets the comment-based help and converts to GitHub Flavored Markdown. .PARAMETER Name A command name to get comment-based help. .EXAMPLE & .\Get-HelpByMarkdown.ps1 Select-Object > .\Select-Object.md DESCRIPTION ----------- This example gets comment-based help of `Select-Object` command, and converts GitHub Flavored Markdown format, then saves it to `Select-Object.md` in current directory. .INPUTS System.String .OUTPUTS System.String #> [CmdletBinding()] param ( [Parameter(Mandatory = $True)] $Name ) function EncodePartOfHtml { param ( [string] $Value ) ($Value -replace '<', '&lt;') -replace '>', '&gt;' } function GetCode { param ( $Example ) $codeAndRemarks = (($Example | Out-String) -replace ($Example.title), '').Trim() -split "`r`n" $code = New-Object "System.Collections.Generic.List[string]" for ($i = 0; $i -lt $codeAndRemarks.Length; $i++) { if ($codeAndRemarks[$i] -eq 'DESCRIPTION' -and $codeAndRemarks[$i + 1] -eq '-----------') { break } if (1 -le $i -and $i -le 2) { continue } $code.Add($codeAndRemarks[$i]) } $code -join "`r`n" } function GetRemark { param ( $Example ) $codeAndRemarks = (($Example | Out-String) -replace ($Example.title), '').Trim() -split "`r`n" $isSkipped = $false $remark = New-Object "System.Collections.Generic.List[string]" for ($i = 0; $i -lt $codeAndRemarks.Length; $i++) { if (!$isSkipped -and $codeAndRemarks[$i - 2] -ne 'DESCRIPTION' -and $codeAndRemarks[$i - 1] -ne '-----------') { continue } $isSkipped = $true $remark.Add($codeAndRemarks[$i]) } $remark -join "`r`n" } try { if ($Host.UI.RawUI) { $rawUI = $Host.UI.RawUI $oldSize = $rawUI.BufferSize $typeName = $oldSize.GetType().FullName $newSize = New-Object $typeName (500, $oldSize.Height) $rawUI.BufferSize = $newSize } $full = Get-Help $Name -Full @" # $($full.Name) ## SYNOPSIS $($full.Synopsis) ## SYNTAX ``````powershell $((($full.syntax | Out-String) -replace "`r`n", "`r`n`r`n").Trim()) `````` ## DESCRIPTION $(($full.description | Out-String).Trim()) ## PARAMETERS "@ + $(foreach ($parameter in $full.parameters.parameter) { @" ### -$($parameter.name) &lt;$($parameter.type.name)&gt; $(($parameter.description | Out-String).Trim()) `````` $(((($parameter | Out-String).Trim() -split "`r`n")[-5..-1] | % { $_.Trim() }) -join "`r`n") `````` "@ }) + @" ## INPUTS $($full.inputTypes.inputType.type.name) ## OUTPUTS $($full.returnValues.returnValue[0].type.name) ## NOTES $(($full.alertSet.alert | Out-String).Trim()) ## EXAMPLES "@ + $(foreach ($example in $full.examples.example) { @" ### $(($example.title -replace '-*', '').Trim()) ``````powershell $(GetCode $example) `````` $(GetRemark $example) "@ }) + @" "@ } finally { if ($Host.UI.RawUI) { $rawUI = $Host.UI.RawUI $rawUI.BufferSize = $oldSize } }
PowerShellCorpus/GithubGist/mikeplate_6162420_raw_de9b36dd52763165ca636a1cb2590a3581e2bb3c_ColumnUsage.ps1
mikeplate_6162420_raw_de9b36dd52763165ca636a1cb2590a3581e2bb3c_ColumnUsage.ps1
param ( [String]$SiteUrl = 'http://spdev', [String]$FieldName = 'Title' ) Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue $site = Get-SPSite $SiteUrl "Showing where ""$FieldName"" is used" foreach ($web in $site.AllWebs) { foreach ($ctype in $web.ContentTypes) { if ($ctype.Fields.ContainsField($FieldName)) { $web.Url + ' Content Type: ' + $ctype.Name } } foreach ($list in $web.Lists) { if ($list.Fields.ContainsField($FieldName)) { $web.Url + ' List: ' + $list.Title } } }
PowerShellCorpus/GithubGist/tmenier_9199441_raw_85e36e60da07a2cd1c723d798a283340df0eb482_CopyDeployableWebFiles.ps1
tmenier_9199441_raw_85e36e60da07a2cd1c723d798a283340df0eb482_CopyDeployableWebFiles.ps1
function copy-deployable-web-files($proj_path, $deploy_dir) { # copy files where Build Action = "Content" $proj_dir = split-path -parent $proj_path [xml]$xml = get-content $proj_path $xml.Project.ItemGroup | % { $_.Content } | % { $_.Include } | ? { $_ } | % { $from = "$proj_dir\$_" $to = split-path -parent "$deploy_dir\$_" if (!(test-path $to)) { md $to } cp $from $to } # copy everything in bin cp "$proj_dir\bin" $deploy_dir -recurse }
PowerShellCorpus/GithubGist/josheinstein_cf99bcfdeb573cbbf6a7_raw_6ac161404e9ce9b04d82aa8b32cf62ff99b7f4b0_Write-Highlight.ps1
josheinstein_cf99bcfdeb573cbbf6a7_raw_6ac161404e9ce9b04d82aa8b32cf62ff99b7f4b0_Write-Highlight.ps1
#.SYNOPSIS # Writes text to the host, highlighting portions of the text that # match one or more regular expression patterns in a different # color. # #.DESCRIPTION # There are two forms that this command can take: One which specifies # a single regular expression pattern and a single color (which defaults # to yellow if not specified), and another that takes a hashtable that # consists of regular expressions for keys and colors for values. # See the examples for usage. # #.EXAMPLE # # Phone number will be written in green text # # Email address will be written in yellow text # Write-Highlight "Phone: 555-555-9999, Email: [email protected]" -Colors @{ # '\d{3}-\d{3}-\d{4}' = 'Green' # '[a-z0-9]+@[a-z0-9]+\.com' = 'Yellow' # } # #.EXAMPLE # # Numbers will be written in yellow text # Write-Highlight "Phone: 555-555-9999, Email: [email protected]" -Pattern '\d+' function Write-Highlight { [CmdletBinding(DefaultParameterSetName='SinglePattern')] param( [Parameter(Position=1, Mandatory=$true)] [String]$Text, # A regular expression that will be matched in the Text # parameter and highlighted in yellow. [Parameter(ParameterSetName='SinglePattern', Mandatory=$true)] [Regex]$Pattern, # The color to write the matched portion of the text. # Defaults to Yellow. [Parameter(ParameterSetName='SinglePattern')] [ConsoleColor]$MatchColor = $MatchColor, # A hashtable consisting of keys that are the regular expression # pattern to match and values that are the color to use. # Colors must be convertible to ConsoleColor enumeration values. [Parameter(ParameterSetName='MultiplePatterns', Mandatory=$true)] [Hashtable]$Colors, # The default color to write the non-highlighted text. # Defaults to the current foreground color. [Parameter()] [ConsoleColor]$DefaultColor = $Host.UI.RawUI.ForegroundColor, # Specifies that the content displayed in the console does not # end with a newline character. [Parameter()] [Switch]$NoNewLine ) process { # Normalize the parameter sets. # If a single pattern parameter set was used, pack it # into the same variable we use for the multi parameter set. if ($PSCmdlet.ParameterSetName -eq 'SinglePattern') { $Colors = @{} $Colors.Add($Pattern.ToString(), [ConsoleColor]::Yellow) } # Run each regular expression on the text, sorting the # regex matches by their Index property. This will be # important when we start breaking up the text into chunks # of non-colored and colored text. $AllMatches = @($Colors.GetEnumerator() | %{ $Pattern = [Regex]$_.Key $Color = [ConsoleColor]$_.Value # Append a new property to the Match objects that holds # the corresponding color. This makes it easier than # having to go look up the right color later. $Pattern.Matches($Text) | Add-Member -PassThru NoteProperty Color $Color } | Sort Index) # Loop through segments of the string, starting at position 0. $i = 0 while ($i -lt $Text.Length) { # Find the closest match that comes after the current # string position. $NextMatch = $AllMatches | ?{ $_.Index -ge $i } | Select -First 1 if ($NextMatch) { # We still have matches. # Write the portion of the string that comes before the match. # (This could potentially be an empty string if our position # is currently at the beginning of a match.) Write-Host $Text.Substring($i, $NextMatch.Index-$i) -ForegroundColor $DefaultColor -NoNewline # Write the portion of the string that matched in its # designated color. (Note, newline is suppressed.) Write-Host $NextMatch.Value -ForegroundColor $NextMatch.Color -NoNewline # Advance the string position $i = $NextMatch.Index + $NextMatch.Length } else { # No more matches. Write the remainder of the string. # This could potentially be an empty string. Write-Host $Text.Substring($i) -ForegroundColor $DefaultColor -NoNewline break } } # Since we've been suppressing newlines all this time, we # need to write out one final newline (unless NoNewLine is true) if (!$NoNewLine) { Write-Host } } }
PowerShellCorpus/GithubGist/JamesTryand_6915577_raw_b1f59833366cb12625105158e3364e25a0716c7a_windowsstatuscodes.ps1
JamesTryand_6915577_raw_b1f59833366cb12625105158e3364e25a0716c7a_windowsstatuscodes.ps1
$windowsHttpCodes = [net.httpstatuscode]|gm -s|?{$_.membertype -eq 'Property'}|select name, @{n='code';e={ iex "[int][net.httpstatuscode]::$($_.Name)" } }
PowerShellCorpus/GithubGist/ao-zkn_bb8cda1233c2459b187c_raw_f84abd1f1c84c5cba29c2afd37da9dfac37e4e03_Set-LogSetting.ps1
ao-zkn_bb8cda1233c2459b187c_raw_f84abd1f1c84c5cba29c2afd37da9dfac37e4e03_Set-LogSetting.ps1
### 初期値の設定 # ログファイルパス Remove-Variable -Name LogFilePath -Force -ea silentlycontinue Set-Variable -Name LogFilePath -Value "common.log" -Option ReadOnly -Scope "Global" # ログレベル Remove-Variable -Name LogLevel -Force -ea silentlycontinue Set-Variable -Name LogLevel -Value 1 -Option ReadOnly -Scope "Global" # ログの文字エンコード Remove-Variable -Name LogEncoding -Force -ea silentlycontinue Set-Variable -Name LogEncoding -Value "utf8" -Option ReadOnly -Scope "Global" # ------------------------------------------------------------------ # XMLファイルよりログ出力の設定情報をセットする # 関数名:Set-LogSetting # 引数 :XMLFilePath XMLファイルパス # :Appender アペンダ # 戻り値:なし # ------------------------------------------------------------------ function Set-LogSetting([String]$XMLFilePath, [String]$Appender){ #XMLファイルの読込 $xmlLogSetting = [XML](Get-Content $XMLFilePath -encoding "utf8") # 指定したアペンダを取得 $params = $xmlLogSetting.configuration.appender | Where-Object{$_.name -eq $Appender} if($params){ foreach($param In $params){ # ログファイルパス if("file" -eq $param.name){ Set-Variable -Name LogFilePath -Value ($param.value) -Option ReadOnly -Scope "Global" -Force } # ログ文字エンコード if("encode" -eq $param.name){ Set-Variable -Name LogEncoding -Value ($param.value) -Option ReadOnly -Scope "Global" -Force } # ログの種類 if("loglevel" -eq $param.name){ Set-Variable -Name LogLevel -Value ($param.value) -Option ReadOnly -Scope "Global" -Force } } } }
PowerShellCorpus/GithubGist/naraga_3240847_raw_947448b9012bd9ad47c023251d706315f086dbee_profile.ps1
naraga_3240847_raw_947448b9012bd9ad47c023251d706315f086dbee_profile.ps1
function Get-GitRepoPath { @( $i=0;` $pwd.path -split "\\"| ` %{"$(@($pwd.path -split '\\')[0..$i] -join '\')";$i++} | ` ? {test-path "$_\\.git"})[0] } function Get-GitCurrentBranch { ((cat "$(Get-GitRepoPath)\.git\HEAD") -split "/")[-1] } function prompt { "$($pwd.path)[$(Get-GitCurrentBranch)]>" }
PowerShellCorpus/GithubGist/billerby_4214535_raw_78805472449a3fe38bf1a7419bc1ab31f3f11395_strip-content-from-alf-data-dir.ps1
billerby_4214535_raw_78805472449a3fe38bf1a7419bc1ab31f3f11395_strip-content-from-alf-data-dir.ps1
# Script that traverses a directory and strips all content from files larger than # $filesizelimit This comes handy when we need to transfer a backuped directory # structure to our local environment. We are normally not interested in the content # of the files when debugging. # Version 0.1, # By Erik Billerby, billerby[-at-]acando.com # Location where 7-Zip is installed on your computer. # The default is in a folder, '7-Zip' in your Program Files directory. # The backup archive name needs to be on the following format for this script to # operate correctly backup_[YYYY-MM-DD].zip # To run script: start cmd.exe with administrator privileges: # prompt> powershell.exe # prompt> .\strip-content-from-alf-data-dir.ps1 # To begin with, enter the date for the backup you want to process below: # TODO - parameterize $backupdate="2012-10-13" # Only strip files larger than the limit stated below: $filesizelimit=25KB # Alias for 7-zip if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"} set-alias sz "$env:ProgramFiles\7-Zip\7z.exe" # Path to the directory that contain the backups $backupdir="C:\Alfresco\backups" # Path to directory to store the stripped version $strippeddir="C:\Alfresco-stripped-backups" # copy the backup file to a new temporary directory echo $backupdir"\backup_"$backupdate".zip" Copy-Item $backupdir"\backup_"$backupdate".zip" $strippeddir "Uncompressing backup file" $outputOption = "-o$strippeddir/backup_$backupdate" sz x $strippeddir\"backup_"$backupdate".zip" $outputOption $dirtostrip = "$strippeddir\backup_$backupdate\$backupdate\alf_data\contentstore" $files=((dir $dirtostrip -recurse) |?{$_.psiscontainer -eq $false}) "stripping content from files larger than $filesizelimit" # feedback, number of trunkaded files $matches = 0; $totalfiles = 0; for ($i=0;$i -ne $files.count; $i++) { if ($files[$i] -eq $null) {continue} if ($files[$i].length -gt $filesizelimit) { Clear-Content $files[$i].FullName $matches++; } $totalfiles++; } "$matches files of total $totalfiles have had their content stripped..." sz a $strippeddir\stripped-$backupdate.zip $strippeddir\backup_$backupdate\$backupdate
PowerShellCorpus/GithubGist/mmooney_4539567_raw_17f05c1f028493c48c2767f1337a27852aeea0ea_deploy.ps1
mmooney_4539567_raw_17f05c1f028493c48c2767f1337a27852aeea0ea_deploy.ps1
#Modified and simplified version of https://www.windowsazure.com/en-us/develop/net/common-tasks/continuous-delivery/ #From: #https://gist.github.com/3694398 $subscription = "[SubscriptionName]" #this the name from your .publishsettings file $service = "[ServiceName]" #this is the name of the cloud service $storageAccount = "[StorageAccountName]" #this is the name of the storage service $slot = "production" #staging or production $package = "[Fully Qualified Path to .cspkg]" $configuration = "[Fully Qualified path to .cscfg]" $publishSettingsFile = "[Path to .publishsettings file, relative is OK]" $timeStampFormat = "g" $deploymentLabel = "PowerShell Deploy to $service" Write-Output "Slot: $slot" Write-Output "Subscription: $subscription" Write-Output "Service: $service" Write-Output "Storage Account: $storageAccount" Write-Output "Slot: $slot" Write-Output "Package: $package" Write-Output "Configuration: $configuration" Write-Output "Running Azure Imports" Import-Module "C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure\*.psd1" Import-AzurePublishSettingsFile $publishSettingsFile Set-AzureSubscription -CurrentStorageAccount $storageAccount -SubscriptionName $subscription Set-AzureService -ServiceName $service -Label $deploymentLabel function Publish(){ $deployment = Get-AzureDeployment -ServiceName $service -Slot $slot -ErrorVariable a -ErrorAction silentlycontinue if ($a[0] -ne $null) { Write-Output "$(Get-Date -f $timeStampFormat) - No deployment is detected. Creating a new deployment. " } if ($deployment.Name -ne $null) { #Update deployment inplace (usually faster, cheaper, won't destroy VIP) Write-Output "$(Get-Date -f $timeStampFormat) - Deployment exists in $servicename. Upgrading deployment." UpgradeDeployment } else { CreateNewDeployment } } function CreateNewDeployment() { write-progress -id 3 -activity "Creating New Deployment" -Status "In progress" Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: In progress" $opstat = New-AzureDeployment -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel - ServiceName $service $completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot $completeDeploymentID = $completeDeployment.deploymentid write-progress -id 3 -activity "Creating New Deployment" -completed -Status "Complete" Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: Complete, Deployment ID: $completeDeploymentID" } function UpgradeDeployment() { write-progress -id 3 -activity "Upgrading Deployment" -Status "In progress" Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: In progress" # perform Update-Deployment $setdeployment = Set-AzureDeployment -Upgrade -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service -Force $completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot $completeDeploymentID = $completeDeployment.deploymentid write-progress -id 3 -activity "Upgrading Deployment" -completed -Status "Complete" Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: Complete, Deployment ID: $completeDeploymentID" } Write-Output "Create Azure Deployment" Publish
PowerShellCorpus/GithubGist/peaeater_c7ecd4ef6a0996353ee2_raw_606f9f460ad99d274e2eb0a578c88adbbc0265b0_ocr.ps1
peaeater_c7ecd4ef6a0996353ee2_raw_606f9f460ad99d274e2eb0a578c88adbbc0265b0_ocr.ps1
# ocr tif/png to txt # requires tesseract Param( [string]$ext = "tif", [string]$indir = ".", [string]$outdir = $indir ) if (!(test-path $outdir)) { mkdir $outdir } $files = ls "$indir\*.*" -include *.$ext foreach ($file in $files) { $o = "$outdir\{0}" -f $file.BaseName $args = "`"$file`" `"$o`"" start-process tesseract $args -wait -NoNewWindow }
PowerShellCorpus/GithubGist/guitarrapc_09e7afdc70356e487470_raw_e93acde05e59b4d11f652438a1b91dd7311d1d69_LocalMD5.ps1
guitarrapc_09e7afdc70356e487470_raw_e93acde05e59b4d11f652438a1b91dd7311d1d69_LocalMD5.ps1
Get-FileHash C:\tools\FileName.zip -Algorithm md5 <# Algorithm Hash Path --------- ---- ---- MD5 0A58C113534FAA4D531442E8A3221E7A C:\tools\FileName.zip #>
PowerShellCorpus/GithubGist/ddhahn_4692388_raw_576d1070145e6a4384d86c4cc7c2c545739bf6a2_ipfilter.ps1
ddhahn_4692388_raw_576d1070145e6a4384d86c4cc7c2c545739bf6a2_ipfilter.ps1
del "c:\temp\vpn_machines.txt" $machines = gc "c:\temp\hosts" |% {$_.split("`t")[0]} foreach ($machine in $machines) { if ($machine.startswith('10.54')) { Out-File -InputObject $machine "c:\temp\vpn_machines.txt" -Encoding "ASCII" -append } }
PowerShellCorpus/GithubGist/birryree_2e072b0fd047faebd358_raw_b57c92cd8ce4597840a014aed2e192738e06c72b_gistfile1.ps1
birryree_2e072b0fd047faebd358_raw_b57c92cd8ce4597840a014aed2e192738e06c72b_gistfile1.ps1
# Load all computer names from a text file into an array/list $computers = Get-Content -path C:\users\brynet01\desktop\Computers.txt # Loop over each computer name in the array/list foreach ($computer in $computers) { # Open a remote registry connection to the current value of $computer. This requires going into the .NET library # The 'LocalMachine' bit specifies that the remote registry base should be HKLM $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer) # Get the entire registry key for this path of the registry $updatePolicy = $reg.OpenSubkey("SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate") # Get another registry key $wsus = $reg.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update") # Format a new line of output for printing to a file. the GetValue("x") function is to retrieve a particular value of the registry key $output = "{0},{1},{2},{3}" -f $computer, $wsus.GetValue("TargetGroup"), $wsus.GetValue("WUServer") $updatePolicy.GetValue("TargetGroup") # Append output to the file C:\users\brynet01\desktop\WSUSclient.txt add-content C:\users\brynet01\desktop\WSUSclient.txt $output }
PowerShellCorpus/GithubGist/Tatejimaru_59a7786d7ce13fb16c2e_raw_3bd374d3152e3d228f05a13ded6c5a5646424e13_add_alias.ps1
Tatejimaru_59a7786d7ce13fb16c2e_raw_3bd374d3152e3d228f05a13ded6c5a5646424e13_add_alias.ps1
# 実行ポリシーの変更 Set-ExecutionPolicy RemoteSigned # $profileを作成 New-Item $profile -type file -force # $profileにnotepad++からnppへのエイリアスを追加 "Set-Alias npp C:\Program Files (x86)\Notepad++\notepad++.exe" > $profile
PowerShellCorpus/GithubGist/jptomo_8c15ce88f31396ade9a1_raw_3e169c4a1af3dd9312e4ffff0b7735252d473cdf_pwd.ps1
jptomo_8c15ce88f31396ade9a1_raw_3e169c4a1af3dd9312e4ffff0b7735252d473cdf_pwd.ps1
$_path = $(Get-Location).Path if ($_path.IndexOf($ENV:HOME) -eq 0) { $_path = Join-Path '~' ($PWD.ProviderPath.Remove(0, ($ENV:HOME).Length)) }
PowerShellCorpus/GithubGist/pkirch_2f8c1a19c13782a4bcc6_raw_655ca6ea3a56ed9973a4be3a1cd28b86ed7d77de_MVA06-LockedVHDs.ps1
pkirch_2f8c1a19c13782a4bcc6_raw_655ca6ea3a56ed9973a4be3a1cd28b86ed7d77de_MVA06-LockedVHDs.ps1
Set-AzureSubscription -SubscriptionName "MSFT MVA Live" -CurrentStorageAccountName pktest1 # sample 1 $blobs = Get-AzureStorageBlob -Container vhds $blobs | Format-Table -AutoSize $disks = Get-AzureDisk | Select-Object -ExpandProperty MediaLink | Select-Object -ExpandProperty AbsoluteUri $disks $blobs | Select-Object -ExpandProperty ICloudBlob | Select-Object -ExpandProperty Uri | Select-Object -ExpandProperty AbsoluteUri # Get all blobs for the given container that are used by disks. $lockedBlobs = $blobs | Where-Object {$disks -contains $_.ICloudBlob.Uri.AbsoluteUri} $lockedBlobs # sample 2 # Simply remove all disks and ignore errors. Get-AzureDisk | Remove-AzureDisk # Remove all disks which are not attached to any VM anymore. Get-AzureDisk | Where-Object AttachedTo -eq $null | Remove-AzureDisk
PowerShellCorpus/GithubGist/adoprog_5480127_raw_c07302e59ed3e2508a9c17d5538f4da8ec46cff7_gistfile1.ps1
adoprog_5480127_raw_c07302e59ed3e2508a9c17d5538f4da8ec46cff7_gistfile1.ps1
$checkoutFolder = "%teamcity.build.workingDir%" $targetDll = "$checkoutFolder\Website\TestProject\bin\Release\TestProject.dll" $fixture = "TestProject.MediaPlayerEditorTest" $resultXml = "$checkoutFolder\TestResult.xml" rm $resultXml -Force -Verbose -ErrorAction SilentlyContinue $buildOptions = "/xml:$resultXml /fixture:$fixture" $command = 'C:\Chocolatey\bin\nunit-console.bat "$targetDll" ' + $buildOptions Invoke-Expression $command
PowerShellCorpus/GithubGist/appakz_1674457_raw_07bde3c4ed940805cad0e873aa5acecd539d91f6_countLOC.ps1
appakz_1674457_raw_07bde3c4ed940805cad0e873aa5acecd539d91f6_countLOC.ps1
#Quick and dirty PS script for counting lines of code in a directory. Output is dumped to a simple CSV file. #Note that this script doesn't count blank lines. #Parameters: # path - the path containing the code files (note that the script will recurse through subfolders # outputFile - fully qualified path of the file to dump the CSV output # include (Optional) - file mask(s) to include in the count (deafults to *.*) # exclude (Optional) - file mask(s) to exclude in the count (defaults to none) # Example (count lines in target path including *.cs but excluding *.designer.cs) # .\countLOC.ps1 -path "C:\code\MyProject" -outputFile "C:\code\loc.csv" -include "*.cs" -exclude "*.designer.cs" param([string]$path, [string]$outputFile, [string]$include = "*.*", [string]$exclude = "") Clear-Host Get-ChildItem -re -in $include -ex $exclude $path | Foreach-Object { Write-Host "Counting $_.FullName" $fileStats = Get-Content $_.FullName | Measure-Object -line $linesInFile = $fileStats.Lines "$_,$linesInFile" } | Out-File $outputFile -encoding "UTF8" Write-Host "Complete"
PowerShellCorpus/GithubGist/mubix_fd0c89ec021f70023695_raw_60d28ae965ddba52995d0deaf83888ea39709bc2_Reset-KrbtgtKeyInteractive.ps1
mubix_fd0c89ec021f70023695_raw_60d28ae965ddba52995d0deaf83888ea39709bc2_Reset-KrbtgtKeyInteractive.ps1
<#---------------------------------------------------------------------------------------------------- Release Notes: v1.4: Author: Jared Poeppelman, Microsoft First version published on TechNet Script Gallery ----------------------------------------------------------------------------------------------------#> function Test-Command { Param([string]$Command) Try {Invoke-Expression $Command} Catch [System.Exception] {If ($Error.FullyQualifiedErrorId -eq 'CommandNotFoundException') {Return $false}} Return $true } function Test-RpcToHost { Param([string]$Hostname) Try {$RpcPingResult = rpcping.exe -s $Hostname} # Attempt to RPCPING the target host # Check for RPCPING.exe command and execution errors Catch [System.Exception] { If ($Error.FullyQualifiedErrorId -eq 'CommandNotFoundException') {Write-Host -ForegroundColor Red "The 'RPCPING.exe' utility is not available. Install it and/or add its location to the path and retry... exiting."; Exit} Write-Host -ForegroundColor Red "An unknown error occurred when attempting to execute 'RPCPING.exe'... exiting."; Exit } # Check output of RPCPING for success If ($RpcPingResult -like "*Completed*") {Return (New-Object -TypeName PSObject -Property @{'Success'=$true; 'Message'="$Hostname - RPC connectivity successful."})} # Check output of RPCPING for exceptions If ($RpcPingResult -like "*Exception 5*") {Return (New-Object -TypeName PSObject -Property @{'Success'=$false; 'Message'="$Hostname - Access is denied. Ensure your credentials have the required rights on the target host."})} If ($RpcPingResult -like "*Exception 1722*") {Return (New-Object -TypeName PSObject -Property @{'Success'=$false; 'Message'="$Hostname - RPC server unavailable. Check firewall rules and name resolution for the target host."})} If ($RpcPingResult -like "*Exception*") {Return (New-Object -TypeName PSObject -Property @{'Success'=$false; 'Message'="$Hostname - RPC to the target host failed for an unknown reason."})} } function Replicate-ADSingleObject { Param([string]$TargetDC, [string]$SourceDC, [string]$ObjectDN) Try {$RepAdminResult = repadmin.exe /replsingleobj $TargetDC $SourceDC $ObjectDN} # Attempt REPADMIN # Check for REPADMIN.exe command and execution errors Catch [System.Exception] { If ($Error.FullyQualifiedErrorId -eq 'CommandNotFoundException') {Write-Host -ForegroundColor Red "The 'REPADMIN.exe' utility is not available. Install it and/or add its location to the path and retry... exiting."; Exit} Write-Host -ForegroundColor Red "An unknown error occurred when attempting to execute 'REPADMIN.exe'... exiting."; Exit } # Check output of REPADMIN for success If ($RepAdminResult -like "*Successfully replicated object*") {Return (New-Object -TypeName PSObject -Property @{'Success'=$true; 'Message'="$ObjectDN - Successfully replicated from $SourceDC to $TargetDC."})} # Check output of REPADMIN for exceptions If ($RepAdminResult -like "*Exception 5*") {Return (New-Object -TypeName PSObject -Property @{'Success'=$false; 'Message'="$ObjectDN - $SourceDC access is denied. Ensure your credentials have the required rights on the target host."})} If ($RepAdminResult -like "*Exception 1722*") {Return (New-Object -TypeName PSObject -Property @{'Success'=$false; 'Message'="$ObjectDN - $SourceDC server unavailable. Check firewall rules and name resolution for the target host."})} If ($RepAdminResult -like "*Exception*") {Return (New-Object -TypeName PSObject -Property @{'Success'=$false; 'Message'="$ObjectDN - Failed to replicate from $SourceDC to $TargetDC for an unknown reason."})} } function Shuffle-Array { Param([Array] $a) $rnd=(New-Object System.Random) For($i=0;$i -lt $a.Length;$i+=1) { $newpos=$i + $rnd.Next($a.Length - $i); $tmp=$a[$i]; $a[$i]=$a[$newpos]; $a[$newpos]=$tmp } Return $a } function New-ComplexPassword { Param([string]$Username, [int]$PasswordLength) # Keep the password length within bounds If ($PasswordLength -lt 8) {$PasswordLength = 8} If ($PasswordLength -gt 28) {$PasswordLength = 28} # Define base characters for complex password and avoid ambiguous characters like I,i,1,L,l,O,o,0, etc. $UpperAlpha = @('A','B','C','D','E','F','G','H','J','K','M','N','P','Q','R','S','T','U','V','W','X','Y','Z') $LowerAlpha = @(); ForEach ($i in $UpperAlpha) {$LowerAlpha += $i.ToLower()} $Numerics = @('2','3','4','5','6','7','8','9') $SpecialChars = @('~','!','@','#','$','%','^','&','*','_','+','=','.','?') # Remove characters of the username to avoid possible conflicts $UpperAlpha = $UpperAlpha | Where-Object {($Username.ToCharArray()) -notcontains $_} $LowerAlpha = $LowerAlpha | Where-Object {($Username.ToCharArray()) -notcontains $_} [char[]]$ComplexPassword # Add random characters to our password until required length is reached For ($i=1; $i -le $PasswordLength; $i++) { If (($i % 4) -eq 0) {$ComplexPassword += $UpperAlpha | Get-Random} If (($i % 4) -eq 1) {$ComplexPassword += $LowerAlpha | Get-Random} If (($i % 4) -eq 2) {$ComplexPassword += $Numerics | Get-Random} If (($i % 4) -eq 3) {$ComplexPassword += $SpecialChars | Get-Random} } # Shuffle the password characters, so the type positions are not predictable and return it Return ((Shuffle-Array $ComplexPassword.ToCharArray()) -join "") } function Reset-KrbtgtKey { Param([string]$Server) Try {Set-ADAccountPassword -Identity (Get-ADUser krbtgt -Server $Server).DistinguishedName -Server $Server -Reset -NewPassword (ConvertTo-SecureString ((New-ComplexPassword krbtgt 22).ToString()) -AsPlainText -Force)} Catch { If (($Error.FullyQualifiedErrorId -eq 'ActiveDirectoryCmdlet:System.UnauthorizedAccessException,Microsoft.ActiveDirectory.Management.Commands.SetADAccountPassword') -and ($Error.CategoryInfo -like "*PermissionDenied*")) {Return (New-Object -TypeName PSObject -Property @{'Success'=$false; 'Message'='Krbtgt key reset failed due to insufficient permissions.'})} Else {Return (New-Object -TypeName PSObject -Property @{'Success'=$false; 'Message'='Krbtgt key reset failed for an unknown reason.'})} } Return (New-Object -TypeName PSObject -Property @{'Success'=$true; 'Message'='Krbtgt key reset successfully.'}) } <#---------------------------------------------------------------------------------------------------- Initialize ----------------------------------------------------------------------------------------------------#> #cls Set-Location (Split-Path $MyInvocation.MyCommand.Path) # Set the path of the script as the working directory $TimeStamp = Get-Date -Format o | foreach {$_ -replace ":", "."} # Timestamp for logfile $LogFile = "Reset-KrbtgtKey_$TimeStamp.log" # Logfile $Status = New-Object -TypeName PSObject # Custom object for status information <#---------------------------------------------------------------------------------------------------- Display menu options to user ----------------------------------------------------------------------------------------------------#> $ScriptDescription = @' This script can be used to perform a single reset of the krbtgt key that is shared by all writable domain controllers in the domain in which it is run. This script has 3 modes: '@ $Mode1Description = @' - Mode 1 is Informational Mode. This mode is safe to run at any time and makes no changes to the environment. It will analyze the environment and check for issues that may impact the successful execution of Mode 2 or Mode 3. '@ $Mode2Description = @' - Mode 2 is Estimation Mode. This mode will perform all the analysis and checks included in Mode 1. It will also initiate a single object replication of the krbtgt object from the PDC emulator DC to every writable domain controller that is reachable. This replication is not to replicate changes (no changes will be made). Instead, this replication is performed so that it can be measured and an estimate provided for the impact duration of Mode 3. '@ $Mode3Description = @' - Mode 3 is Reset Mode. This mode will perform all the analysis and checks included in Mode 1. It will also perform a single reset of the krbtgt key on the PDC emulator DC. If the krbtgt reset is successful, it will automatically initiate a single object replication of krbtgt from the PDC emulator DC to every writable domain controller that is reachable. Once the replication is complete, the total impact time will be displayed. During the impact duration of Mode 3 (estimated in Mode 2), the following impacts may be observed: '@ $Mode3Impact1 = @' - Kerberos PAC validation failures: Until the new krbtgt key is replicated to all writable DCs in the domain, applications which attempt KDC PAC validation may experience KDC PAC validation failures. This is possible when a client in one site is accessing a Kerberos-authenticated application that is in a different site. If that application is not a trusted part of the operating system, it may attempt to validate the PAC of the client''s Kerberos service ticket against the KDC (DC) in its site. If the DC in its site does not yet have the new krbtgt key, this KDC PAC validation will fail. This will likely manifest itself to the client as authentication errors for that application. Once all DCs have the new krbtgt key, some affected clients may recover gracefully and resume functioning normally. If not, rebooting the affected client(s) will resolve the issue. This issue may not occur if the replication of the new krbtgt key is timely and successful and no applications attempt KDC PAC validation against an out of sync DC during that time. '@ $Mode3Impact2 = @' - Kerberos TGS request failures: Until the new krbtgt key is replicated to all writable DCs in the domain, a client may experience Kerberos authentication failures. This is when a client in one site has obtained a Kerberos user ticket (TGT) from a DC that has the new krbtgt, but then subsequently attempts to obtain a service ticket via a TGS request against a DC in a different site. If that DC does not also have the new krbtgt key, it will not be able to decrypt the client''s TGT, which will result in a TGS request failure. This will manifest itself to the client as authenticate errors. However, it should be noted that this impact is very unlikely, because it is very unlikely that a client will attempt to obtain a service ticket from a different DC than the one from which their TGT was obtained, especially during the relatively short impact duration of Mode 3. '@ $ScriptRecommendation = @' It is highly recommended that Mode 1 be run first, then Mode 2, and then Mode 3. '@ $Menu = @' In which mode do you wish to run the script? 1 --- Informational Mode (no changes made; no replication triggered) 2 --- Estimation Mode (no changes made, but replication WILL BE triggered for estimation purposes) 3 --- Reset Mode (krbtgt WILL BE reset once, and replication WILL BE triggered) 0 --- Exit '@ $MenuPrompt = '(Enter 1-3, or 0 to exit)' Write-Host '' Write-Host $ScriptDescription Write-Host -ForegroundColor Green $Mode1Description Write-Host -ForegroundColor Yellow $Mode2Description Write-Host -ForegroundColor Red $Mode3Description Write-Host -ForegroundColor Cyan $Mode3Impact1 Write-Host -ForegroundColor Cyan $Mode3Impact2 Write-Host '' Write-Host $ScriptRecommendation Write-Host '' Write-Host $Menu Write-Host '' $Status | Add-Member -MemberType NoteProperty -Name 'ScriptMode' -Value (Read-Host $MenuPrompt) Write-Host '' If (($Status.ScriptMode -lt 1) -or ($Status.ScriptMode -gt 3)) {Write-Host 'Invalid selection...exiting'; Exit} # Validate input <#---------------------------------------------------------------------------------------------------- Perform pre-flight checks ----------------------------------------------------------------------------------------------------#> Write-Host 'Checking for script pre-requisites...' $Status | Add-Member -MemberType NoteProperty -Name 'PreFlightPassed' -Value $true Write-Host '' Write-Host ' Checking for ActiveDirectory Powershell module.....' -NoNewline If (Get-Module -List ActiveDirectory) {Write-Host -ForegroundColor Green 'PASSED'} Else {$Status.PreFlightPassed = $false; Write-Host -ForegroundColor Red 'FAILED'} Write-Host ' Checking if RPCPING.exe is installed and in the path.....' -NoNewline If (Test-Command rpcping.exe) {Write-Host -ForegroundColor Green 'PASSED'} Else {$Status.PreFlightPassed = $false; Write-Host -ForegroundColor Red 'FAILED'} Write-Host ' Checking if REPADMIN.exe is installed and in the path.....' -NoNewline If (Test-Command repadmin.exe) {Write-Host -ForegroundColor Green 'PASSED'} Else {$Status.PreFlightPassed = $false; Write-Host -ForegroundColor Red 'FAILED'} Write-Host '' If ($Status.PreFlightPassed -ne $true) {Write-Host -ForegroundColor Red "Pre-flight checks failed... exiting."; Exit} <#---------------------------------------------------------------------------------------------------- Gather and analyze domain information ----------------------------------------------------------------------------------------------------#> Write-Host 'Gathering and analyzing target domain information...' Import-Module ActiveDirectory $TargetDomain = Get-AdDomain | Select Name,DNSRoot,NetBIOSName,DomainMode,PDCEmulator Write-Host '' Write-Host ' Domain NetBIOS name: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.NetBIOSName Write-Host ' Domain DNS name: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.DNSRoot Write-Host ' PDC emulator: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.PDCEmulator Write-Host ' DomainMode: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.DomainMode Write-Host ' Checking domain functional mode is ''Windows2008Domain'' or higher.....' -NoNewline $Status | Add-Member -MemberType NoteProperty -Name 'DomainModePassed' -Value (!(($TargetDomain.DomainMode -eq 'Windows2000Domain') -or ($TargetDomain.DomainMode -eq 'Windows2003InterimDomain') -or ($TargetDomain.DomainMode -eq 'Windows2003Domain'))) If ($Status.DomainModePassed) {Write-Host -ForegroundColor Green 'PASSED'} Else {Write-Host -ForegroundColor Red 'FAILED'} Write-Host '' <#---------------------------------------------------------------------------------------------------- Gather and analyze krbtgt information and Kerberos policy ----------------------------------------------------------------------------------------------------#> Write-Host 'Gathering and analyzing krbtgt information and Kerberos policy...' Write-Host '' $Krbtgt = Get-ADUser krbtgt -Properties PasswordLastSet -Server $TargetDomain.PDCEmulator [xml]$gpo = Get-GPOReport -Guid '{31B2F340-016D-11D2-945F-00C04FB984F9}' -ReportType Xml $MaxTgtLifetimeHrs = (($gpo.gpo.Computer.ExtensionData | Where-Object {$_.name -eq 'Security'}).Extension.ChildNodes | Where-Object {$_.Name -eq 'MaxTicketAge'}).SettingNumber $MaxClockSkewMins = (($gpo.gpo.Computer.ExtensionData | Where-Object {$_.name -eq 'Security'}).Extension.ChildNodes | Where-Object {$_.Name -eq 'MaxClockSkew'}).SettingNumber $ExpirationTimeForNMinusOneTickets = (($Krbtgt.PasswordLastSet.AddHours($MaxTgtLifetimeHrs)).AddMinutes($MaxClockSkewMins)).AddMinutes($MaxClockSkewMins) # Doubling the clock skew to account for skew in both directions Write-Host ' Krbtgt account: ' -NoNewline; Write-Host -ForegroundColor Cyan $Krbtgt.DistinguishedName Write-Host ' Krbtgt account password last set on PDC emulator: ' -NoNewline; Write-Host -ForegroundColor Cyan $Krbtgt.PasswordLastSet Write-Host ' Kerberos maximum lifetime for user ticket (TGT lifetime): ' -NoNewline; Write-Host -ForegroundColor Cyan $MaxTgtLifetimeHrs 'hours' Write-Host ' Kerberos maximum tolerance for computer clock synchronization: ' -NoNewline; Write-Host -ForegroundColor Cyan $MaxClockSkewMins 'minutes' Write-Host ' Checking if all tickets based on the previous (N-1) krbtgt key have expired.....' -NoNewline $Status | Add-Member -MemberType NoteProperty -Name 'NMinusOneTicketExpirationPassed' -Value ($ExpirationTimeForNMinusOneTickets -lt [DateTime]::Now) If ($Status.NMinusOneTicketExpirationPassed) {Write-Host -ForegroundColor Green 'PASSED'} Else {Write-Host -ForegroundColor Red 'FAILED'} Write-Host '' <#---------------------------------------------------------------------------------------------------- Gather and analyze domain controller information ----------------------------------------------------------------------------------------------------#> Write-Host 'Gathering and analyzing writable domain controller information...' Write-Host '' $RwDcs = @() $RwDcs = Get-ADDomainController -Filter {IsReadOnly -eq $false} -Server $TargetDomain.PDCEmulator | Select Name,Hostname,Domain,Site Write-Host ' Checking RPC connectivity to domain controllers:' $Status | Add-Member -MemberType NoteProperty -Name 'RpcToDCsPassed' -Value $true ForEach ($DC in $RwDcs) { Write-Host ' Checking RPC connectivity to'$DC.Hostname'.....' -NoNewline $DC | Add-Member -MemberType NoteProperty -Name 'IsPdcEmulator' -Value ($DC.Hostname -eq $TargetDomain.PDCEmulator) $DC | Add-Member -MemberType NoteProperty -Name 'IsReachableViaRpc' -Value ((Test-RpcToHost $DC.Hostname).Success) If (!$DC.IsReachableViaRpc) {$Status.RpcToDCsPassed = $false; Write-Host -ForegroundColor Red 'FAILED'} Else {Write-Host -ForegroundColor Green 'PASSED'} } If ($Status.RpcToDCsPassed) {Write-Host -ForegroundColor Green ' Check for RPC connectivity to writable domain controllers PASSED: All writable DCs were reachable.'} Else {Write-Host -ForegroundColor Red ' Check for RPC connectivity to writable domain controllers FAILED. One or more writable DCs was unreachable.'} Write-Host '' <#---------------------------------------------------------------------------------------------------- MODES 2 AND 3 - Replicate krbtgt to all writable DCs that are reachable and generate an impact estimate ----------------------------------------------------------------------------------------------------#> If ($Status.ScriptMode -gt 1 -and $Status.PreFlightPassed -and $Status.DomainModePassed -and $Status.RpcToDCsPassed) { Write-Host 'Replicating krbtgt object to all writable domain controllers that are reachable...' If ($Status.ScriptMode -eq 2) { Write-Host -ForegroundColor Yellow ' The krbtgt object replication WILL BE triggered if you proceed. Are you sure you wish to proceed?' If (!((Read-Host ' (Enter ''Y'' to proceed or any other key to exit)').ToUpper() -eq 'Y')) {Write-Host -ForegroundColor Yellow ' Replication of krbtgt was skipped at the user''s request...exiting'; Exit} } $ImpactStartTime = (Get-Date).ToUniversalTime() ########## THIS IS WHERE KRBTGT PASSWORD RESET OCCURS IN MODE 3 ########## # Replicate krbtgt to appropriate DCs $Status | Add-Member -MemberType NoteProperty -Name 'ReplicationCheckSucceeded' -Value $true ForEach ($DC in $RwDcs) { Write-Host ' Replication of krbtgt from'$TargetDomain.PDCEmulator'to'$DC.Hostname'...' -NoNewline If ($DC.IsReachableViaRpc) { $ReplAttemptStart = (Get-Date).ToUniversalTime() If ((Replicate-ADSingleObject $DC.Hostname $TargetDomain.PDCEmulator $Krbtgt.DistinguishedName).Success) {Write-Host -ForegroundColor Green 'SUCCEEDED' -NoNewline} Else {$Status.ReplicationCheckSucceeded = $false; Write-Host -ForegroundColor Red 'FAILED' -NoNewline} $ReplElapsedTime = ((Get-Date).ToUniversalTime() - $ReplAttemptStart) Write-Host -ForegroundColor Cyan ' Time:'$ReplElapsedTime } Else {Write-Host -ForegroundColor Yellow 'SKIPPED'} } $TotalImpactTime = (Get-Date).ToUniversalTime() - $ImpactStartTime Write-Host '' $Status | Add-Member -MemberType NoteProperty -Name 'ImpactDurationEstimate' -Value $TotalImpactTime If ($Status.ReplicationCheckSucceeded) {Write-Host -ForegroundColor Cyan 'The total duration of impact when running Mode 3 will be approximately:' $TotalImpactTime} Else {Write-Host -ForegroundColor Red 'Single object replication failed to one or more writable domain controllers. All failures should be remediated before attempting Mode 3.'} } <#---------------------------------------------------------------------------------------------------- MODE 3 ONLY - Reset the krbtgt key and replicate to all writable DCs that are reachable ----------------------------------------------------------------------------------------------------#> If ($Status.ScriptMode -eq 3 -and $Status.PreFlightPassed -and $Status.DomainModePassed -and $Status.RpcToDCsPassed -and $Status.ReplicationCheckSucceeded) { Write-Host 'Resetting krbtgt key and replicating krbtgt object to all reachable domain controllers...' Write-Host '' Write-Host -ForegroundColor Red ' WARNING!!! The krbtgt key WILL BE reset AND krbtgt object replication WILL BE triggered if you proceed. Are you sure you wish to proceed?' Write-Host -ForegroundColor Red ' If you proceed, the impact duration of Mode 3 (described above) will begin and not end until all DCs obtained the new krbtgt key.' If (!((Read-Host ' (Enter ''Y'' to proceed or any other key to exit)').ToUpper() -eq 'Y')) {Write-Host -ForegroundColor Yellow ' The krbtgt reset and replication was skipped at the user''s request...exiting'; Exit} Write-Host '' If (!$Status.NMinusOneTicketExpirationPassed) { Write-Host -ForegroundColor Red ' The last change of the krbtgt key for this domain occurred: ' -NoNewline; Write-Host -ForegroundColor Cyan $Krbtgt.PasswordLastSet 'according to'$TargetDomain.PDCEmulator Write-Host -ForegroundColor Red ' and the domain Kerberos policy is configured with a maximum user ticket (TGT) lifetime of '-NoNewline; Write-Host -ForegroundColor Cyan $MaxTgtLifetimeHrs 'hours' Write-Host -ForegroundColor Red ' and a maximum tolerance for computer clock synchronization of ' -NoNewline; Write-Host -ForegroundColor Cyan $MaxClockSkewMins 'minutes' Write-Host -ForegroundColor Red ' That means that if you reset the krbtgt key again before ' -NoNewline; Write-Host -ForegroundColor Cyan $ExpirationTimeForNMinusOneTickets Write-Host -ForegroundColor Red ' A major impact is very likely. Are you sure you wish to proceed?' If (!((Read-Host ' (Enter ''Y'' to proceed or any other key to exit)').ToUpper() -eq 'Y')) {Write-Host -ForegroundColor Yellow ' The krbtgt reset and replication was skipped at the user''s request...exiting'; Exit} Write-Host '' } $ImpactStartTime = (Get-Date).ToUniversalTime() # Record start time # Reset krbtgt password Write-Host -ForegroundColor Cyan ' Resetting krbtgt key.....' -NoNewline $Status | Add-Member -MemberType NoteProperty -Name 'ResetSucceeded' -Value (Reset-KrbtgtKey $TargetDomain.PDCEmulator).Success If ($Status.ResetSucceeded) {Write-Host -ForegroundColor Green 'SUCCEEDED'} Else {Write-Host -ForegroundColor Red 'FAILED'; Write-Host -ForegroundColor Red ' Krbtgt reset failed. Check to ensure you have sufficient rights to reset the krbtgt account. Replication will be skipped'} Write-Host '' # Replicate krbtgt to appropriate DCs If ($Status.ResetSucceeded) { $Status | Add-Member -MemberType NoteProperty -Name 'PostResetReplicationSucceeded' -Value $true ForEach ($DC in $RwDcs) { Write-Host ' Replication of krbtgt from'$TargetDomain.PDCEmulator'to'$DC.Hostname'...' -NoNewline If ($DC.IsReachableViaRpc) { $ReplAttemptStart = (Get-Date).ToUniversalTime() If ((Replicate-ADSingleObject $DC.Hostname $TargetDomain.PDCEmulator $Krbtgt.DistinguishedName).Success) {Write-Host -ForegroundColor Green 'SUCCEEDED' -NoNewline} Else {$Status.PostResetReplicationSucceeded = $false; Write-Host -ForegroundColor Red 'FAILED' -NoNewline} $ReplElapsedTime = ((Get-Date).ToUniversalTime() - $ReplAttemptStart) Write-Host -ForegroundColor Cyan ' Time:'$ReplElapsedTime } Else {Write-Host -ForegroundColor Yellow 'SKIPPED'} } $TotalImpactTime = (Get-Date).ToUniversalTime() - $ImpactStartTime $Status | Add-Member -MemberType NoteProperty -Name 'ImpactDuration' -Value $TotalImpactTime If ($Status.PostResetReplicationSucceeded) {Write-Host -ForegroundColor Cyan 'The total duration of impact when running mode 3 was:' $TotalImpactTime} Else {Write-Host -ForegroundColor Red 'Single object replication failed to one or more writable domain controllers.'} Write-Host '' # Validate krbtgt password last set is in sync with PDC emulator Write-Host ' Validating krbtgt password last set is in sync with PDC emulator...' $Status | Add-Member -MemberType NoteProperty -Name 'NewKrbtgtKeyReplValidationPassed' -Value $true $KrbtgtKeyLastSetOnPdc = (Get-ADUser krbtgt -Properties PasswordLastSet -Server $TargetDomain.PDCEmulator).PasswordLastSet Write-Host ' PDC emulator: Krbtgt account password last set on'$TargetDomain.PDCEmulator'.....' -NoNewline; Write-Host -ForegroundColor Cyan $KrbtgtKeyLastSetOnPdc ForEach ($DC in $RwDcs) { If (!$DC.IsPdcEmulator) { Write-Host ' Checking krbtgt account password last set on '$DC.Hostname'.....' -NoNewline If (!$DC.IsReachableViaRpc) {Write-Host -ForegroundColor Yellow "SKIPPED"} Else { $CouldConnect = $true Try {$KrbtgtKeyLastSetOnThisDc = (Get-ADUser krbtgt -Properties PasswordLastSet -Server $DC.Hostname).PasswordLastSet} Catch {If ($Error.FullyQualifiedErrorId -eq 'ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADUser') {$CouldConnect = $false}} If ($CouldConnect) { If ($KrbtgtKeyLastSetOnThisDc -ne $KrbtgtKeyLastSetOnPdc) {Write-Host -ForegroundColor Red "FAILED" -NoNewline; $Status.NewKrbtgtKeyReplValidationPassed = $false} Else {Write-Host -ForegroundColor Green "PASSED" -NoNewline} Write-Host -ForegroundColor Cyan ' Last set:' $KrbtgtKeyLastSetOnThisDc } Else {Write-Host -ForegroundColor Yellow "SKIPPED (could not connect to server)"} } } } } Write-Host '' If (!$Status.NewKrbtgtKeyReplValidationPassed) {Write-Host -ForegroundColor Red ' Check if krbtgt key on all writable domain controllers was in sync with PDC emulator FAILED. One or more reachable DCs was out of sync with the PDC emulator.'} Else {Write-Host -ForegroundColor Green ' Check if krbtgt key on all writable domain controllers was in sync with PDC emulator PASSED. All reachable DCs were in sync with the PDC emulator..'} Write-Host '' } If ((!$Status.PreFlightPassed -or !$Status.DomainModePassed -or !$Status.RpcToDCsPassed) -or ($Status.ScriptMode -gt 1 -and !$Status.ReplicationCheckSucceeded)) {Write-Host -ForegroundColor Red 'One or more items failed. Resolve failures and retry.'} # Log status data $Status | Out-File -FilePath $LogFile -Append Write-Host "Logged to file: $LogFile"
PowerShellCorpus/GithubGist/jrampon_2a82f114d88b29110794_raw_a560c2ce9443056459f9a5ea96d3236ddc7be29f_boxstarter.ps1
jrampon_2a82f114d88b29110794_raw_a560c2ce9443056459f9a5ea96d3236ddc7be29f_boxstarter.ps1
# From a command prompt: # START http://boxstarter.org/package/nr/url?<raw-url> # Boxstarter options $Boxstarter.RebootOk=$true # Allow reboots? $Boxstarter.NoPassword=$false # Is this a machine with no login password? $Boxstarter.AutoLogin=$true # Save my password securely and auto-login after a reboot # Basic setup Update-ExecutionPolicy Unrestricted Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -DisableShowProtectedOSFiles -EnableShowFileExtensions -EnableShowFullPathInTitleBar Enable-MicrosoftUpdate Enable-RemoteDesktop Disable-InternetExplorerESC Disable-UAC if (Test-PendingReboot) { Invoke-Reboot } # Update Windows and reboot if necessary Install-WindowsUpdate -AcceptEula if (Test-PendingReboot) { Invoke-Reboot } # Tools - version matters cinstm cygwin -version 1.7.33.20150102 cinstm bison flex binutils diffutils inetutils openssh -source cygwin cinstm git -version 1.9.5 # Tools - latest always fine cinstm notepadplusplus cinstm beyondcompare cinstm procexp cinstm sysinternals cinstm googlechrome cinstm 7zip cinstm adobereader cinstm jre8 -params "both=true" cinstm jdk8 -params "both=true" cinstm clover
PowerShellCorpus/GithubGist/sunnyc7_8617483_raw_7f3c5bdaeece1c8ea54173af13f256414dd3a2cb_Sort-WSDL.ps1
sunnyc7_8617483_raw_7f3c5bdaeece1c8ea54173af13f256414dd3a2cb_Sort-WSDL.ps1
#requires -version 3.0 [CmdletBinding()] param ( [Parameter(Mandatory)] [string] $Path ) function Sort-NodeArray { param ( [System.Xml.XmlNode[]] $SortedNodes ) foreach ($Node in $SortedNodes) { $Node.ParentNode.AppendChild($Node.ParentNode.RemoveChild($Node)) | Out-Null } } $Path = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) $TempPath = [IO.Path]::GetTempFileName() Add-Type -AssemblyName System.Web.Services $ServiceDescription = [System.Web.Services.Description.ServiceDescription]::Read($Path) $ServiceDescription.Namespaces = $null $ServiceDescription.Write($TempPath) $Namespaces = @{ wsdl = 'http://schemas.xmlsoap.org/wsdl/' xs = 'http://www.w3.org/2001/XMLSchema' } $TypesNode = Select-Xml -Path $TempPath -XPath wsdl:definitions/wsdl:types -Namespace $Namespaces | Select-Object -ExpandProperty Node -First 1 $Schemas = @( Select-Xml -Xml $TypesNode -XPath xs:schema -Namespace $Namespaces | Select-Object -ExpandProperty Node | Sort-Object -Property { $_.GetAttribute('targetNamespace') } ) Sort-NodeArray -SortedNodes $Schemas foreach ($Schema in $Schemas) { $ImportNodes = @( Select-Xml -Xml $Schema -XPath xs:import -Namespace $Namespaces | Select-Object -ExpandProperty Node | Sort-Object -Property { $_.GetAttribute('namespace') } ) Sort-NodeArray -SortedNodes $ImportNodes $SimpleTypeNodes = @( Select-Xml -Xml $Schema -XPath xs:simpleType -Namespace $Namespaces | Select-Object -ExpandProperty Node | Sort-Object -Property { $_.GetAttribute('name') } ) Sort-NodeArray -SortedNodes $SimpleTypeNodes $ComplexTypeNodes = @( Select-Xml -Xml $Schema -XPath xs:complexType -Namespace $Namespaces | Select-Object -ExpandProperty Node | Sort-Object -Property { $_.GetAttribute('name') } ) Sort-NodeArray -SortedNodes $ComplexTypeNodes } $OutputPath = $Path $TypesNode.OwnerDocument.Save($TempPath) $ServiceDescription = [System.Web.Services.Description.ServiceDescription]::Read($TempPath) $ServiceDescription.Namespaces = $null $ServiceDescription.Namespaces.Add('tns', $ServiceDescription.TargetNamespace) $ServiceDescription.Namespaces.Add('wsdl', 'http://schemas.xmlsoap.org/wsdl/') $ServiceDescription.Namespaces.Add('soap', 'http://schemas.xmlsoap.org/wsdl/soap/') foreach ($Schema in $ServiceDescription.Types.Schemas) { $Schema.Namespaces = $null $Schema.Namespaces.Add('tns', $Schema.TargetNamespace) $Schema.Namespaces.Add('xs', 'http://www.w3.org/2001/XMLSchema') $NamespaceIndex = 1 foreach ($Include in $Schema.Includes) { $Schema.Namespaces.Add("ns$NamespaceIndex", $Include.Namespace) $NamespaceIndex++ } } $ServiceDescription.Write($OutputPath) Remove-Item -Path $TempPath
PowerShellCorpus/GithubGist/pkskelly_097bb3e6aa3cafe4cb08_raw_4f811f84c6269bb64ec4fd515892f44042c9c975_Add-SPListItemsFromCSV.ps1
pkskelly_097bb3e6aa3cafe4cb08_raw_4f811f84c6269bb64ec4fd515892f44042c9c975_Add-SPListItemsFromCSV.ps1
# =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= # Script: Add-SPListItemsFromCSV.ps1 # # Author: Pete Skelly # Twitter: ThreeWillLabs # http://www.threewill.com # # Description: Add list items to SharePoint Online - Office 365 List using CSOM from CSV file. # # WARNING: Script provided AS IS with no warranty. Your mileage will vary. Use # this script on a production list AT YOUR OWN RISK. # # =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= param( [string] $siteUrl, [string] $userId, [string] $listName, [string] $csvName ) # --------------------------------------------------------- # Load SharePoint 2013 CSOM libraries. Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll" Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition $password = Read-Host -Prompt "Enter password" -AsSecureString $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $password) $ctx.Credentials = $credentials $list = $ctx.get_web().get_lists().getByTitle($listName); ## Step 1. collect column names from the header row of the file $csvFilePath = Join-Path -Path $scriptPath -ChildPath $csvName if (Test-Path "$csvFilePath") { # Step 2. collect the rows for the list Write-Host "Importing CSV data from $csvFilePath " $listItems = import-csv -Path "$csvFilePath" $recordCount = @($listItems).count; Write-Host -ForegroundColor Yellow "There are $recordCount list items to process" Write-Host "Please wait..." # Step 3. Add the list items for($rowCounter = 1; $rowCounter -le $recordCount - 1; $rowCounter++) { $curItem = @($listItems)[$rowCounter]; Write-Progress -id 1 -activity "Adding List Item" -status "Inserting item $rowCounter of $recordCount list items." -percentComplete ($rowCounter*(100/$recordCount)); # # Create list item. $itemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation $newItem = $list.addItem($itemCreateInfo); $newItem.set_item('Title', $curItem.Summary); $newItem.set_item('FieldName1', $curItem.ColumnName1); $newItem.set_item('FieldName2', $curItem.ColumnName2); # More fields / columns as needed... may improve if I revisit... #simple hack for Lookup lists... #$newItem.set_item('LookupFieldName', $curItem.LookupValues); #Id1;#Value1;#Id2;#Value2;#Id3;#Value3... may improve if I revisit... $newItem.update(); $ctx.Load($newItem) $ctx.ExecuteQuery() } } else { Write-Host "Could not load file path $csvFilePath " }
PowerShellCorpus/GithubGist/vermorel_1391893_raw_9b0a38cce91aa8fbafe5adcd0e5f8db048fe075a_measure-loc.ps1
vermorel_1391893_raw_9b0a38cce91aa8fbafe5adcd0e5f8db048fe075a_measure-loc.ps1
# Measure-Loc # By Joannes Vermorel, 2010 # Recurse directories and compute the number of C# lines # Usage: measure-loc function Measure-Loc { param( ) begin { } process { ls -recurse -filter *.cs | gc | ? { $_.Trim().Length -gt 1 } | measure-object -line } end { } }
PowerShellCorpus/GithubGist/nizah01_54c18f0dc161c629f44d_raw_635732506909f11cdc81902e25e3ec9c7ba218d6_gistfile1.ps1
nizah01_54c18f0dc161c629f44d_raw_635732506909f11cdc81902e25e3ec9c7ba218d6_gistfile1.ps1
$apikey = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" $baseurl = "http://localhost/redmine" # issue ID $child = 1 $parent = 100 $header = @{"Content-Type"="application/xml"} $url = $baseurl + "/issues/${child}.xml?key=" + $apikey $xml = [xml] "<?xml version=`"1.0`" encoding=`"UTF-8`"?><issue><parent_issue_id>${parent}</parent_issue_id></issue>" $result = Invoke-RestMethod $url -Method Put -Body $xml -headers $header
PowerShellCorpus/GithubGist/mrdrbob_4125657_raw_6c9ea369d751afbbb0c66f477e4155651fc292e3_Precompile-Site.ps1
mrdrbob_4125657_raw_6c9ea369d751afbbb0c66f477e4155651fc292e3_Precompile-Site.ps1
function global:Precompile-Site([string]$csproj, [string]$outputdir = '', [string]$configuration = 'Release') { if (!($csproj)) { echo 'You must at least include the path to the .csproj file.' return; } $ErrorActionPreference = 'Stop' function Exec([scriptblock]$cmd, [string]$errorMessage = "Error executing command: " + $cmd) { & $cmd if ($LastExitCode -ne 0) { throw $errorMessage } } if (!($env:path.Contains('Microsoft.NET'))) { $env:path = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319;$env:path" } $code_dir = [System.IO.Path]::GetDirectoryName($csproj) $build_artifacts_dir = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), [System.Guid]::NewGuid().ToString().Substring(0, 8)) $publish_dir = [System.IO.Path]::Combine($build_artifacts_dir, "publish") $precompile_dir = [System.IO.Path]::Combine($build_artifacts_dir, "precompile") try { New-Item -Type Directory -Path $build_artifacts_dir | out-null New-Item -Type Directory -Path $publish_dir | out-null # Publish the site Exec { msbuild "$csproj" /t:PipelinePreDeployCopyAllFilesToOneFolder /v:q /p:Configuration=$configuration /p:_PackageTempDir=$publish_dir /p:AutoParameterizationWebConfigConnectionStrings=false } # Copy any non-referenced .DLL files that msbuild did not publish. $old_bin_files = @(Get-ChildItem -Name "$code_dir\bin\*.dll") foreach($file in $old_bin_files) { $final_bin_path = [System.IO.Path]::Combine("$publish_dir\bin", $file) if (!(Test-Path $final_bin_path)) { $source = [System.IO.Path]::Combine("$code_dir\bin", $file) Copy-Item $source $final_bin_path } } # Compile the site Exec { aspnet_compiler -v / -p $publish_dir $precompile_dir } # Deploy if ($outputdir) { Copy-Item "$precompile_dir\*" $outputdir -Recurse -Force } } finally { Remove-Item -Recurse -Force $build_artifacts_dir } }
PowerShellCorpus/GithubGist/jm-welch_6022056_raw_8c88d7e31e21fe2a82ab21a5857a82f72be4eba0_Syntax%20Test%20Script.ps1
jm-welch_6022056_raw_8c88d7e31e21fe2a82ab21a5857a82f72be4eba0_Syntax%20Test%20Script.ps1
# Syntax test script for PowerGUI # ------------------------------- # To modify syntax highlighting, use the Script Colors addin # from http://www.powergui.org/entry.jspa?externalID=3023 # Or edit PowerShellSyntax.xml in your PowerGUI install path cls <# Formatted types in example below $myarray : variable function, if : reserved word MyFunc : function 6,2 : numbers (int) 0x3 : number (hex) =,-,* : operators -eq : operator word $false, $args : autovars Write-Host : cmdlet -NoNewline : cmdlet parameter Green : string (unquoted) #> $myarray = ('day', "ignore") function MyFunc { if (6-2*0x3 -eq $false){ Write-Host "Oh, happy " -NoNewline Write-Host $args[0] -ForegroundColor Green } } MyFunc $myarray[0] #region Formatting type definitions from PowerShellSyntax.xml # region/endregion tags are formatted as Reserved Words, and allow code folding function StringTypes{ # Placing these in a function so they aren't executed 'Single-quoted string' "Double-quoted sring" @' Single-quoted here-string '@ @" Double-quoted here-string "@ } <# Auto-Vars $$ $? $^ $_ $Args $DebugPreference $Error $ErrorActionPreference $foreach $Home $Input $LASTEXITCODE $MaximumAliasCount $MaximumDriveCount $MaximumFunctionCount $MaximumHistoryCount $MaximumVariableCount $PsHome $Host $OFS $ReportErrorShowExceptionClass $ReportErrorShowInnerException $ReportErrorShowSource $ReportErrorShowStackTrace $ShouldProcessPreference $ShouldProcessReturnPreference $StackTrace $VerbosePreference $WarningPreference $PWD $true $false #> <# Reserved Words break continue do for foreach while if switch until function filter else elseif in return param throw trap default begin process end try catch finally workflow parallel sequence inlinescript checkpoint-workflow suspend-workflow #> <# Operators/OperatorWords -eq -ne -gt -ge -lt -le -ieq -ine -igt -ige -ilt -ile -ceq -cne -cgt -cge -clt -cle -like -notlike -match -notmatch -ilike -inotlike -imatch -inotmatch -clike -cnotlike -cmatch -cnotmatch -contains -notcontains -icontains -inotcontains -ccontains -cnotcontains -isnot -is -as -replace -ireplace -creplace -split -join -and -or -band -bor -not -bnot -f -xor -bxor += -= *= /= %= -- ++ + - * / % = ! -regex -wildcard -exact -casesensitive -file #> #endregion
PowerShellCorpus/GithubGist/atifaziz_5365389_raw_ab2d51b1f807d33ae50f4e3b9c75b9323a133a1a_DataAccess.ps1
atifaziz_5365389_raw_ab2d51b1f807d33ae50f4e3b9c75b9323a133a1a_DataAccess.ps1
function Get-DatabaseProvider { [CmdletBinding()] param ($Provider) if ($provider -eq $null) { [Data.OleDb.OleDbFactory]::Instance } elseif (!($provider -is [Data.Common.DbProviderFactory])) { if (!($provider -is [string])) { throw "Provider must be a string or an object of $([Data.Common.DbProviderFactory]) type." } [Data.Common.DbProviderFactories]::GetFactory($provider) } else { $provider } } function Get-DatabaseQuery { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$ConnectionString, [Parameter(Mandatory = $true)] [string]$Query, [hashtable]$Parameters, $Provider ) $provider = Get-DatabaseProvider -ea Stop $provider #$errorActionPreference = [Management.Automation.ActionPreference]'Stop' $connection = $provider.CreateConnection() $connection.ConnectionString = $connectionString $command = $connection.CreateCommand() $command.CommandText = $query if ($parameters -ne $null) { $parameters.GetEnumerator() | % { $parameter = $command.CreateParameter(); $parameter.ParameterName = "$($_.Name)" $parameter.Value = $_.Value $command.Parameters.Add($parameter) | Out-Null } } $command } function Get-DatabaseData { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$ConnectionString, [Parameter(Mandatory = $true)] [string]$Query, [hashtable]$Parameters, $Provider, [scriptblock]$OnConnecting ) $provider = Get-DatabaseProvider -ea Stop $provider $command = Get-DatabaseQuery -ea Stop $connectionString $query $parameters $provider $connection = $command.Connection if ($onConnecting) { & $onConnecting $connection } $connection.Open() try { $reader = $command.ExecuteReader() if ($reader.FieldCount -gt 0) { $ordinals = 0..($reader.FieldCount - 1) [string[]]$names = $ordinals | % { $name = $reader.GetName($_) if ($name.Length -eq 0) { "Column$($_ + 1)" } else { $name } } $e = New-Object Data.Common.DbEnumerator($reader) while ($e.MoveNext()) { $obj = New-Object psobject $ordinals | % { Add-Member NoteProperty ` -InputObject $obj ` -Name ($names)[$_] ` -Value $e.Current.GetValue($_) } $obj } if ($reader.NextResult()) { Write-Warning 'Query had additional result sets but this does not return them.' } } } finally { if ($reader -ne $null) { $reader.Close() } $connection.Close() } } function Invoke-DatabaseQuery { [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Low')] param ( [Parameter(Mandatory = $true)] [string]$ConnectionString, [Parameter(Mandatory = $true)] [string]$Query, [hashtable]$Parameters, $Provider ) $provider = Get-DatabaseProvider -ea Stop $provider #$errorActionPreference = [Management.Automation.ActionPreference]'Stop' $command = Get-DatabaseQuery -ea Stop $connectionString $query $parameters $provider if ($pscmdlet.ShouldProcess($query)) { $connection = $command.Connection $connection.Open() try { $command.ExecuteNonQuery() } finally { $connection.Close() } } } function Get-SqlData { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$ConnectionString, [Parameter(Mandatory = $true)] [string]$Query, [hashtable]$Parameters, [switch]$SqlVerbose ) Get-DatabaseData -ea Stop ` $connectionString $query $parameters ` ([Data.SqlClient.SqlClientFactory]::Instance) ` -OnConnecting $(if ($sqlVerbose) { { param($conn) $conn.add_InfoMessage({ param($sender, $e) Write-Verbose $e.Message }) }} else { $null }) } function Invoke-SqlQuery { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$ConnectionString, [Parameter(Mandatory = $true)] [string]$Query, [hashtable]$Parameters ) Invoke-DatabaseQuery -ea Stop ` $connectionString $query $parameters ` ([Data.SqlClient.SqlClientFactory]::Instance) }
PowerShellCorpus/GithubGist/mrdaemon_1132676_raw_315272a7c73c0dbf0e241ced1d4379d6d42c3b87_import-hvconfigonlyvm.ps1
mrdaemon_1132676_raw_315272a7c73c0dbf0e241ced1d4379d6d42c3b87_import-hvconfigonlyvm.ps1
<# .SYNOPSIS Safely Imports Hyper-V Virtual Machines that were exported as configuration only, without State Data (snapshots, VHDs, etc). .DESCRIPTION Hyper-V 2008 R2 removed the option to export a Virtual Machine without its State Data (Snapshots, Virtual Disk Images (VHDs), Suspend State), as configuration only through the GUI. The functionality is still there, only it is not exposed through the Hyper-V Manager snap-in in R2. Many scripts and resources exist to perform such an export, namely the PowerShell management Library for Hyper-V (see links). However, there are very few, if any usable tools that leverage the new ImportVirtualSystemEx() API to perform an import of such a configuration-only export. This cmdlet attempts to remedy this. It will copy the specified VM Export to a sensible location based on the current global setting for VM Data location in Hyper-V, and then assuming the VHD files are in the right place and the Virtual Networks still have the same friendly names, reattach everything together and import the virtual machine back into Hyper-V. This was written because there is no direct upgrade path between Hyper-V Server 2008 and Hyper-V Server 2008 R2. .PARAMETER ExportDirectory Specifies either a Directory or a list of directories where the Configuration Only exports can be found. Each directory must contain the 'config.xml' file in the root along with the "Virtual Machines" directory containing the actual configuration. .INPUTS You can pipe a collection of directories into Import-HVConfigOnlyVM. They will all be processed. .OUTPUTS System.Object - may be formatted as a table, contains a report of the operations in its property members. .NOTES The script must be ran locally on the Hyper-V server. It also will only work on Hyper-V R2 and Powershell 2.0. .EXAMPLE Import a config only export of a virtual machine stored at E:\Export\VMSVR03 C:\PS> Import-HVConfigOnlyVM -ExportDirectory E:\Export\VMSVR03 .EXAMPLE Import all the exports stored in E:\Export C:\PS> gci E:\Export | where { $_.PSIsContainer -eq $true } | Import-HVConfigOnlyVM .LINK https://github.com/mrdaemon/hyper-v_utils Script page and code repository on GitHub .LINK http://www.raptorized.com Author's Blog .LINK http://pshyperv.codeplex.com/ PowerShell management Library for Hyper-V (only vaguely related) #> function Import-HVConfigOnlyVM { [OutputType([System.Object])] [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact="Medium" )] Param ( [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Enter path to exported VM directory (containing config.xml)")] [ValidateScript({ (Test-Path (Join-Path $_ "config.xml") -PathType Leaf) -and (Test-Path (Join-Path $_ "Virtual Machines") -PathType Container) })] [alias("FullName", "Path")] [string[]]$ExportDirectory ) BEGIN { # Local settings and local-scope WMI class instances ##################################################### # Sane default for Errors behavior. # You shouldn't override it anyways. $ErrorActionPreference = "Stop" # Hyper-V WMI Namespace $hyperv_namespace = "root/virtualization" # VirtualSystemManagementService and # VirtualSystemManagementSettingData WMI instances $vsms = Get-WmiObject -Namespace $hyperv_namespace -Class "MsVM_virtualSystemManagementService" $hyperv_config = Get-WmiObject -NameSpace $hyperv_namespace -Class "MsVM_VirtualSystemManagementServiceSettingData" # List of currently configured Virtual Networks from the # Hyper-V server configuration, for validation purposes. [String[]]$vswitches = Get-WmiObject -NameSpace $hyperv_namespace -Class "MsVM_VirtualSwitch" | foreach( $_.ElementName.toString()) # Array to hold the result set populated with our custom report objects [System.Object[]]$statusdataset = @() } PROCESS { write-host "Importing config-only Virtual machine in", $ExportDirectory # Reporting Object, contains all the status data. # It is pushed into a global array and returned when the script # is done executing. $importstatus = New-Object System.Object # Construct new destination root from the default Hyper-V VM storage # path, the system default name of "Virtual Machines" as a subdirectory, # and the the top level directory (which should be the name of the VM). # TODO: make this a parameter. $newroot = Join-Path (Join-Path $hyperv_config.DefaultExternalDataRoot "Virtual Machines") (get-item $ExportDirectory).Name # There's no way we can continue if the data set already exists. if (Test-Path $newroot -PathType Container) { $err = "The destination path $newroot already exists!`n", "Aborting..." throw $err } # Copy the export files to their final location in $newroot, # they will be imported in-place, since we do not enable CreateCopy. # Copy-Item creates target Directories if they don't already exist. Write-Host "Copying configuration to $newroot..." if($PSCmdlet.ShouldProcess) { Copy-Item $ExportDirectory -Destination $newroot -Container -Recurse } # Fetch current import settings data from files in new data root $importconfig = $vsms.GetVirtualSystemImportSettingData("$newroot").ImportSettingData Write-Host "Processing configuration for", $importconfig.Name # Populate our status object with what we have gathered so far: $importstatus | Add-Member # Alter importation settings to reuse current and default values. # This is how to specify where the data actually lives. # http://msdn.microsoft.com/en-us/library/dd379577(v=VS.85).aspx $importconfig.CreateCopy = $false $importconfig.GenerateNewId = $false $importconfig.SourceSnapshotDataRoot = $hyperv_config.DefaultVirtualHardDiskPath $importconfig.SourceResourcePaths = $importconfig.CurrentResourcePaths $importconfig.TargetNetworkConnections = $importconfig.SourceNetworkConnections # Validate (at least roughly) import settings foreach ($path in $importconfig.SourceResourcePaths) { if(Test-Path -Path $path -PathType Leaf) { Write-Host "Found Resource $path ." } else { Write-Warning ("Warning, missing ressource: $path!`n", "You will be able to continue but you will have to reattach", "the missing volumes to the virtual machines after the import." -join " ") } } # Perform Importation of system. $result = $vsms.ImportVirtualSystemEx("$newroot", $importconfig.PSBase.GetText(1)) # Apparently, calling ImportVirtualSystemEx forks a process/thread asynchronously, # returning a CIM_ConcreteJob class instance with the job details. # This is translated in Powershell as a Job, but the translation is not flawless. if ($result.ReturnValue -eq 4096) { # Getting WMI Job object reference. $job = [WMI]$result.Job # Process our job status in a loop while it is in one of the following states: # 2 - Never Started # 3 - Starting # 4 - Running # http://msdn.microsoft.com/en-us/library/cc136808(v=VS.85).aspx#properties while ($job.JobState -eq 2 -or $job.JobState -eq 3 -or $job.JobState -eq 4) { # Display and update the lovely progress bar. Write-Progress $job.Caption -Status "Importing VM" -PercentComplete $job.PercentComplete start-sleep 1 # Update the ref, it doesn't do that by itself. $job = [WMI]$result.Job } # Complete Progress bar and move on. Write-Progress "Importing Virtual Machine" -Status "Done." -PercentComplete 100 # JobState 7 means Successfully Completed. # There are a billion other things that could be returned here, # and frankly, I don't care. Enjoy your generic error code. if($job.JobState -eq 7) { Write-Output "System in $ExportDirectory successfully imported in $newroot." } else { Write-Error "System failed to import. Error value:", $job.Errorcode, $job.ErrorDescription } } else { # Return code was not 4096, which is "Job Started". # This means no job was forked. There can be only two outcomes # to this entire ordeal. Let's Address them in the laziest way possible. $msg = "ImportVirtualSystemEx() returned prematurely with status" if($result.ReturnValue -eq 0) { Write-Warning $msg, "0 (Success)" } else { Write-Error $msg, $result.ReturnValue } } } }
PowerShellCorpus/GithubGist/ramondeklein_ef6c955b12ee09297cf8_raw_13a96fe693c73f0b0d8ed1ecb19039eefbb581a7_Redirector.ps1
ramondeklein_ef6c955b12ee09297cf8_raw_13a96fe693c73f0b0d8ed1ecb19039eefbb581a7_Redirector.ps1
# This Powershell script can be used on a server to redirect HTTP/HTTPS # traffic to different sources. Make sure your DNS routes the requests # for the source URLs to this server. It automatically forwards the URL # to the destination server without altering the rest of the URL. # # You can use multiple mappings. Of course the 'source' should be # unique, but the destination can occur multiple times. # # Make sure PowerShell is allowed to run this script. You might need to # change PowerShell's policy by running the following command as admin: # # PS C:> Set-ExecutionPolicy RemoteSigned # # I would advise not to run this script as Administrator, but as a uwer # with restricted permission (in production use). You might need to authorize # the user to handle specific HTTP(S) URLs. Refer to http://bit.ly/1Crn0xz # for more information how to do this. # # Script written by Nov 2014 by Ramon de Klein ([email protected]). # Use and alter as you please. $map = @{ # Source -> Destination "http://localhost:8888/" = "http://www.microsoft.com/" #"http://www.example.com/" = "https://example.com/" #"https://www.example.com/" = "https://example.com/" #"http://example.com/" = "https://example.com/" #"http://blog.example.com/" = "https://example.com/blog/" #"https://blog.example.com/" = "https://example.com/blog/" } # Setup the HTTP listener and start it $listener = New-Object System.Net.HttpListener $map.Keys | % { # Listen on each source URL Write-Host "- Redirect $_ to" $map.Item($_) $listener.Prefixes.Add($_) } $listener.Start() while ($listener.IsListening) { # Obtain HTTP context $context = $listener.GetContext() # Determine the request URL $url = $context.Request.Url.ToString() # Process the URL mappings $map.Keys | % { $url = $url.Replace($_, $map.Item($_)) } # Create a HTTP 301 (permanent redirect) response $response = $context.Response $response.StatusCode = 301 $response.AddHeader("Location", $url) $response.Close() # Log the redirect Write-Host "> Redirecting to $url" }
PowerShellCorpus/GithubGist/callemall_6123581_raw_f8b6d060bbb021a9b8bc54875d9548536b5f8bbf_PowerShell%20-%20ExtCreateBroadcast.ps1
callemall_6123581_raw_f8b6d060bbb021a9b8bc54875d9548536b5f8bbf_PowerShell%20-%20ExtCreateBroadcast.ps1
# =========================================================================================================================== # # Send a voice-only broadcast (an announcement) with the name 'Test of Emergency' to the Emergency contacts group outside of the # calling window. The broadcast should launch immdediately with the text-to-speech message of 'Please call the emergency bridge # line as soon as possible, we are having an outage.' # # To do this, we'll make use of the ExtCreateBroadcast_AD function (shown below), passing it six parameters: # # ExtCreateBroadcast_AD 'Test of Emergency' Emergency 1 0 '' 'Please call the emergency bridge line as soon as possible, we are having an outage' # # The ExtCreateBroadcast_AD function's full list of parameters is described in the example code below. # # ============================================================================================================================ function ExtCreateBroadcast_AD ( # The name of the Broadcast [String] $broadcastName, # The Active Directory "group" to call [String] $ADGroupName, # Broadcast Type 1-announcement, 2-survey, 3-SMS/Text, 4-SMS to opt-ins, Voice to remaining, 5-SMS to opt-ins voice to all [String] $broadcastType = "1", # CheckCallingWindow 0-DO NOT CHECK, 1-Only allow between default hours [String] $checkCallingWindow = "0", # When to send, leave empty for immediate "" else format = "12/25/2011 7:30 AM" [String] $launchDateTime = "", # Text to speak, send empty to ignore "" [String] $TTSText = "", # Text to speak for non live answer, send empty to ignore "" [String] $TTSTextVM = "", # Message ID to use [String] $messageID = "", # Message ID to use [String] $messageIDVM = "", # BC Type 3/4/5 the SMS message to send [String] $smsMsg = "", # Coming soon send email when BC completes [String] $notifyEmail ="" ) { [String] $username = '999111999' [String] $pin = '9991' [String] $callerID = "9725551212" $URL = "http://staging-api.call-em-all.com/webservices/ceaapi_v2.asmx" $Action = "http://call-em-all.com/ExtCreateBroadcast" $phoneNumberSource = "3" $commaDelimitedPhoneNumbers = $(GetADMembers $ADGroupName) [XML] $SOAPRequest = '&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap:Body&gt; &lt;ExtCreateBroadcast xmlns="http://call-em-all.com/"&gt; &lt;myRequest&gt; &lt;username&gt;' + $username +'&lt;/username&gt; &lt;pin&gt;' + $pin + '&lt;/pin&gt; &lt;TTSText&gt;' + $TTSText + '&lt;/TTSText&gt; &lt;TTSTextVM&gt;' + $TTSTextVM + '&lt;/TTSTextVM&gt; &lt;broadcastName&gt;' + $broadcastName + '&lt;/broadcastName&gt; &lt;broadcastType&gt;' + $broadcastType + '&lt;/broadcastType&gt; &lt;callerID&gt;' + $callerID + '&lt;/callerID&gt; &lt;checkCallingWindow&gt;' + $checkCallingWindow + '&lt;/checkCallingWindow&gt; &lt;phoneNumberSource&gt;' + $phoneNumberSource + '&lt;/phoneNumberSource&gt; &lt;commaDelimitedPhoneNumbers&gt;' + $commaDelimitedPhoneNumbers + '&lt;/commaDelimitedPhoneNumbers&gt; &lt;launchDateTime&gt;' + $launchDateTime + '&lt;/launchDateTime&gt; &lt;listID&gt;' + $listID + '&lt;/listID&gt; &lt;messageID&gt;' + $messageID + '&lt;/messageID&gt; &lt;messageIDVM&gt;' + $messageIDVM + '&lt;/messageIDVM&gt; &lt;notifyEmail&gt;' + $notifyEmail + '&lt;/notifyEmail&gt; &lt;smsMsg&gt;string&lt;/smsMsg&gt; &lt;/myRequest&gt; &lt;/ExtCreateBroadcast&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt;' write-host "Sending SOAP Request To Server: $URL" write-host "SOAP Request : " $SOAPRequest.Envelope.Body.ExtCreateBroadcast.myRequest $soapWebRequest = [System.Net.WebRequest]::Create($URL) $soapWebRequest.Headers.Add("SOAPAction", $Action) $soapWebRequest.ContentType = "text/xml;charset=`"utf-8`"" $soapWebRequest.Accept = "text/xml" $soapWebRequest.Method = "POST" write-host "Initiating Send." $requestStream = $soapWebRequest.GetRequestStream() $SOAPRequest.Save($requestStream) $requestStream.Close() write-host "Send Complete, Waiting For Response." $resp = $soapWebRequest.GetResponse() $responseStream = $resp.GetResponseStream() $soapReader = [System.IO.StreamReader]($responseStream) $ReturnXml = [Xml] $soapReader.ReadToEnd() $responseStream.Close() write-host "============================================" write-host "errorCode " $ReturnXml.Envelope.Body.ExtCreateBroadcastResponse.ExtCreateBroadcastResult.errorCode write-host "errorMessage " $ReturnXml.Envelope.Body.ExtCreateBroadcastResponse.ExtCreateBroadcastResult.errorMessage write-host "============================================" write-host "broadcastID " $ReturnXml.Envelope.Body.ExtCreateBroadcastResponse.ExtCreateBroadcastResult.broadcastID write-host "goodRecordCountOnFile " $ReturnXml.Envelope.Body.ExtCreateBroadcastResponse.ExtCreateBroadcastResult.goodRecordCountOnFile write-host "============================================================================" write-host "" write-host " If you did not specify a message/audio ID or provide Text-To-Speech info" write-host " then you need to call " $ReturnXml.Envelope.Body.ExtCreateBroadcastResponse.ExtCreateBroadcastResult.tollFreeNumber " and use recording ID : " $ReturnXml.Envelope.Body.ExtCreateBroadcastResponse.ExtCreateBroadcastResult.messageRecordingID write-host "" write-host "============================================================================" write-host "tollFreeNumber " $ReturnXml.Envelope.Body.ExtCreateBroadcastResponse.ExtCreateBroadcastResult.tollFreeNumber write-host "messageRecordingID " $ReturnXml.Envelope.Body.ExtCreateBroadcastResponse.ExtCreateBroadcastResult.messageRecordingID write-host "============================================" return [xml] $ReturnXml }
PowerShellCorpus/GithubGist/lantrix_bb0fea3b029dcbd1ca9c_raw_180f1c21e0c1b153dc32f5af762c79cf71c8a85a_stripe_2_ephemeral.ps1
lantrix_bb0fea3b029dcbd1ca9c_raw_180f1c21e0c1b153dc32f5af762c79cf71c8a85a_stripe_2_ephemeral.ps1
# # This will take the two non-system disks on an AWS windows server 2012 R2 instance and ERASE THEM; creating a single striped Volume. # WARNING: Before using this be sure to check that ((Get-Disk) |where issystem -eq $false) are actually the ***DISKS YOU WANT ERASED*** # #Get ephemeral disk $ephemeralDisks = (Get-Disk) |where issystem -eq $false if ($ephemeralDisks.Count -ne 2) {throw "Not correct amount of disks. Expecting 2"} #Prepare diskpart Script for each disk foreach ($disk in $ephemeralDisks) { $clean = "select disk $($disk.Number)"+[char][int](13)+[char][int](10); #Select Disk $clean += "clean"+[char][int](13)+[char][int](10); #Clear Disk $clean += "attributes disk clear readonly noerr "+[char][int](13)+[char][int](10); #set attributes $clean += "convert dynamic noerr "+[char][int](13)+[char][int](10); #convert to dynamic $clean += "exit"+[char][int](13)+[char][int](10); $clean | Set-Content c:\diskpartA_$($disk.Number).txt -Encoding ASCII } #Execute script for each disk foreach ($disk in $ephemeralDisks) { & Diskpart /s c:\diskpartA_$($disk.Number).txt Remove-Item c:\diskpartA_$($disk.Number).txt } #Prepare striped Ephemeral Volume $striped = "create volume stripe disk=" foreach ($disk in $ephemeralDisks) { #join volumes together for strip set $striped = $striped + $disk.Number + "," } $striped = $striped -replace ".$" #remove last , $striped = $striped +[char][int](13)+[char][int](10); #add CR/LF $striped += "format fs=NTFS unit=4096 label=`"Temporary Storage`" quick "+[char][int](13)+[char][int](10); #Format Vol $striped += "assign letter=Z "+[char][int](13)+[char][int](10); #Assign Drive Letter $striped += "exit"+[char][int](13)+[char][int](10); $striped | Set-Content c:\diskpartB.txt -Encoding ASCII #Execute striped Volume & Diskpart /s c:\diskpartB.txt Remove-Item c:\diskpartB.txt
PowerShellCorpus/GithubGist/gioxx_c71611db976536029c57_raw_e3f522cfc3311eeeb7f27d2ac9a4704edae08c91_LockoutAD.ps1
gioxx_c71611db976536029c57_raw_e3f522cfc3311eeeb7f27d2ac9a4704edae08c91_LockoutAD.ps1
# ACTIVE DIRECTORY: Alert mail quando un account utilizza una password errata #------------------------------------------------------------------------------- # Autore: GSolone # Utilizzo: E' necessario schedulare questo script quando si presenta l'evento da monitorare # (nel caso specifico qui di seguito è il 4771) # Info: http://wp.me/pdQ5q-4Rh # Ultima modifica: 28-04-2014 (rev1) # Diff: rev1- incluso l'if che permette di procedere con l'invio mail solo se l'account utente # che ha usato una password errata è quello specificato nella variabile AccountMonitor #------------------------------------------------------------------------------- # RAPIDO PROMEMORIA: # -InstanceID 4740: account bloccato # -InstanceID 4771: password errata #-------------------------------------------# # SPECIFICARE L'ACCOUNT DA MONITORARE: # $AccountMonitor = 'UTENTEDISERVIZIO' #-------------------------------------------# Import-Module ActiveDirectory $EventDetails = Get-EventLog -LogName Security -InstanceID 4771 -Newest 1 | Where-Object { $_.message -match $AccountMonitor } $LockedAccount = $($EventDetails.ReplacementStrings[0]) if ($AccountMonitor -eq $LockedAccount) { $EventDetailsTime = $EventDetails.TimeGenerated $EventDetailsMessage = $EventDetails.Message $messageParameters = @{ Subject = "Attenzione: Accesso negato per $LockedAccount" Body = "Qualcuno sta utilizzando una password sbagliata per l'account $LockedAccount (ultimo tentativo il $EventDetailsTime).`n`nDettagli evento:`n`n$EventDetailsMessage" From = "[email protected]" To = "[email protected]" SmtpServer = "smtp.azienda.tld" } Send-MailMessage @messageParameters }
PowerShellCorpus/GithubGist/rucka_4391732_raw_a058b5aced8d263315bd4c015efd22908fcd64c2_build-2012-ppt-download.ps1
rucka_4391732_raw_a058b5aced8d263315bd4c015efd22908fcd64c2_build-2012-ppt-download.ps1
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath foreach ($day in 2..4){ foreach ($number in 000..200 ) { $url = 'http://video.ch9.ms/sessions/build/2012/' + $day + '-' + ("{0:D3}" -f [int]$number) + '.pptx' $uri = New-Object System.Uri($url) $file = '' + $day + '-' + ("{0:D3}" -f [int]$number) + '.pptx' if (!(test-path $file)) { $wc = (New-Object System.Net.WebClient) #Set the username for windows auth proxy #$wc.proxy.credentials=[system.net.credentialcache]::defaultnetworkcredentials $wc.DownloadFile($uri, $file) Write-Host 'Try to download ' + $url } } }
PowerShellCorpus/GithubGist/VertigoRay_5068130_raw_de960d0eb286250cc7830384a7d066450d907026_SCCM2012-DeleteInvalideDrivers.ps1
VertigoRay_5068130_raw_de960d0eb286250cc7830384a7d066450d907026_SCCM2012-DeleteInvalideDrivers.ps1
$a = (Get-WmiObject -ComputerName 'myserver.fqdn' -Namespace 'root\SMS\Site_XXX' -Class 'SMS_Driver' | ?{!(test-path $_.ContentSourcePath)}) $a | %{$_.delete()}
PowerShellCorpus/GithubGist/nblumhardt_9884287_raw_0062236de71da5158f0953d24940b4c3b250c981_Octopus.Features.IISWebSite_BeforePostDeploy.ps1
nblumhardt_9884287_raw_0062236de71da5158f0953d24940b4c3b250c981_Octopus.Features.IISWebSite_BeforePostDeploy.ps1
## -------------------------------------------------------------------------------------- ## Configuration ## -------------------------------------------------------------------------------------- $ConfirmPreference = "None" $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 = "." } $maxFailures = $OctopusParameters["Octopus.Action.IISWebSite.MaxRetryFailures"] if ($maxFailures -Match "^\d+$") { $maxFailures = [int]$maxFailures } else { $maxFailures = 5 } $sleepBetweenFailures = $OctopusParameters["Octopus.Action.IISWebSite.SleepBetweenRetryFailuresInSeconds"] if ($sleepBetweenFailures -Match "^\d+$") { $sleepBetweenFailures = [int]$sleepBetweenFailures } else { $sleepBetweenFailures = Get-Random -minimum 1 -maximum 4 } if ($sleepBetweenFailures -gt 60) { Write-Host "Invalid Sleep time between failures. Setting to max of 60 seconds" $sleepBetweenFailures = 60 } # Helper to run a block with a retry if things go wrong function Execute-WithRetry([ScriptBlock] $command) { $attemptCount = 0 $operationIncomplete = $true while ($operationIncomplete -and $attemptCount -lt $maxFailures) { $attemptCount = ($attemptCount + 1) if ($attemptCount -ge 2) { Write-Output "Waiting for $sleepBetweenFailures seconds before retrying..." Start-Sleep -s $sleepBetweenFailures Write-Output "Retrying..." } try { & $command $operationIncomplete = $false } catch [System.Exception] { if ($attemptCount -lt ($maxFailures)) { Write-Output ("Attempt $attemptCount of $maxFailures failed: " + $_.Exception.Message) } else { throw } } } } $webRoot = (resolve-path $webRoot) $wsbindings = new-object System.Collections.ArrayList # Each binding string consists of a protocol/binding information (IP, port, hostname)/SSL thumbprint/enabled # Binding strings are pipe (|) separated to allow multiple to be specified $bindingString.Split("|") | foreach-object { $bindingParts = $_.split("/") $skip = $false if ($bindingParts.Length -ge 4) { if (![String]::IsNullOrEmpty($bindingParts[3]) -and [Bool]::Parse($bindingParts[3]) -eq $false) { $skip = $true } } if ($skip -eq $false) { $wsbindings.Add(@{ protocol=$bindingParts[0];bindingInformation=$bindingParts[1];thumbprint=$bindingParts[2] }) | Out-Null } else { Write-Host "Ignore binding: $_" } } 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 } | Select-Object -first 1 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) -or ($ipAddress -eq '*')) { $ipAddress = "0.0.0.0" } $port = $bindingParts[1] $sslBindingsPath = ("IIS:\SslBindings\" + $ipAddress + "!" + $port) Execute-WithRetry { $sslBinding = get-item $sslBindingsPath -ErrorAction SilentlyContinue if (! $sslBinding) { New-Item $sslBindingsPath -Value $certificate -confirm:$false -Force | Out-Null } else { Set-Item $sslBindingsPath -Value $certificate | Out-Null } } } ## -------------------------------------------------------------------------------------- ## Run ## -------------------------------------------------------------------------------------- pushd IIS:\ $appPoolPath = ("IIS:\AppPools\" + $ApplicationPoolName) Execute-WithRetry { $pool = Get-Item $appPoolPath -ErrorAction SilentlyContinue if (!$pool) { Write-Host "Application pool `"$ApplicationPoolName`" does not exist, creating..." new-item $appPoolPath -confirm:$false -Force $pool = Get-Item $appPoolPath } else { Write-Host "Application pool `"$ApplicationPoolName`" already exists" } } Execute-WithRetry { 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"} } } Execute-WithRetry { Write-Host "Set .NET framework version: $appPoolFrameworkVersion" Set-ItemProperty $appPoolPath managedRuntimeVersion $appPoolFrameworkVersion } $sitePath = ("IIS:\Sites\" + $webSiteName) Execute-WithRetry { $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 -confirm:$false -Force } else { Write-Host "Site `"$WebSiteName`" already exists" } } $cmd = { Write-Host "Assigning website to application pool..." Set-ItemProperty $sitePath -name applicationPool -value $ApplicationPoolName } Execute-WithRetry -Command $cmd Execute-WithRetry { Write-Host ("Home directory: " + $webRoot) Set-ItemProperty $sitePath -name physicalPath -value "$webRoot" } Execute-WithRetry { 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 + " " + $wsbindings[$i].thumbprint)) New-ItemProperty $sitePath -name bindings -value ($wsbindings[$i]) -Force } } try { Execute-WithRetry { Write-Host "Anonymous authentication enabled: $enableAnonymous" Set-WebConfigurationProperty -filter /system.webServer/security/authentication/anonymousAuthentication -name enabled -value "$enableAnonymous" -location $WebSiteName -PSPath "IIS:\" } Execute-WithRetry { Write-Host "Basic authentication enabled: $enableBasic" Set-WebConfigurationProperty -filter /system.webServer/security/authentication/basicAuthentication -name enabled -value "$enableBasic" -location $WebSiteName -PSPath "IIS:\" } Execute-WithRetry { Write-Host "Windows authentication enabled: $enableWindows" Set-WebConfigurationProperty -filter /system.webServer/security/authentication/windowsAuthentication -name enabled -value "$enableWindows" -location $WebSiteName -PSPath "IIS:\" } } catch [System.Exception] { Write-Output "Authentication options could not be set. This can happen when there is a problem with your application's web.config. For example, you might be using a section that requires an extension that is not installed on this web server (such as URL Rewrtiting). It can also happen when you have selected an authentication option and the appropriate IIS module is not installed (for example, for Windows authentication, you need to enable the Windows Authentication module in IIS/Windows first)" throw } # It can take a while for the App Pool to come to life (#490) Start-Sleep -s 1 Execute-WithRetry { $state = Get-WebAppPoolState $ApplicationPoolName if ($state.Value -eq "Stopped") { Write-Host "Application pool is stopped. Attempting to start..." Start-WebAppPool $ApplicationPoolName } } Execute-WithRetry { $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/coza73_c9f56bfe8b05cd17ac88_raw_3895d14a742570afd704da7bf7d44f11becaf969_vSphere_SysLogCollector_Shortcut.ps1
coza73_c9f56bfe8b05cd17ac88_raw_3895d14a742570afd704da7bf7d44f11becaf969_vSphere_SysLogCollector_Shortcut.ps1
######################################################################################################## # # Powershell Script for vSphere Syslog Collector # # Uses IP address from directories created for each esxi host to do a DNS lookup and create shortcuts # for for those folders based on the returned DNS of the esxi host # # http://vspherepowershellscripts.blogspot.com.au/2014/07/test.html # ######################################################################################################## Function ReverseDNS { $nslookup = "nslookup " + $args[0] + " " + $ns + " 2> null" $result = Invoke-Expression ($nslookup) $global:reverse_solved_ip = $result.SyncRoot[3] # If nslookup returns no result set variable to 'No record found' if ($result.count -lt 4) { $global:reverse_solved_ip = "No record found" } else { #Trim off the first 9 charactors from the start this removes the 'Name:' from the output $global:reverse_solved_ip = $global:reverse_solved_ip.Remove(0,9) } } # Name Server which will do name resolution $ns = "dns.server.com" #Root path of log folders (always include the trailing backslash) $folderpath = "C:\ProgramData\VMware\VMware Syslog Collector\Data\" # Create array of folder names to feed into ReverseDNS function $foldername = Get-ChildItem $folderpath | Where-Object {$_.PSIsContainer} | Foreach-Object {$_.Name} # Loop through each folder name Foreach ($ip in $foldername){ # Feed IP address into ReverseDNS function ReverseDNS $ip #Write some output so you can see what is going on Write-Host $ip Write-Host $reverse_solved_ip Write-Host "" # For all records in array that do not contain 'No record found' if ($reverse_solved_ip -ne "No record found") { #Create Shortcut $target = $folderpath + $ip $shortcut = $folderpath + $reverse_solved_ip + ".lnk" $wshshell = New-Object -ComObject WScript.Shell $link = $wshshell.CreateShortcut($shortcut) $link.TargetPath = $target $link.Save() } }
PowerShellCorpus/GithubGist/robdmoore_af6ec893c85364a97dc4_raw_e6dc89be153afd0b3dc888f7f91dd98ea74266b6_setup-cordova-phonegap.ps1
robdmoore_af6ec893c85364a97dc4_raw_e6dc89be153afd0b3dc888f7f91dd98ea74266b6_setup-cordova-phonegap.ps1
# Run this in an elevated PowerShell prompt <# This script worked on a fresh Windows Server 2012 VM in Azure and the following were the latest versions of each package at the time: * Chocolatey 0.9.8.27 * java.jdk 7.0.60.1 * apache.ant 1.8.4 * android-sdk 22.6.2 * cordova 3.5.0-0.2.6 * nodejs.install 0.10.29 #> # Note: there is one bit that requires user input (accepting the Android SDK license terms) # Install Chocolatey iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) choco # Check this works # Install Java JDK cinst java.jdk # Set Java bin dir as first thing on path to override java.exe in Windows [System.Environment]::SetEnvironmentVariable("PATH", [System.Environment]::GetEnvironmentVariable("JAVA_HOME","Machine") + "\bin;" + [System.Environment]::GetEnvironmentVariable("Path","Machine"), "Machine") $env:PATH = [System.Environment]::GetEnvironmentVariable("PATH", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("PATH", "User") javac # Check this works # Install ant cinst apache.ant $env:PATH = [System.Environment]::GetEnvironmentVariable("PATH", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("PATH", "User") ant # Check this works # Install Android SDK cinst android-sdk [System.Environment]::SetEnvironmentVariable("PATH", [System.Environment]::GetEnvironmentVariable("PATH", "Machine") + ";$env:LOCALAPPDATA\android\android-sdk\tools;$env:LOCALAPPDATA\android\android-sdk\platform-tools", "Machine") $env:PATH = [System.Environment]::GetEnvironmentVariable("PATH", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("PATH", "User") # Update Android SDK bits android list sdk <# This lists out all the things to install. You want to choose the marked items (x) next to the following for the next command: x1- Android SDK Tools, revision 23 x2- Android SDK Platform-tools, revision 20 x3- Android SDK Build-tools, revision 19.1 4- Documentation for Android SDK, API 19, revision 2 x5- SDK Platform Android 4.4.2, API 19, revision 3 ... Alternatively, you can just run "android" and use the GUI :) #> android update sdk --no-ui --filter "1,2,3,5" # You will need to enter "y[enter]" to accept the license terms adb # Check this works # Install nodejs cinst nodejs.install $env:PATH = [System.Environment]::GetEnvironmentVariable("PATH", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("PATH", "User") npm # Check this works # Install Cordova npm install -g cordova cordova # Check this works # Check everything works cordova create helloworld cd helloworld cordova platform add android cordova build cd .. # Install Phonegap (optional) npm install -g phonegap phonegap # Check this works # Check everything works phonegap create helloworld2 cd helloworld2 phonegap build android cd ..
PowerShellCorpus/GithubGist/humbleposh_7366544_raw_a78d1d2d102992e2d03f74492fed4d84530ca0dd_OfflineFiles_1.ps1
humbleposh_7366544_raw_a78d1d2d102992e2d03f74492fed4d84530ca0dd_OfflineFiles_1.ps1
# Emumerate Offline Files $OfflineFilesItem = [wmiclass]"\\localhost\root\cimv2:win32_offlinefilesItem" $FileList = $OfflineFilesItem.GetInstances() # Filter based on share that you want to know if someone has taken offline $FileList | ?{$_.ItemPath -like "\\server\share*"} | select ItemPath
PowerShellCorpus/GithubGist/nate-strauser_2346682_raw_75f2e57e88c31e5cbd3aa5b3be5e1fe2275e834e_churnQueue.ps1
nate-strauser_2346682_raw_75f2e57e88c31e5cbd3aa5b3be5e1fe2275e834e_churnQueue.ps1
function get-queueLength(){ try { $s = (New-Object net.webclient).DownloadString('http://localhost:56785/stats.json') } catch { return "queue length unavailable" } $queueLength = $s -split (',') | foreach{if ($_ | select-string "queueLength" -quiet){ ($_ -split ":")[1]}} return $queueLength } $service = "Kiln Queuing Service" $queueLength = get-queueLength while($queueLength -gt 1){ "queue length $queueLength" $status = sc.exe query $service $running = $status -match "RUNNING" if (!$running){ "service was not running - starting" sc.exe start $service start-sleep -s 5 $status = sc.exe query $service "service started" $status }else{ "service already running" } start-sleep -s 15 $queueLength = get-queueLength }
PowerShellCorpus/GithubGist/andyhey_5480259_raw_5effbc21d8187a0cb50d98da185966d0777d3b00_gistfile1.ps1
andyhey_5480259_raw_5effbc21d8187a0cb50d98da185966d0777d3b00_gistfile1.ps1
Get-ChildItem -Path E:\ROOT_OF_ALL_WEBSITES -Filter umbraco.webservices.dll -Recurse
PowerShellCorpus/GithubGist/pohatu_10701938_raw_bc56c5325e883986a868671ff28e1ccae1d12ccc_ConvertTo-MarkDownTable.ps1
pohatu_10701938_raw_bc56c5325e883986a868671ff28e1ccae1d12ccc_ConvertTo-MarkDownTable.ps1
function ConvertTo-MarkDownTable() { $in = [windows.clipboard]::GetText() $lines = $in.split("`n") $out=@() $out += $lines[0] -replace "`r",'' -replace "^","|" -replace ",","|" -replace "$","|`n" $out += $lines[0] -replace "`r",'' -replace "\w+","---" -replace "^","|" -replace ",","|" -replace "$","|`n" $out += $lines[1..($lines.Count-1)] -replace "`r", '' -replace "^", "|" -replace ",","|" -replace "$", "|`n" [windows.clipboard]::SetText($out -join "") } ## input is a comma-seperated multi-line segment ## ex: ## foo,bar,buzz,bazz,biff ## 1,2,3,4,5 ## 6,7,8,9,10 ## ## ## output is markdown-style table ## ## example: ## |foo|bar|buzz|bazz|biff| ## |---|---|---|---|---| ## |1|2|3|4|5| ## |6|7|8|9|10| ## doesn't care about right-aligned or centered, just does default. ## Doesn't care about pretty.
PowerShellCorpus/GithubGist/PyYoshi_3236576_raw_f39dfa10d73044258661cc93a83e590c77b75c70_Microsoft.PowerShell_profile.ps1
PyYoshi_3236576_raw_f39dfa10d73044258661cc93a83e590c77b75c70_Microsoft.PowerShell_profile.ps1
# virtualenvwrapper用の設定 $WORKON_HOME = "$HOME\.virtualenvs" $env:WORKON_HOME = $WORKON_HOME # $WORKON_HOMEがない場合は作成する if(-not(Test-Path -Path $WORKON_HOME)){ New-Item -Path $WORKON_HOME -itemType Directory | Out-Null } # virtualenvwrapper-powershellを起動時にロードする $virtualenv_module_path = "$profile\..\Modules\VirtualEnvWrapper" Import-Module $virtualenv_module_path
PowerShellCorpus/GithubGist/XPlantefeve_adf352d758ccf276959d_raw_1001eaf5448b992373e892d6d155e6c13d1b180f_ConvertFrom-Csave.ps1
XPlantefeve_adf352d758ccf276959d_raw_1001eaf5448b992373e892d6d155e6c13d1b180f_ConvertFrom-Csave.ps1
Function ConvertFrom-Csave { [CmdletBinding(DefaultParameterSetName='UseDelimiter')] Param ( [Parameter(Position=2,ParameterSetName='UseDelimiter')] [char]$Delimiter = ',', # FIXME [string[]] $Header, [Parameter(Mandatory=$True,Position=1,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)] [PSObject] $InputObject, [Parameter(Mandatory=$True,Position=2,ParameterSetName='UseCulture')] [switch] $UseCulture ) Begin { $OutputObject = New-Object PSCustomObject $HeadersDone = $false $Properties = @() If ( $UseCulture ) { $Delimiter = (Get-Culture).TextInfo.ListSeparator } } Process { If ( $InputObject -like '#TYPE *') { $OutputObject.pstypenames.insert(0,'CSV:' + $InputObject.ToString().Replace('#TYPE ','')) } ElseIf ( !$HeadersDone ) { foreach ( $Property in $InputObject.Split($Delimiter) ) { $Properties += $property -Replace('^"(.*)"$', '$1') Add-Member -InputObject $OutputObject -MemberType NoteProperty -Name ($property -Replace('^"(.*)"$', '$1')) -Value "" } $HeadersDone = $True } else { $i = 0 foreach ( $Property in $InputObject.Split($Delimiter) ) { $OutputObject."$($Properties[$i])" = $property -Replace('^"(.*)"$', '$1') $i++ } $OutputObject } } }
PowerShellCorpus/GithubGist/nzbart_9791503_raw_915cabda04bda9d33a41b4ae9f6f3579a066fd6c_ShowSassTree.ps1
nzbart_9791503_raw_915cabda04bda9d33a41b4ae9f6f3579a066fd6c_ShowSassTree.ps1
param([string][parameter(mandatory)]$ParentFile, [string][parameter(mandatory)]$RootFile, [int][parameter(mandatory)]$Depth, [string][parameter(mandatory)]$IncludePath, [switch]$RenderDotFormat, [switch]$DoNotRecurse) function RenderImports([string][parameter(mandatory)]$ParentFile, [string][parameter(mandatory)]$RootFile, [int][parameter(mandatory)]$Depth, [string][parameter(mandatory)]$IncludePath, [switch]$RenderDotFormat, [switch]$DoNotRecurse) { $ErrorActionPreference = 'Stop' function GetRelativePath([string][parameter(mandatory)]$ParentFile, [string][parameter(mandatory)]$RootFile) { pushd (Split-Path -Parent $ParentFile) try { (Resolve-Path -Relative $RootFile) -replace '^\.\\', '' } finally { popd } } function EscapeDotCharacters([string][parameter(mandatory)]$value) { return $value -replace '\\', '\\' } if($RenderDotFormat) { if($Depth -eq 0) { echo "digraph g{" } $left = EscapeDotCharacters $ParentFile $right = EscapeDotCharacters $RootFile echo "`"$left`" -> `"$right`";" } else { $indent = New-Object System.String ' ', ($Depth * 4) $relativePath = GetRelativePath $ParentFile (Resolve-Path $RootFile) echo "$indent $relativePath" } if(!$DoNotRecurse) { cat $RootFile | % { if($_ -match '^\s*@import\s*"([^"]+)"') { $file = $Matches[1] $leaf = Split-Path -Leaf $file $parent = Split-Path -Parent $file $rootDir = Split-Path -Parent $RootFile $path = Join-Path $rootDir "$parent\_$leaf.scss" if((Test-Path $path)) { RenderImports $RootFile $path ($Depth + 1) $IncludePath -RenderDotFormat:$RenderDotFormat } else { $path = Join-Path $IncludePath "$parent\_$leaf.scss" if(!(Test-Path $path)) { throw "Unable to find import: $file." } RenderImports $RootFile $path ($Depth + 1) $IncludePath -RenderDotFormat:$RenderDotFormat -DoNotRecurse } } } } if($RenderDotFormat) { if($Depth -eq 0) { echo "}" } } } RenderImports $ParentFile $RootFile $Depth $IncludePath -RenderDotFormat:$RenderDotFormat -DoNotRecurse:$DoNotRecurse
PowerShellCorpus/GithubGist/jhorsman_88b05a6938ca4de2e021_raw_181433f48fad42e57d67ec25c2ec1803d2f4da10_vs.ps1
jhorsman_88b05a6938ca4de2e021_raw_181433f48fad42e57d67ec25c2ec1803d2f4da10_vs.ps1
# http://boxstarter.org/package/url? # It's nice to be able to browse NuGet files if necessary cinstm NugetPackageExplorer # Visual Studio! cinstm VisualStudio2012Professional # Get rid of upper case menu in Visual Studio Set-ItemProperty -Path HKCU:\Software\Microsoft\VisualStudio\11.0\General -Name SuppressUppercaseConversion -Type DWord -Value 1 # Run Visual Studio Update if((Get-Item "$($Boxstarter.programFiles86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe").VersionInfo.ProductVersion -lt "11.0.60115.1") { if(Test-PendingReboot){Invoke-Reboot} Install-ChocolateyPackage 'vs update 2 ctp2' 'exe' '/passive /norestart' 'http://download.microsoft.com/download/8/9/3/89372D24-6707-4587-A7F0-10A29EECA317/vsupdate_KB2707250.exe' } # JetBrains ReSharper cinstm resharper
PowerShellCorpus/GithubGist/willryan_3e6af7565fba09fdadd4_raw_b20354484a34d04f04703afd57bfe64b45dd6c43_stop_iis_express.ps1
willryan_3e6af7565fba09fdadd4_raw_b20354484a34d04f04703afd57bfe64b45dd6c43_stop_iis_express.ps1
foreach($proc in (ps | Where { $_.name -like "iisexpress"} )) { $iisid = $proc.Id $iis = Get-WmiObject Win32_Process -filter "ProcessId=$iisid" | Where-Object { $_.CommandLine -like "*MyProjectName*" } | Select-Object -first 1 if($iis) { stop-process -force $iis.ProcessId } }
PowerShellCorpus/GithubGist/richjenks_5933156_raw_7ebd230726039c211ed0828b78e7a8afe8c21586_delete-empty-directories.ps1
richjenks_5933156_raw_7ebd230726039c211ed0828b78e7a8afe8c21586_delete-empty-directories.ps1
Get-ChildItem -recurse | Where {$_.PSIsContainer -and @(Get-ChildItem -Lit $_.Fullname -r | Where {!$_.PSIsContainer}).Length -eq 0} | Remove-Item -recurse
PowerShellCorpus/GithubGist/pkirch_aff99159719addbd5e95_raw_08d7cc3dd11e7e0b9b68d4db8b9742431b691ee4_Get-AzureVMSelectStatusSample.ps1
pkirch_aff99159719addbd5e95_raw_08d7cc3dd11e7e0b9b68d4db8b9742431b691ee4_Get-AzureVMSelectStatusSample.ps1
Get-AzureVM -ServiceName leasetest3 -Name host3 | Select-Object -Property Status <# Output Status ------ RoleStateUnknown #>
PowerShellCorpus/GithubGist/zorab47_9508715_raw_3601a8227b3bc3faf2f0a3ebc3e5f638cc4640fa_fix-virtualbox-adapters.ps1
zorab47_9508715_raw_3601a8227b3bc3faf2f0a3ebc3e5f638cc4640fa_fix-virtualbox-adapters.ps1
# Adaptation of the VMware adapters fix script by Oisin Grehan: # http://www.nivot.org/post/2008/09/05/VMWareVMNETAdaptersTriggeringPublicProfileForWindowsFirewall.aspx # see http://msdn2.microsoft.com/en-us/library/bb201634.aspx # # *NdisDeviceType # # The type of the device. The default value is zero, which indicates a standard # networking device that connects to a network. # # Set *NdisDeviceType to NDIS_DEVICE_TYPE_ENDPOINT (1) if this device is an # endpoint device and is not a true network interface that connects to a network. # For example, you must specify NDIS_DEVICE_TYPE_ENDPOINT for devices such as # smart phones that use a networking infrastructure to communicate to the local # computer system but do not provide connectivity to an external network. # # Usage: run in an elevated shell (vista/longhorn) or as adminstrator (xp/2003). # # PS> .\fix-vbox-adapters.ps1 # boilerplate elevation check $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = new-object Security.Principal.WindowsPrincipal $identity $elevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $elevated) { $error = "Sorry, you need to run this script" if ([System.Environment]::OSVersion.Version.Major -gt 5) { $error += " in an elevated shell." } else { $error += " as Administrator." } throw $error } $entryName = '*NdisDeviceType' $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", ` "Set the '$entryName' entry for this adapter to 1." $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", ` "Skip this adapter." $reset = $false # adapters key pushd 'hklm:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}' # ignore and continue on error dir -ea 0 | % { $key = $_.pspath $desc = gp $key -name driverdesc -ea 0 if ($desc.driverdesc -eq "VirtualBox Host-Only Ethernet Adapter") { write-host "`nFound adapter: $($desc.driverdesc)" -ForegroundColor White $state = "Registry entry '$entryName' " $entry = gp $key -name $entryName -ea 0 if ($entry -eq $null) { $value = $null $state = $state + "does not exist for this adapter" } else { $value = $entry.$entryName if ($value -eq 1) { $state = $state + "already exists and is set to '1'." } else { $state = $state + "exists, but is set to '$value', not'1'" } } if ($value -eq 1) { write-host $state -ForegroundColor White } else { if ($host.ui.PromptForChoice( $state, "`nDo you want to fix it?`n`n", [Management.Automation.Host.ChoiceDescription[]]@($yes, $no), 1) -eq 0) { $reset = $true write-host "" if ($entry -eq $null) { write-host -nonew "Creating $entryName entry ... " $entry = new-itemproperty $key -name $entryName -propertytype dword -value 1 if ($entry.$entryName -eq 1) { write-host " success." } else { write-host " failed." } } else { write-host -nonew "Modifying $entryName entry ... " $entry = set-itemproperty $key -name $entryName -value 1 if ($entry.$entryName -eq 1) { write-host " success." } else { write-host " failed." } } } } write-host "" } } popd if ($reset) { # if there were registry changes, disable/enable network adapters gwmi win32_networkadapter | ? {$_.name -like "VirtualBox Host-Only Ethernet Adapter*" } | % { # disable write-host -nonew "Disabling $($_.name) ... " $result = $_.Disable() if ($result.ReturnValue -eq -0) { write-host " success." } else { write-host " failed." } # enable write-host -nonew "Enabling $($_.name) ... " $result = $_.Enable() if ($result.ReturnValue -eq -0) { write-host " success." } else { write-host " failed." } } } else { write-host "No registry changes were made." -ForegroundColor White }
PowerShellCorpus/GithubGist/winterheart_5211370_raw_4b6241a7838111f6f19a991c4dfd0a9e95c94b1f_get-all-mailboxes.ps1
winterheart_5211370_raw_4b6241a7838111f6f19a991c4dfd0a9e95c94b1f_get-all-mailboxes.ps1
# Copyright (c) 2013 Azamat H. Hackimov <[email protected]> # MIT License, see http://opensource.org/licenses/MIT for full text # Этот сценарий получает список всех почтовых аккаунтов Exchange 2010 со следующей информацией: # Имя, Основной SMTP-адрес, База данных хранения, Количество сообщений, Общий объем сообщений в Мб, Действующие ограничения по объему, Последняя аутентификация, Контейнер в AD # Список экспортируется в CSV-файл All_users.csv по месту нахождения сценария. Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010; $emails = Get-Mailbox -ResultSize unlimited; foreach ($email in $emails) { $mailstats = Get-MailboxStatistics $email; $email | add-member -type noteProperty -name TotalItemSizeMB -value $mailstats.TotalItemSize.value.ToMB(); $email | add-member -type noteProperty -name ItemCount -value $mailstats.ItemCount; $email | add-member -type noteProperty -name StorageLimitStatus -value $mailstats.StorageLimitStatus; $email | add-member -type noteProperty -name LastLogonTime -value $mailstats.LastLogonTime; } $emails | select Name,PrimarySMTPAddress,Database,ItemCount,TotalItemSizeMB,StorageLimitStatus,LastLogonTime,OrganizationalUnit | sort-object -Descending "TotalItemSizeMB" | Export-Csv -Delimiter ";" -Encoding Default -path All_users.csv;
PowerShellCorpus/GithubGist/sandrinodimattia_4128649_raw_ba50d35a3b8a787c7adb365bfc440f8949bc5b4c_Import-AzureEndpointsFromCSV.ps1
sandrinodimattia_4128649_raw_ba50d35a3b8a787c7adb365bfc440f8949bc5b4c_Import-AzureEndpointsFromCSV.ps1
# Arguments. param ( [Microsoft.WindowsAzure.Management.ServiceManagement.Model.PersistentVMRoleContext]$vm = $(throw "'vm' is required."), [string]$csvFile = $(throw "'csvFile' is required."), [string]$parameterSet = $(throw "'parameterSet' is required.") ) Get-ChildItem "${Env:ProgramFiles(x86)}\Microsoft SDKs\Windows Azure\PowerShell\Azure\*.dll" | ForEach-Object {[Reflection.Assembly]::LoadFile($_) | out-null } # Add endpoints without loadbalancer. if ($parameterSet -eq "NoLB") { Write-Host -Fore Green "Adding NoLB endpoints:" $endpoints = Import-Csv $csvFile -header Name,Protocol,PublicPort,LocalPort -delimiter ';' | foreach { New-Object PSObject -prop @{ Name = $_.Name; Protocol = $_.Protocol; PublicPort = [int32]$_.PublicPort; LocalPort = [int32]$_.LocalPort; } } # Add each endpoint. Foreach ($endpoint in $endpoints) { Add-AzureEndpoint -VM $vm -Name $endpoint.Name -Protocol $endpoint.Protocol.ToLower() -PublicPort $endpoint.PublicPort -LocalPort $endpoint.LocalPort } } # Add endpoints with loadbalancer. elseif ($parameterSet -eq "LoadBalanced") { Write-Host -Fore Green "Adding LoadBalanced endpoints:" $endpoints = Import-Csv $csvFile -header Name,Protocol,PublicPort,LocalPort,LBSetName,ProbePort,ProbeProtocol,ProbePath -delimiter ';' | foreach { New-Object PSObject -prop @{ Name = $_.Name; Protocol = $_.Protocol; PublicPort = [int32]$_.PublicPort; LocalPort = [int32]$_.LocalPort; LBSetName = $_.LBSetName; ProbePort = [int32]$_.ProbePort; ProbeProtocol = $_.ProbeProtocol; ProbePath = $_.ProbePath; } } # Add each endpoint. Foreach ($endpoint in $endpoints) { Add-AzureEndpoint -VM $vm -Name $endpoint.Name -Protocol $endpoint.Protocol.ToLower() -PublicPort $endpoint.PublicPort -LocalPort $endpoint.LocalPort -LBSetName $endpoint.LBSetName -ProbePort $endpoint.ProbePort -ProbeProtocol $endpoint.ProbeProtocol -ProbePath $endpoint.ProbePath } } else { $(throw "$parameterSet is not supported. Allowed: NoLB, LoadBalanced") } # Update VM. Write-Host -Fore Green "Updating VM..." $vm | Update-AzureVM Write-Host -Fore Green "Done."
PowerShellCorpus/GithubGist/mbrownnycnyc_9913361_raw_858ae126e2f7bcb417448ec8dfaf826601154b42_veryfastping.ps1
mbrownnycnyc_9913361_raw_858ae126e2f7bcb417448ec8dfaf826601154b42_veryfastping.ps1
# with reference to http://theadminguy.com/2009/04/30/portscan-with-powershell/ function fastping{ [CmdletBinding()] param( [String]$computername = "127.0.0.1", [int]$delay = 100 ) $ping = new-object System.Net.NetworkInformation.Ping # see http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipstatus%28v=vs.110%29.aspx try { if ($ping.send($computername,$delay).status -ne "Success") { return $false; } else { return $true; } } catch { return $false; } }
PowerShellCorpus/GithubGist/NomikOS_9491294_raw_ec4090feb482e714ae947ef45f73c77bec11d7d0_gistfile1.ps1
NomikOS_9491294_raw_ec4090feb482e714ae947ef45f73c77bec11d7d0_gistfile1.ps1
# Encontrar directorios (-type d) en el directorio actual (.) y darles # acceso 755 find . -type d -exec chmod 755 {} \; # Encontrar archivos (-type f) en el directorio actual (.) y darles # acceso 644 find . -type f -exec chmod 644 {} \; # Encontrar archivos (-type f) html (-name '*.htm*') en el subdirectorio # web (./web) y darles acceso 644 find ./web -type f -name '*.htm*' -exec chmod 644 {} \; # Encontrar archivos/directorios con permiso 777 (-perm 777) en el # directorio actual (.) y darles acceso 755. La opción -print entrega # más información sobre el resultado find . -perm 777 -exec chmod 755 {} \; -print
PowerShellCorpus/GithubGist/jonnii_5065804_raw_5487f0776d5c3136c421851a9bf6525f03258bef_gistfile1.ps1
jonnii_5065804_raw_5487f0776d5c3136c421851a9bf6525f03258bef_gistfile1.ps1
param($installPath, $toolsPath, $package) # notify the user we're going to be doing something destructive # find out where to put the files, we're going to assume that the # solution file is in a ./src directory and we want to put # everything in a ./build directory at the same level. $rootDir = (Get-Item $installPath).parent.parent.parent.fullname $deployTarget = "$rootDir\deploy\support\" # create our deploy support directory if it doesn't exist yet $deploySource = join-path $installPath 'tools/deploy' if (!(test-path $deployTarget)) { mkdir $deployTarget } # copy everything in there Copy-Item "$deploySource/*" $deployTarget -Recurse -Force # get the active solution $solution = Get-Interface $dte.Solution ([EnvDTE80.Solution2]) # create a deploy solution folder if it doesn't exist $deployFolder = $solution.Projects | where-object { $_.ProjectName -eq "Deploy" } | select -first 1 if(!$deployFolder) { $deployFolder = $solution.AddSolutionFolder("Deploy") } # add all our support deploy scripts to our Support solution folder $folderItems = Get-Interface $deployFolder.ProjectItems ([EnvDTE.ProjectItems]) ls $deployTarget | foreach-object { $folderItems.AddFromFile($_.FullName) > $null } > $null
PowerShellCorpus/GithubGist/petarvucetin_5616160_raw_7eda51c29f41522ab575e89436bc325a7c4a48da_NuGet.Downloader.ps1
petarvucetin_5616160_raw_7eda51c29f41522ab575e89436bc325a7c4a48da_NuGet.Downloader.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/ritalin_c9b9cfe58222c1756735_raw_a0263b0d3d3aa0154aa336a451d6b6db836a3178_autoload-module-config.ps1
ritalin_c9b9cfe58222c1756735_raw_a0263b0d3d3aa0154aa336a451d6b6db836a3178_autoload-module-config.ps1
function test(){ get-pscallstack | select -skip 1 -first 1 | %{ if ([io.path]::GetExtension($_.ScriptName) -eq ".psm1") { if (test-path "$($_.ScriptName).config") { [xml](Get-Content "$($_.ScriptName).config") } elseif (test-path "$($_.ScriptName).json") { [string]::join('', (Get-Content "$($_.ScriptName).json")) | ConvertFrom-Json } else { @{} } } else { @{} } } }
PowerShellCorpus/GithubGist/PProvost_2583571_raw_98fa318e23388717f15b26f0860aea294796af57_gistfile1.ps1
PProvost_2583571_raw_98fa318e23388717f15b26f0860aea294796af57_gistfile1.ps1
$str = "some long assed string you want to convert" $str.ToCharArray() | % { "&#{0};" -f [Convert]::ToInt32($_) } | Join-String | clip
PowerShellCorpus/GithubGist/pkirch_553defb9c3b71018aeca_raw_c1193595699c93b717b388e2a9d6981e975f0180_MVA01-AzureVM.ps1
pkirch_553defb9c3b71018aeca_raw_c1193595699c93b717b388e2a9d6981e975f0180_MVA01-AzureVM.ps1
# Sample by Peter Kirchner ([email protected]) # Settings $subscriptionName = "MSFT MVA Live" # Get-AzureSubscription $location = "West Europe" # Get-AzureLocation $serviceName = "pktestservice" $storageAccountName = "pkteststorage" $storageContainerName = "vhds" $adminUsername = "adm_test" $adminPassword = "Azureisttoll!" $imageNameWS2012R2 = "a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-201410.01-en.us-127GB.vhd" # Get-AzureVMImage $vmName = "host1" # In case you have more than one Azure subscription, select one. Set-AzureSubscription -SubscriptionName $subscriptionName # 1st: create cloud service New-AzureService -Location $location -ServiceName $serviceName # 2nd: create storage account. New-AzureStorageAccount -Location $location -StorageAccountName $storageAccountName # 3rd: create container for VHDs. $storageAccountKey = Get-AzureStorageKey -StorageAccountName $storageAccountName $storageContext = New-AzureStorageContext -StorageAccountKey $storageAccountKey.Primary -StorageAccountName $storageAccountKey.StorageAccountName $result = New-AzureStorageContainer -Name $storageContainerName -Permission Off -Context $storageContext # 4th: New-AzureVM needs the CurrentStorageAccountName to be set. Set-AzureSubscription -SubscriptionName $subscriptionName -CurrentStorageAccountName $storageAccountName # 5th: create new VM configuration. $vmConfig = New-AzureVMConfig -ImageName $imageNameWS2012R2 -InstanceSize Small -Name $vmName ` -MediaLocation "https://$storageAccountName.blob.core.windows.net/$storageContainerName/$vmName.vhd" # 6th: add provisioning data to VM configuration. $vmConfig = Add-AzureProvisioningConfig -Windows -AdminUsername $AdminUsername -Password $AdminPassword -VM $vmConfig # 7th: create new VM and let it start. New-AzureVM -ServiceName $serviceName -Location $location -VMs $vmConfig
PowerShellCorpus/GithubGist/colorqualia_8119866_raw_078513100466c52eb0742ab85edf86c1b9880d23_gitignore.ps1
colorqualia_8119866_raw_078513100466c52eb0742ab85edf86c1b9880d23_gitignore.ps1
#PowerShell v3 script Function gitignore { Param( [Parameter(Mandatory=$true)] [string[]]$list ) $params = $list -join "," invoke-WebRequest -Uri "http://gitignore.io/api/$params" | select -expandproperty content | out-file -FilePath $(join-path -path $pwd -ChildPath ".gitignore") -Encoding ascii }
PowerShellCorpus/GithubGist/selfcommit_696d2a45593313044dde_raw_899ca3d60eb03a653158eb0b45dbf9382b3298cd_AdMembers.ps1
selfcommit_696d2a45593313044dde_raw_899ca3d60eb03a653158eb0b45dbf9382b3298cd_AdMembers.ps1
$Group = "All" $path = $("C:\Users\doboyle.STACKEXCHANGE\Desktop\", $Group, ".txt" -join "") #There's no Header in our TSV, so we define one as "GoogleUser" $csv = Import-Csv -Delimiter t -Encoding UTF8 -Header GoogleUser -Path $path foreach ($user in $csv) { $email = $($user.GoogleUser.ToString(), "@stackoverflow.com" -join "") $user = Get-ADUser -Filter {mail -like $email} Add-ADGroupMember $Group $user }
PowerShellCorpus/GithubGist/mortenya_ecd7f4aa55d9abab6a45_raw_77b8ad36567e6e60484b6cd76545e0550acb1b2b_Get-MappedDrives.ps1
mortenya_ecd7f4aa55d9abab6a45_raw_77b8ad36567e6e60484b6cd76545e0550acb1b2b_Get-MappedDrives.ps1
function Get-MappedDrives { <# .Synopsis Returns the Mapped Drives on the system .DESCRIPTION This function uses WMI to query computers on the network and return the mapped drives, not local drives. If no user is logged on there will likely be an error about RPC server not available. .PARAMETER ComputerName The name of the system(s) you want to check .EXAMPLE Get-MappedDrives Get-MappedDrives system1 Get-MappedDrives -ComputerName system1,system2 -FileLoc "c:\myfile.txt" Get-ADComputer -Filter * -SearchBase "OU=computers,DC=contoso,DC=net" | select -ExpandProperty Name | Get-MappedDrives (Get-ADComputer -Filter * -SearchBase "OU=computers,DC=contoso,DC=net").Name | Get-MappedDrives -ToFile #> [CmdletBinding()] Param ( [parameter( Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage='The name of the system(s) you want to check. Leave blank for local system.')] [string[]]$Name=$env:COMPUTERNAME, [parameter( HelpMessage='Location to save the ouput files, defaut: C:\PSResults\')] [string]$FileLoc="$env:SystemDrive\PSResults", [parameter( HelpMessage='Use this flag if you want to save the results to a file')] [switch]$ToFile ) Begin { if ($ToFile) { if (!(Test-Path $FileLoc)) { # Check if we have an output directory, if not, create one New-Item -Path $FileLoc -ItemType Directory | Out-Null } } $err = @() } Process { if ($ToFile) { $file = "$FileLoc\DriveMaps.txt" foreach ($n in $Name) { $n | FT | Out-File -Append $file try { Get-WmiObject Win32_MappedLogicalDisk -ComputerName $n -ErrorAction Stop | FT @{Label="Drive Letter";Expression={$_.Name}},@{Label="Drive Path";Expression={$_.ProviderName}} | Out-File -Append $file } catch { Add-Content -Path $file -Value "Could not connect to the system" } } } else { try { Get-WmiObject Win32_MappedLogicalDisk -ComputerName $Name -ErrorAction Stop | FT @{Label="Drive Letter";Expression={$_.Name}},@{Label="Drive Path";Expression={$_.ProviderName}},@{Label="Computer";Expression={$_.SystemName}} } catch { $err += $Name } } } End { if ($ToFile) { if (!($err[0] -eq $null)) { Write-Warning "Could not connect to some systems" } } else { if (!($err[0] -eq $null)) { Write-Host "Could not connect to the following systems:" $err } } } }
PowerShellCorpus/GithubGist/alienone_a42644cee90c244296d2_raw_90a1b4851394ea17d64059de72102bc7ad25cd57_connector_inventory.ps1
alienone_a42644cee90c244296d2_raw_90a1b4851394ea17d64059de72102bc7ad25cd57_connector_inventory.ps1
# Global Variables $LOGPATH = "\\nicsrv10\network\InfoSec\SIM\SCCM Custom Code for Agents\" $PROCESSCSV = $LOGPATH + "connector_state.csv" Function GetComputerStats{ <# Description: Cull Memory, CPU, and Disk statistics Input: String object Output: Hash object #> param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNull()] [string[]]$ComputerName ) process { foreach ($computername in $ComputerName) { $average = Get-WmiObject win32_processor -computername $computername| Measure-Object -property LoadPercentage -Average | Foreach {$_.Average} $memory = Get-WmiObject win32_operatingsystem -ComputerName $computername| Foreach {"{0:N2}" -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize)} $free = Get-WmiObject Win32_Volume -ComputerName $computername -Filter "DriveLetter = 'E:'" | Foreach {"{0:N2}" -f (($_.FreeSpace / $_.Capacity)*100)} new-object psobject -prop @{ ComputerName = $computername AverageCpu = $average MemoryUsage = $memory PercentFree = $free } } } } Function CheckRemoteConnectorState{ <# Description: Cull ArcSight Smart Connector/s state and attributes Input: CSV file Output: Hash obj to CSV #> param([string[]]$ComputerNameCSV) $count = 0 $timestamp = $((get-date).ToString("yyyyMMddThhmmss")) $uuid = Get-Random -minimum 1 -maximum 9999 $username = "DOMAIN\USERNAME" $secure_file = "C:\Temp\securestring.txt" $server_array = Import-Csv $ComputerNameCSV 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.ComputerName) { $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[0].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 $stats = Invoke-Command -Session $ps_session -ScriptBlock ${function:GetComputerStats} -ArgumentList $server $cpu_load = $stats.AverageCpu.ToString() + "%" $mem_load = $stats.PercentFree.ToString() + "%" $disk_free = $stats.MemoryUsage.ToString() + "%" #$drive_mapped = "Z" #$drive_path = “\\nicsrv10\network\InfoSec\SIM\SCCM Custom Code for Agents\AGENTPROPERTIES\” #Invoke-Command -Session $ps_session -ScriptBlock {New-PSDrive –Name "Z" –PSProvider FileSystem –Root “\\nicsrv10\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; CpuLoad = $cpu_load; MemLoad = $mem_load; ` DiskFree = $disk_free; 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{ $ComputerNameCSV = "C:\Temp\systems.csv" CheckRemoteConnectorState $ComputerNameCSV } MainFunction