Question : Powershell -contains

I am struggling to figure out why the -contains options when searching through an array works for one array and not for another?

I'm trying to use the neat method here: http://technet.microsoft.com/en-us/library/ee692798.aspx

The Code:

1:
2:
3:
4:
5:
6:
7:
8:
$arrColours = "Black","Blue","Green"
if ($arrColours -contains "Black"){Write-Host "True"}

$arrServices = Get-Service | Select-Object name

$arrservices[0] #show first element

if ($arrServices -contains "Alerter"){Write-Host "True"}else{Write-Host "False"}


The results:

True

Name                                                                                          
----                                                                                          
Alerter  
                                                                                   
False


So, it finds the colour, but when I try to load services, and see if a certain service exists in the array it does not work?

I think it has something to do with the type of array, but I don't know how to convert the array to an array of strings?

Any help would be great,

Thanks

Shaun

Answer : Powershell -contains


It's because $arrServices is an array of objects and you can't implicitly test the name property.

You can get around that when generating the list, returning only the property value. Then you can use contains. Otherwise you're stuck with Where-Object.

Chris
1:
2:
3:
4:
5:
$arrServices = Get-Service | ForEach-Object { $_.Name }

$arrServices[0] # This is a String

if ($arrServices -contains "Alerter"){Write-Host "True"}else{Write-Host "False"}
Random Solutions  
 
programming4us programming4us