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

Time:02-25

I'm having an issue with a portion of a function I'm trying to write (it is stuck in the loop, Read-Host portion indefinitely).

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: "
       }

Input string for $pub_file = "ABCD" The file in /userpub/ is named pubtest.txt

If I type in pubtest.txt or Exit or even ABCD, it still just keeps prompting for input.

ANSWER with thanks to MathiasR.Jessen in the comments:

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: "
           }

CodePudding user response:

Make the following changes:

  • Remove the trailing / from the file path
  • Change the -or to an -and
    • Remember, you only want to keep prompting when the file name doesn't exists and the user didn't input Exit
  • Change the = to -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: "
}

One final tweak you might want to make: Assuming that you never want to test for a file named exit, make sure you test for that condition first, but flip the loop around so you prompt the user before checking the condition:

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))
  • Related