0

I have a Powershell script returning data from an API which works fine as long as I only attempt to return one $device.realm, but I need multiple realms. I'm a newb to PS. Any help here is really appreciated

Here is my code $Output = forEach ($device in $devices) {

    if ($device.realmName -eq 'Archive') {
    [PSCustomObject]@{
        HostName = $device.name
        IPAddress = $device.primaryInterfaceAddress
        Realm = $device.realmName
        SerialNumbers = (($device.dynamicFields  | where { $_.name -EQ "serial number" } | Select-Object -ExpandProperty values) -join "," | out-string).TrimEnd()
        }| Select-Object Hostname,IPAddress,Realm,SerialNumbers | Export-csv C:\temp\Archive.csv  -notype -Append 
        
    }

I need to return multiple $device.realms as in if ($device.realmName -eq 'Archive' -and 'Default' -and 'Farms')

Once I add the additional -and's every realm is returned instead of just the one's I need to return.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
lito
  • 3
  • 1

1 Answers1

0

I believe the issue at hand here is that the statement within the If block that you're querying as ($device.realmName -eq 'Archive' -and 'Default' -and 'Farms')
is not, when evaluated logically "Evaluate true if the device realmname is Archive, Default, or Farms." It is evaluating whether device.realmname is archive, and then just interpreting the two -ands in your example as true, as they are not querying a comparison, but just the presence of a non-null string. Not sure what is leading it to return everything, I'd have to see some more direct examples to be sure, but in my experience that is most common when you include an -or in a comparison pointing to a nonnull string, which will make the entire statement true.

What I would suggest is as follows: Use the regex operators built in to powershell for cases like this. You could use

if($device.realmname -eq 'Archive' -or $Device.realmname -eq 'farm' -or $device.realmname -eq 'Default')

which would, I believe, return what you are looking for, but I find it a bit complex. More complicated queries on a single property, I find, are easiest to do via -match, through something invoking the -match operator, which allows you to build a regex query statement that can include Or's or And's with a bit simpler of a synatax, like so:

if($Device.realmName -match 'Archive|Farm|Default')
Chakani
  • 101
  • 4