0

I'm struggling with passing objects in a pipeline. I have been going round the problem converting them to strings, but that cannot be the most efficient way of doing things.

$mapi = (Get-CASMailbox -Identity $user | fl mapiEnabled | Out-String ).Split(':')[-1]
if ($mapi -match "True") {
   Set-CASMailbox -Identity $User -MAPIEnabled $false
}   

I really want to directly access the bool returned instead of converting it to string

Similarly, I have been using below to do a for loop:

$groups = (Get-DistributionGroup | fl name | Out-String -Stream ).Replace("Name : ", "")
foreach ($group in $groups) {
    echo $group
}

Both examples are from Exchange Online, below one more universal:

if (((Get-NetIPInterface -InterfaceAlias $adapters -AddressFamily Ipv4 | fl dhcp | Out-String -Stream ).Trim() -ne "").Replace("Dhcp : ","") -match "Disabled") {
    echo disabled
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
piorrun
  • 3
  • 1
  • 3
    Stop using `fl` (use `select` instead, or just... nothing) and all your problems will disappear :) – Mathias R. Jessen Oct 17 '19 at 15:20
  • 5
    Why not just use `(Get-CASMailbox -Identity $user).mapiEnabled`? You can use the dereferences operator (`.`) to access the value of an object's property. `Get-CASMailbox` returns those objects. Or just use `Select-Object` as @MathiasR.Jessen has suggested in lieu of `Format-List`. – AdminOfThings Oct 17 '19 at 15:22

1 Answers1

4

I just wanted to take a second to see if I can help you understand what is happening in the pipeline and why @mathiasR.Jessen and @AdminOfThings comments will help you.

$mapi = (Get-CASMailbox -Identity $user | fl mapiEnabled | Out-String ).Split(':')[-1]

Breaking down that this line of code does:

Get-CASMailbox is going to return an object with multiple properties. Format-List (fl) is still going to return an object, but now it has been formatted so it's less malleable. Out-String is going to transform that formatted list into a single string. Putting those commands in parentheses runs them and allows you to execute a method on the resulting string object.

Using the same concept, we can use the parenthesis to execute the Get-CASMailbox command and get the singular property you are looking for:

$mapi = (Get-CASMailbox -Identity $user).mapiEnabled

Now we have set $mapi to the value of the mapiEnabled property returned by the command.

Hope this helps!

mklement0
  • 382,024
  • 64
  • 607
  • 775
Scott Heath
  • 830
  • 7
  • 5
  • 1
    +1, but re "still going to return an object": it returns _multiple, completely unrelated_ objects whose sole purpose is to provide _formatting instructions_ to PowerShell's output-formatting system - see https://stackoverflow.com/a/55174715/45375. In short: only ever use `Format-*` cmdlets to format data _for display_, never for subsequent _programmatic processing_. – mklement0 Oct 17 '19 at 16:02