Powershell (linux) while 循环检查文件是否存在或输入了一个单词

Powershell (linux) while loop to check if a file exists OR a word is typed

我尝试编写的函数的一部分有问题(它卡在循环中,读取主机部分无限期)。

while (!(Test-Path -Path /userpub/$pub_file/ -PathType Leaf) -or ($pub_file = "Exit"))
       {
        [string]$pub_file = Read-Host  "Enter in the correct filename or type Exit to quit: "
       }

$pub_file 的输入字符串 = "ABCD" /userpub/ 中的文件名为 pubtest.txt

如果我输入 pubtest.txtExit 甚至 ABCD,它仍然只是提示输入。

感谢 MathiasR.Jessen 在评论中回答:

while (!(Test-Path -Path /userpub/$pub_file -PathType Leaf) -and ($pub_file -ne 'Exit'))
           {
            [string]$pub_file = Read-Host  "Enter in the correct filename or type Exit to quit: "
           }

进行以下更改:

  • 从文件路径中删除尾随 /
  • -or 更改为 -and
    • 记住,你只想在文件名不存在时一直提示 用户没有输入Exit
  • = 更改为 -ne:
while (!(Test-Path -Path /userpub/$pub_file -PathType Leaf) -and $pub_file -ne "Exit")
{
    [string]$pub_file = Read-Host  "Enter in the correct filename or type Exit to quit: "
}

您可能想要做的最后一个调整:假设您永远不想测试名为 exit 的文件,请确保先测试该条件 ,但是翻转循环,以便在检查条件之前提示用户:

do {
    [string]$pub_file = Read-Host  "Enter in the correct filename or type Exit to quit: "
} while ($pub_file -ne "Exit" -and -not(Test-Path -Path /userpub/$pub_file -PathType Leaf))