Reputation: 69
I ran into a strange behavior while creating an 'interactive' PS script. When started, the script needs information that is requested from the user. I'm using regex to evaluate the result, but one of them just fails:
$a = ""
while (!$a)
{
Write-Host "`nSome text to instruct the user:"
$Global:a = Read-Host
if($a -notmatch "a1[a-z,A-Z]{6}$")
{
Write-Host "no match!"
}
else {Write-Host "match"}
}
The program waits for a string that begins with 'a1' followed by 6 letters.
When I run this snippet from ISE it works as it should. Providing with the test value a1szvite it returns 'match', nevertheless when I save this as a stand alone script and run it in a normal PowerShell windows it returns 'no match!', and keeps asking for another value which indicates that $a
is not written with the data for some reason.
All the other regexes work like a charm I'm a bit confused as to what is the matter here. How could the same lines of code with the same feeding value return a different result?
I really think that this is some little mistake from me, I just don't recognized where it is.
Thanks in advance!
Upvotes: 0
Views: 256
Reputation: 46730
I have tested this and get the same results as you. To help explain my findings I added the following lines to your script.
write-host "$a" -ForegroundColor Yellow
write-host "$Global:a" -ForegroundColor Red
$global:a
and $a
are different variables when the script is being run outside of the ISE. As Frode F. mentions in comments the script has its own scope so $a
is local to the script. The line where you gather used input you are defining another variable in the global scope called $a
When I run your script outside of ISE I only get the red text which tells me your -notmatch
is checking against the original null value of $a
. Which proves the scope issue.
Remove to scope modifier off the line $Global:a = Read-Host
and change it to just $a = Read-Host
. This way all line are referencing the same variable.
Side note: I would update your regex string to ^a1[a-z]{6}$
the match operators and most others are not case sensitive so that will match upper and lowercase alike. Also you mention that the string has to start with a1 so using the start of line anchor would enforce that.
Upvotes: 2