The ISE isn't the best place to test a script. It's okay for composing and debugging, but you have to keep in mind that the ISE "remembers" variable and their values from previous executions of the script. It also uses your credentials when accessing things such as file shares. It's a good idea to start a new PowerShell session to run the script each time when you want to verify that it's able to run by itself in a clean session.
You probably don't have permission to access either the file share or its subdirectory. Without permission, the Test-Path will fail and with it the While loop (which will receive a $null value), causing the script to end.
Try using this sort of code:
Try{
# just see if you have access to the directory
if (-NOT (Test-Path \\file.server.test\file\data -PathType Container -ErrorAction STOP)){
Throw "No error was detected, but you do not have access to the directory or the directory does not exist"
}
}
Catch{
# don't use Write-Host here because you may be running in an environment (e.g. Scheduled Task) that has no user profile
"Unable to access file share or a sub directory" | Out-File <some log file name here> -Append
$_ | Out-File <some log file name here> -Append
Exit # or try to recover
}
Try{
if (Test-Path '\\file.server.test\file\data\test.txt' -ErrorAction STOP){ # verify existence of the file
While ((Test-Path '\\file.server.test\file\data\test.txt' -ErrorAction SilentlyContinue))
{
# endless loop, when the file will be there, it will continue
Start-Sleep -Milliseconds 500 # avoid large CPU consumption and network traffic -- adjust time as needed
}
"The file has been removed from the directory after being detected at least once. " | Out-File <some log file name here> -Append
}
else {
"No error was detected, but the file was not found in the directory" | Out-File <some log file name here> -Append
}
}
Catch{
"Unable to access the file" | Out-File <some log file name here> -Append
$_ | Out-File <some log file name here> -Append
Exit # or try to recover
}
EDIT: added additional checking and stopped True/False emitted in success stream.