【发布时间】:2022-01-06 10:58:32
【问题描述】:
在我的 powershell 脚本中,我调用了一个 cmdlet(比如“连接数据库”)。如果 cmdlet 需要其他参数,它会提示用户提供这些值(例如,“Connect-Database”无法从注册表获取凭据,因此它会在 Powershell 控制台上提示输入“用户名”“密码”并希望用户提供值)。
我查看了 Powershell cmdlet 的代码。我发现它使用“CommandInvocationIntrinsics”来提示用户(使用“NewScriptBlock”,然后使用“CommandInvocationIntrinsics”的“Invoke”方法)。
由于我是从 Powershell 脚本调用此 cmdlet,因此我希望每当出现此类提示时,它都会被抑制并引发异常。
代码是这样的 -
try
{
$db = Connect-Database <databasename>
#if username / password is prompted, it should be converted into error. But it should not be shown in powershell console.
if($Error.Count > 0)
{
throw $Error[0]
}
}
catch
{
#do something
}
【问题讨论】:
标签: powershell