BeowulfNode42 BeowulfNode42 - 3 months ago 63
PowerShell Question

powershell Test-Path is not recognized as a cmdlet

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?

Answer

try with qualifier:

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