在我的powershell腳本中,我調用了一個cmdlet(稱「連接數據庫」)。如果該cmdlet需要額外的參數,它會提示用戶提供這些值(例如,「Connect-Database」無法從註冊表中獲取憑據,因此它會在Powershell控制檯上提示「用戶名」「密碼」,並希望用戶給出值)。Powershell - 如何在Powershell腳本中以非交互方式調用cmdlet?
我查看了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
}