Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: Convert an object to a string

Tags:

powershell

We have Exchange Info Stores that begin with UsersA-B, UsersC-D, etc., and then some that are outside that naming convention.

$allIS = Get-MailboxDatabase |
             Where { $_.name -notlike "*Users*" } |
             Select Identity

I'll lookup a current user's info store, and then try to do a comparison on the $allIS array. If it matches, do some action.

When I output the value of $allIS[0] for instance, it returns @{Identity=MSCCR\CEO\CEO}.

I'd like to throw those converted strings into a different array, and then do the comparison. This would be to have a dynamic list of information stores to compare against. But maybe this isn't the best, most efficient way. What would be the best way to try to do this comparison, as right now I'm comparing apples to oranges here?

like image 382
cluckinchicken Avatar asked Jun 13 '12 16:06

cluckinchicken


Video Answer


2 Answers

It is hard to tell if that could be optimized without seeing the second part...

But it's pretty easy to get a flat array of identities. Either use -ExpandProperty on select, or use foreach { $_.Identity } instead of select:

$allIS = Get-MailboxDatabase | ? { $_.name -notlike "*Users*" } | select -expand Identity
$allIS = Get-MailboxDatabase | ? { $_.Name -notlike '*Users*' | foreach { $_.Identity}
like image 181
BartekB Avatar answered Oct 22 '22 08:10

BartekB


The PowerShelly way

$isNames = @()
$allIS = Get-MailboxDatabase | 
    Where { $_.name -notlike "*Users*" } | 
    Select Identity | 
    %{ $isNames += $_.name }

It pipes the output to a foreach loop using % instead.

A more procedural way

$isNames = @()

foreach ($is in $allIS)
{
    $isNames += $is.identity
}

That gives you a simple array of only the names of the information stores, as strings instead of objects.

like image 27
Formica Avatar answered Oct 22 '22 10:10

Formica