powershell Test-Path is not recognized as a cmdlet

此生再无相见时 提交于 2019-12-13 16:25:52

问题


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?


回答1:


try with qualifier:

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



回答2:


I added this to my build scripts.

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


来源:https://stackoverflow.com/questions/22188829/powershell-test-path-is-not-recognized-as-a-cmdlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!