0

Having some string trouble, I can get the computer name using $env:computerName and it returns something like ABC1211. I am guessing that the ABC1211 is an object and I want to do a search. I want to search this for the characters ABC and then I need to do some other things with certs. I am having problem searching for the ABC.

I tried:

[string[]]$test = $env:computerName 

to turn it into a string and then do a search within $test by:

if ($test.contains(("DEF")) {
    Write-Host "Yeah" 
}
else {
    Write-Host "NO"
} 

but its not working. Am I missing something? I am guessing this is really simple, but I'm just not getting it.

2 Answers 2

3

$env:computerName is already a string. There is no need to cast it to [string[]]. Just call the .contains method on the variable directly:

if ($env:computerName.contains("ABC")) {
    Write-Host "Yeah" 
}
else {
    Write-Host "NO"
}

Incidentally, casting a variable to [string[]] makes an array of strings, not a single string:

PS > [string[]]$test = $env:computerName     
PS > $test.GetType()

IsPublic IsSerial Name                                     BaseType                 
-------- -------- ----                                     --------                 
True     True     String[]                                 System.Array             


PS >

So, $test was actually of the form ($env:computerName,) and you were using Array.Contains instead of String.Contains.

To cast to a string, you would use just [string]:

[string]$test = $env:computerName

But as I said above, this is unnecessary since $env:computerName is already a string.

Sign up to request clarification or add additional context in comments.

Comments

0

Ok I figured it out...was a lot more simple than I thought. Here's the answer: -match

I just had to use that instead of .contains or -like also I don't need to change the object into a string.

1 Comment

-match uses Regex to search for a pattern. You are only trying to search for static text however, which means it is not necessary (and somewhat inefficient). .contains should work fine if you use it as I demonstrated in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.