PowerShell:Test-Path未被识别为cmdlet

3
作为我之前提出的问题 powershell if-else does not follow either branch 的跟进,我发现了另一个奇怪的情况。我有一个脚本,每天作为计划任务运行一次。问题只会在作为计划任务运行时出现(从命令提示符、IDE或PowerShell窗口中永远不会出现),即使是在某些天也只会出现一次。相关代码如下: $target_dir = "\\server\path\" $tmpStatus = "init" $err = $false try { $tmpStatus = Test-Path ( $target_dir + "receivals.tmp") } catch { $tmpStatus = $error | foreach { $_.Exception } $err = $true }
有些时候,$tmpStatus会报告以下问题:
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)
然而,在同一次运行的同一脚本中,稍后再次使用Test-Path时,它每次都可以正常工作。为什么Test-Path不是有效的命令?

今天开始在我的构建系统中出现了这个问题。 - Dave Neeley
@ranomore,你的程序是作为定时任务、交互式或其他方式运行的吗?你能够可靠地重现这个错误吗? - BeowulfNode42
真希望早点看到你的留言。我重新启动了出现问题的机器,问题消失了。但它是通过TeamCity在非交互式进程中运行的。我尝试了各种脚本重构,但错误仍然存在。 - Dave Neeley
我的问题似乎与服务器重启无关。尽管重启是在下一次脚本计划的17小时之前。 - BeowulfNode42
2个回答

2

尝试使用限定符:

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

1
好的,这已经运行了一个多月了,而之前的成功记录最长只有一周。你认为这个方法为什么有效,而仅使用“Test-Path”则不行呢? - BeowulfNode42
无法加载模块'!Microsoft.PowerShell.Management'。 - pf12345678910

1
我将这句话翻译成中文:"

我把这个加到了我的构建脚本里。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接