Why can’t i call Contains method from my array?


Arrrg!I am running into what i feel is a dumb issue with a simple script i’m writing in powershell. I am invoking a sql command that is calling a stored proc, with the results i put it a array. The results look something like this:

What i’m trying to do is if($s.Contains("Expired")) , report failed. Simple…? 🙁 Problem i’m running into is it looks like Contains method is not being loaded as i get an error like this:

Method invocation failed because [System.Object[]] doesn’t contain a method named ‘Contains’. At line:1 char:12
+ $s.Contains <<<< (“Expired”)
+ CategoryInfo : InvalidOperation: (Contains:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

So, what can i do to stop powershell from unrolling it to string? Actual ps script below –


The reason you see the method is Get-Members is powershell is trying to be helpful and unrolling the collection. If you have an array with multiple types of items, it shows you the members for each type (like if you ‘ls’ (Get-ChildItem) and there are FileInfos and DirectoryInfos in the directory you are in, and you pipe ls | gm, it will show you members of FileInfos and also another group of members of DirectoryInfos):

What I usually do, to make sure I am not looking at unrolled members, is try “$s.GetType().Name” first to see what I am dealing with. In your case, it’s clearly and array, since you initialized it like “$s = @(Invo” (the @ = it’s an array.)

To find out if an array contains an item, you can use the -contains operator:

I think you’ve got an array of strings, so you can use a string literal, like:

But if the expired isn’t an exact match (you were looking for an element that contains expired, like “Connection Expired 1/1/2010”) you need to find matches and check the count, I think:

In this case, there is only one match, so powershell unrolled it to a string. Jerk. If there are more than 1 matches, however:

Now it’s an array.

Luckily, both string and array have a length property:

So you can check the length of your results that contain “Expired” to see if there are any expired’s:

(maybe someone has a better way to check if a collection contains an item that satisifies some predicate (like LINQ’s Any)?)


Why can’t i call Contains method from my array? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply