I have the powershell code
$target_dir = "\\server\share\"
$DelTmpStatus = "init value"
if ( Test-Path ( $target_dir + "receivals.tmp") )
{
del ( $target_dir + "receivals.tmp")
$DelTmpStatus = "Present and delete status $?"
} else {
$DelTmpStatus = "NA"
}
and sometimes it makes it through this section with $DelTmpStatus still set to "init value".
How can the if-else structure not follow either path? Does the if-else structure in powershell not do anything when the if function is given an error instead of true or false?
$PSVersionTable.psversion is 3.0
Edit: I never have any errors or this problem when I run it myself, either fully or step-by-step. But sometimes the scheduled job will run and $DelTmpStatus will still be "init value" I imagine it happens when the \\server\share\ path is unavailable due to server in low power mode overnight taking too long to respond and the test-path function times out. Though I can't be sure if that is the cause or not.
Edit: the results of doing the tests
- using a non existent server for
$target_dirmakes it follow the else path and sets$DelTmpStatusto "NA" - using an invalid path like
$target_dir = "C:\..\..\invalid\"results in test-path writing an error to stderr and returning true (not ideal but whatever), making the program flow down the attempt to delete the file (again there's an error) then it sets$DelTmpStatusto "Present and delete status False". This is not a particularly helpful thing to do but at least the code in the if-else statement is executed.
$ErrorActionPreference = 'Stop'and thedelis throwing an exception and so the setting of$DelTmpStatusis being skipped over. Are you logging your exceptions? - dan-gph$ErrorActionPreferenceit is set to its default of continue. If it was set to stop, wouldn't that stop the entire script? If you haven't guessed the code shown is just an excerpt from the full script that continues to run and generates a newreceivals.tmpfile. I'm not currently logging exceptions. - BeowulfNode42catch. I don't have an explanation. You could test your script with some non-existent server ($target_dir = "\\blah\share\") and see what happens. - dan-gph