Reputation:
I am trying to create a function in which a user has to give a filename that can not containt an empty string. Besides that, the string can not contain a dot. When I run this function, I keep looping when I enter "test" for example. Any idea as to why?
function Export-Output {
do {
$exportInvoke = Read-Host "Do you want to export this output to a new .txt file? [Y/N]"
} until ($exportInvoke -eq "Y" -or "N")
if ($exportInvoke -eq "Y") {
do {
$script:newLog = Read-Host "Please enter a filename! (Exclude the extension)"
if ($script:newLog.Length -lt 1 -or $script:newLog -match ".*") {
Write-Host "Wrong input!" -for red
}
} while ($script:newLog.Length -lt 1 -or $script:newLog -match ".*")
ni "$script:workingDirectory\$script:newLog.txt" -Type file -Value $exportValue | Out-Null
}
}
EDIT:
On a related note:
do {
$exportInvoke = Read-Host "Do you want to export this output to a new .txt file? [Y/N]"
} until ($exportInvoke -eq "Y" -or "N")
When I use these lines of code I can simply hit enter to circumvent the Read-Host
. When I replace "Y" -or "N"
with simply "Y"
it does not. Any idea as to why this is happening?
Upvotes: 0
Views: 86
Reputation: 200213
The -match
operator checks against a regular expression, so this:
$script:newLog -match ".*"
is testing if the filename contains any charachter except newline (.
) 0 or more times (*
). This condition will always be true, thus creating an infinite loop.
If you want to test for a literal dot, you must escape it:
$script:newLog -match '\.'
As for your other question, you're misunderstanding how logical and comparison operators work. $exportInvoke -eq "Y" -or "N"
does not mean $exportInvoke -eq ("Y" -or "N")
, i.e. variable equals either "Y" or "N". It means ($exportInvoke -eq "Y") -or ("N")
. Since the expression "N"
does not evaluate to zero, PowerShell interprets it as $true
, so your condition becomes ($exportInvoke -eq "Y") -or $true
, which is always true. You need to change the condition to this:
$exportInvoke -eq "Y" -or $exportInvoke -eq "N"
Upvotes: 2
Reputation: 28154
Use this to test your input:
!($script:newLog.contains('.')) -and !([String]::IsNullOrEmpty($script:newLog)) -and !([String]::IsNullOrWhiteSpace($script:newLog))
Your regular expression (-match ".*"
is essentially matching on everything.
Upvotes: 1