我正在尝试创建一个函数,用户必须提供一个不能包含空字符串的文件名。除此之外,字符串不能包含点。当我运行这个函数时,我在输入“test”时会继续循环。知道为什么?
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
}
}
编辑:
在相关的说明:
do {
$exportInvoke = Read-Host "Do you want to export this output to a new .txt file? [Y/N]"
} until ($exportInvoke -eq "Y" -or "N")
当我使用这些代码行时,我可以简单地按Enter键以绕过Read-Host
。当我用简单的"Y" -or "N"
替换"Y"
时,它没有。知道为什么会这样吗?
-match
运算符检查正则表达式,所以这:
$script:newLog -match ".*"
正在测试文件名是否包含任何字符串除了换行符(.
)0次或更多次(*
)。这种情况总是如此,从而产生无限循环。
如果要测试文字点,则必须将其转义:
$script:newLog -match '\.'
至于你的另一个问题,你误解了逻辑和比较运算符的工作原理。 $exportInvoke -eq "Y" -or "N"
并不意味着$exportInvoke -eq ("Y" -or "N")
,即变量等于“Y”或“N”。这意味着($exportInvoke -eq "Y") -or ("N")
。由于表达式"N"
不是evaluate to zero,PowerShell将其解释为$true
,因此您的条件变为($exportInvoke -eq "Y") -or $true
,这始终是真的。您需要将条件更改为:
$exportInvoke -eq "Y" -or $exportInvoke -eq "N"
用它来测试你的输入:
!($script:newLog.contains('.')) -and !([String]::IsNullOrEmpty($script:newLog)) -and !([String]::IsNullOrWhiteSpace($script:newLog))
你的正则表达式(-match ".*"
基本上匹配所有东西。