2
votes

As a follow up to my question powershell if-else does not follow either branch I've found another odd situation. I have a script that is running as a scheduled task once a day. The problem occurs only when run as a scheduled task (never from a command prompt, ide, or powershell window) and even then only on some days. The relevant code is

$target_dir = "\\server\path\"
$tmpStatus = "init"
$err = $false
try { $tmpStatus = Test-Path ( $target_dir + "receivals.tmp") }
catch
{
    $tmpStatus = $error | foreach { $_.Exception }
    $err = $true
}

Some days $tmpStatus reports the problem

System.Management.Automation.CommandNotFoundException: The term 'Test-Path' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

However, later on in the same script on the same run when I use Test-Path again, it works just fine every time. How can Test-Path not be a valid command?

2
started happening in my build system today.Dave Neeley
@ranomore is yours running as a scheduled task, or interactive or some other way? Can you reproduce the error reliably?BeowulfNode42
Wish I'd seen your note sooner. I rebooted the machine where this had started happening and the problem disappeared. But it was running in a non-interactive process through TeamCity. I tried various refactorings of the script but the error persisted.Dave Neeley
Mine seems unrelated to server reboots. Though the reboot is 17 hours before the next script schedule.BeowulfNode42

2 Answers

1
votes

try with qualifier:

Microsoft.PowerShell.Management\Test-Path ( $target_dir + "receivals.tmp")
1
votes

I added this to my build scripts.

Import-Module "$env:SystemRoot\System32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1"