powershell Test-Path is not recognized as a cmdlet

2019-08-10 06:46发布

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条回答
成全新的幸福
2楼-- · 2019-08-10 07:16

I added this to my build scripts.

Import-Module "$env:SystemRoot\System32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1"
查看更多
倾城 Initia
3楼-- · 2019-08-10 07:18

try with qualifier:

Microsoft.PowerShell.Management\Test-Path ( $target_dir + "receivals.tmp")
查看更多
登录 后发表回答