2010-08-12 73 views
9

我有一個用PowerShell和SMO恢復數據庫的腳本。現在我知道我可以將事件處理程序傳遞給還原對象上的PercentComplete並在發生還原時獲取還原的進度。問題是我不知道如何創建一個事件處理程序,並在PowerShell中傳遞一個函數?我可以在C#使用PowerShell和SMO恢復數據庫時的顯示進度

restore.PercentComplete += new PercentCompleteEventHandler(restore_PercentComplete); 

static void restore_PercentComplete(object sender, PercentCompleteEventArgs e) 
{ 
    System.Console.WriteLine("{0}", e.Percent); 
} 

任何幫助,將不勝感激。

謝謝。

回答

16

經過一番深入的搜索後,我終於在文檔中找到它。要添加事件處理程序,您需要執行以下操作:

導入相關的程序集;

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SmoExtended') | out-null 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.ConnectionInfo') | out-null 

現在要創建事件處理程序,您需要使用內聯函數聲明它;

$percentEventHandler = [Microsoft.SqlServer.Management.Smo.PercentCompleteEventHandler] { Write-Host "Restored " $_.Percent "%" } 
$completedEventHandler = [Microsoft.SqlServer.Management.Common.ServerMessageEventHandler] { Write-Host "Database " $databasename " Created Successfuly!" } 

現在最後一步是將事件處理程序添加到您正在使用的對象中。通常在C#中,您只需執行以下操作;

restore.PercentComplete += new PercentCompleteEventHandler(restore_PercentComplete); 
restore.Complete += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(restore_Complete); 

這在PowerShell腳本中不起作用,您需要做的是使用生成的函數添加事件。函數名是帶有「add_」的EventHandlerName,並附加到它的開頭,就像這樣;

$dbRestore.add_PercentComplete($percentEventHandler) 
$dbRestore.add_Complete($completedEventHandler) 

希望這可以幫助其他人試圖做到這一點!

+1

好的工作:)我猜這是不需要在分配給處理程序時強制腳本塊。 – stej 2010-08-12 19:40:24

+2

您可以使用Write-Progress而不是Write-Host。 – JasonMArcher 2010-08-13 01:07:55

+0

感謝您添加此詳細信息。在我通過其他例子回顧時非常有幫助 – SheldonH 2017-01-05 16:15:40

1

您可以在v1 powershell - http://pseventing.codeplex.com中使用pseventing來實現異步樣式。隨時檢查進度,而不是等待。 v2 powershell有它自己的事件。

我包含一個腳本來完成你所說的內容,除了以背景方式。

-Oisin