DevOpsHandling/New-GitCountryBranches.ps1
function New-GitCountryBranches { Param( [Parameter(Mandatory=$true)] [string] $branchName ) 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" Invoke-Executable "git checkout -b countries/$country" -ErrorMessage "Could not create branch 'countries/$country'" Invoke-Executable "git push origin countries/$country" -ErrorMessage "Could not push branch 'countries/$country'" } Write-Host "Cleaning up local branches" Invoke-Executable "git checkout $branchName" -ErrorMessage "Could not switch back to source branch" $localBranches = git branch 2>&1 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() } } |