Rex M
Rex M

Reputation: 144162

Set powershell variable if pipeline is empty

I've currently got this pipeline:

Get-R53HostedZones | where {$_.Name -eq 'myval'} | %{ Get-R53ResourceRecordSet -HostedZoneId $_.Id } | %{ $_.ResourceRecordSets | where {$_.Name.StartsWith("myval")} }

This works fine, it gives me the results I expect. Where I'm stumped is what I need to do next... I need to set a variable to true if this produces one or more results, and false if it's empty.

Upvotes: 0

Views: 2601

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

Assign it to a variable, and check it with an if statement:

$MyRecords = @(Get-R53HostedZones | where {$_.Name -eq 'myval'} | %{ Get-R53ResourceRecordSet -HostedZoneId $_.Id } | %{ $_.ResourceRecordSets | where {$_.Name.StartsWith("myval")} })
if($MyRecords.Count -gt 0) { $true } else { $false }

The array subexpression operator (@()) makes sure that an array is returned, even if the result is only a single item. Otherwise the Count property won't exist fail in earlier versions of PowerShell

You can also do:

if ($MyRecords) { $true } else { $false }

But the first method makes it more clear what you're actually testing and will also work in situations where an expression might return the value $false

Upvotes: 3

Related Questions