2011-07-13 32 views
2

在我的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 
} 

回答

1

我這樣做的方式,首先列舉強制性的參數,然後初始化它們與$空瓦爾。所以沒有更多的交互和錯誤拋出。

0

簡單的解決方案,不要提示。我覺得你應該總是提示(通過使用必須的參數),或者在執行命令期間不要提示。如果您沒有足夠的信息,請輸入錯誤。如果您的命令被交互使用,用戶可以重新運行正確的信息。

相關問題