我有很多 powershell 脚本,所以我用几个 cmdlet 创建了一个自定义日志记录 Powershell 模块。问题是我们无法让所有用户下载自定义模块并将其放入他们的 PSModulePath 中。
理想情况下,如果找不到 cmdlet,我希望脚本以静默方式继续运行并且不显示任何错误,但我还没有找到一个好的方法。现在我们收到这样的消息:
C:> foo-bar
foo-bar : The term 'foo-bar' is not recognized as the name of a cmdlet, function, script file, or operable program...
Run Code Online (Sandbox Code Playgroud)
设置 ErrorActionPreference 将抑制消息,但它也会抑制所有其他不需要的错误消息。
我可以在每个脚本中编写一个自定义函数,在调用自定义 cmdlet 之前检查模块是否正在加载,但似乎应该有更好的方法来做到这一点。
对于给定的 cmdlet foo-bar,您可以在脚本开头执行以下操作:
if (-not (Get-Command foo-bar -ErrorAction Ignore)) {
# Define a dummy function that will be a no-op when invoked.
function foo-bar { }
}
Run Code Online (Sandbox Code Playgroud)
对foo-barthen 的所有后续调用要么调用实际的 cmdlet(如果可用),要么调用虚拟函数,从而导致安静的无操作。
| 归档时间: |
|
| 查看次数: |
234 次 |
| 最近记录: |