DevOpsHandling/New-GitCountryBranches.ps1
function New-GitCountryBranches { Param( [Parameter(Mandatory=$true)] [string] $pullRequestNumber ) Write-Host "Fetching pull request" Invoke-Executable "git fetch origin +refs/pull/$pullRequestNumber/merge" -ErrorMessage "Could not fetch pull request #$pullRequestNumber" Invoke-Executable "git checkout FETCH_HEAD" -ErrorMessage "Could not checkout pull request #$pullRequestNumber" Write-Host "Creating country branches" $countries = Get-EnvironmentKeyValue -KeyName "countries" $branches = Invoke-Executable "git ls-remote" foreach ($country in $countries) { if ($null -ne ( $branches | Where-Object { $_ -like "*/countries/$country"})) { Write-Host "$country branch exists. Deleting branch" Invoke-Executable "git push origin --delete countries/$country" -ErrorMessage "Could not delete branch 'countries/$country'" } Write-Host "Creating Branch countries/$country and pushing to remote" $response = Invoke-Executable "git checkout -b countries/$country" -ErrorMessage "Could not create branch 'countries/$country'" Write-Host $response $response = Invoke-Executable "git push origin countries/$($country):countries/$country" -ErrorMessage "Could not push branch 'countries/$country'" Write-Host $response } Write-Host "Cleaning up local branches" Invoke-Executable "git checkout master" -ErrorMessage "Could not switch to master branch" $localBranches = Invoke-Executable "git branch --list" -ErrorMessage "Could not list local branches" foreach ($country in $countries) { if ($null -ne ($localBranches | Where-Object { $_ -like 'countries/$country'})) { Invoke-Executable "git branch -D countries/$country" -ErrorMessage "could not delete local branch 'countries/$country'" } } Write-Host "Country Branches created" } Export-ModuleMember New-GitCountryBranches function Invoke-Executable { Param( [Parameter(Mandatory, Position = 0, ValueFromPipeline)] [string[]] $Command, [Parameter(Mandatory=$false)] [string] $ErrorMessage ) $oldErrorAction = $ErrorActionPreference $ErrorActionPreference = "Continue" $output = Invoke-Expression "$Command 2>&1" $ErrorActionPreference = $oldErrorAction if ($LASTEXITCODE -ne 0) { if ($ErrorMessage -eq "") { throw $output } else { Write-Error $ErrorMessage throw $output } } $output | ForEach-Object { Write-Output $_.ToString() } } |