header
header Register : : Login header
header
divider
menuleft
menuright
submenu
left

[August 25th, 2008] Check the home page regarding PowerShell related news from a brand new sponsor: Idera

How do I test to see if variable is an array?
Last Post 17 Nov 2008 05:42 PM by halr9000. 3 Replies.
Printer Friendly
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
MattGUser is Offline
New Member
New Member
Posts:20
Avatar

--
17 Nov 2008 04:52 PM  

I am using Powershell to query WMI objects.  Some objects like Win32_LogicalDisk,  return an array of objects when there is more than 1 drive on a machine.  However,  when there is only 1 drive it apparently it returns the object to the variable and does not make the variable an array.

My question:  How do I test a variable (or returned object) in PS to see if it is an array or not?

 

Thanks,

-MattG

MattGUser is Offline
New Member
New Member
Posts:20
Avatar

--
17 Nov 2008 05:35 PM  

Figured it out:

$srv = gwmi win32_LogicalDisk -computer $name -filter "DriveType = 3"
   
        if ($srv.Count -gt 1){
            $srv[0]| select $field1,$field2,$field3,$field4,$field5
            $srv[1]| select $field1,$field6,$field7,$field8,$field9
            $srv[2]| select $field1,$field10,$field11,$field12,$field13
            $srv[3]| select $field1,$field14,$field15,$field16,$field17
            $srv[4]| select $field1,$field18,$field19,$field20,$field21
            } else
            {
            $srv|select $field1,$field2,$field3,$field4,$field5
            }
 }

Thanks,

-MattG

halr9000User is Offline
PowerShell MVP, Site Admin
Basic Member
Basic Member
Posts:334
Avatar

--
17 Nov 2008 05:38 PM  
Your message appears to be formatted very strangely. I'm looking into that. As to your question, you can either a) test it or b) use constructs which will work whether the obj is an array or singleton.

a1) if ( $foo.GetType().BaseType -eq 'array' )
a2) if ( $foo -is [system.array] ) # -isnot is the opposite

b)
$a = get-wmiobject win32_logicaldisk
$a | foreach-object { DoStuff }

Community Director, PowerShellCommunity.org
Co-host, PowerScripting Podcast
Author, TechProsaic
halr9000User is Offline
PowerShell MVP, Site Admin
Basic Member
Basic Member
Posts:334
Avatar

--
17 Nov 2008 05:42 PM  
Well, the Count method doesn't even exist on non-arrays, so you could just say

if ( $foo.count ) { DoStuff }

But I don't think this is the best way to handle the case. There's several options.
Community Director, PowerShellCommunity.org
Co-host, PowerScripting Podcast
Author, TechProsaic
You are not authorized to post a reply.

Active Forums 4.1
right
   
footer Sponsored by Quest Software • SAPIEN Technologies • ShellTools, LLC • Microsoft Windows Server 2008 footer
footer