Powershell assert pipeline returns not an array

Viewed 84

Background:

I'm trying to filter a specific GIT branch from my local branches. Therefore I'm using git branch --all.

Powershell specific question:

I'm performing pipeline filtering via Where-Object and want to ensure that only one object and not an array is returned from the pipeline.

I've e.g. :

  $branch = Invoke-Expression "git branch --all" | % { $_.Trim('*').Trim() | ? { $_ -match "MySpecificBranchRegex" }

If I mess up my specific filter regex $branch might be an array and not a string.

Is there an elegant way to ensure only one string is returned. Possible solutions I don't like:

  • Call Select-Object -First 1 at the end of the pipeline
  • Perform if '$arr.GetType().BaseType.Name -eq "Array"`

Thx.

2 Answers

Well Select-Object -First 1 is the elegant solution imho, but you could turn it around by forcing it to always return an array:

$branches = @(Invoke-Expression "git branch --all" | % { $_.Trim('*').Trim() | ? { $_ -match "MySpecificBranchRegex" })

if ($branches.Count -ne 1)
{
    throw "Something went wrong..."
}
$result = git branch --all | where { $_ -match 'MySpecificBranchRegex' } 
$result.count

I wouldn't be above using findstr (even with quotes) instead of where. /i is case insensitive.

$result = git branch --all | findstr /i MySpecificBranchRegex
Related