PowerShell中调用方法的WMI回调

时间:2018-01-08 00:22:25

标签: powershell wmi

我试图在PowerShell v3中的Win32_OfflineFiles缓存上调用Syncronize方法时收到“On Progress”事件(我限制使用更高版本)。根据MSDN文档here,该过程是:

  

要监控进度,请实施WMI事件接收器以进行接收   SWbem.OnProgress事件通知。 strMessage参数   包含使用以下代码编码的文本字符串   以冒号分隔的格式......

收到WMI事件的PowerShell示例here我看不出如何将它们转换为我的用例。

VBScript的示例代码段有效:

Set objCache         = objWMIServices.Get("Win32_OfflineFilesCache=@")
Set objParams        = objCache.Methods_("Synchronize").InParameters.SpawnInstance_
Set objSink          = WScript.CreateObject("WbemScripting.SWbemSink", "SINK_")

objParams.Paths = ItemPaths
objWMIServices.ExecMethodAsync objSink, "Win32_OfflineFilesCache", "Synchronize", objParams, wbemFlagSendStatus

Sub SINK_OnProgress(UpperBound, Current, Message, objContext)
  ' process here
End Sub

Sub SINK_OnCompleted(HResult, objLastError, objContext)
 ' process here
End Sub

虽然我可以看到Register-CimIndication,但是Register-WMIEvent可用于WMI事件,而Register-ObjectEvent用于.NET对象我无法看到示例如何调用WMI方法,因为Register-WMIEvent采用WMI事件类或WMI事件查询。

当前没有回调的PowerShell代码:

 $offlineCache = ([WmiClass]"\\.\root\cimv2:Win32_OfflineFilesCache")
 $offlineCache.Synchronize($filesToSync,$OfflineFilesSyncControlFlagSyncOut+$OfflineFilesSyncControlCrKeepLatest)

1 个答案:

答案 0 :(得分:0)

我使用ManagementOperationObserverInvokeMethodRegister-ObjectEvent

一起解决了这个问题

$ filesToSync包含要同步的文件数组。

$OfflineFilesSyncControlFlagSyncOut = 0x00000004
$OfflineFilesSyncControlCrKeepLatest = 0x30000000
$OfflineFilesTransitionFlagConsole = 0x00000002
$offlineCache = ([WmiClass]"\\.\root\cimv2:Win32_OfflineFilesCache")
    $offlineCache.Enable($true)
    $offlineCache.TransitionOnline([System.IO.Path]::GetDirectoryName($filesToSync[0]),$OfflineFilesTransitionFlagConsole)

    $observer = New-Object System.Management.ManagementOperationObserver

    Register-ObjectEvent -InputObject $observer -EventName "Progress" -Action {
        param ($o,$e)
        Write-Host "Progress $($e.Current) of $($e.Upperbound) Result $($e.Message)"
    }

    Register-ObjectEvent -InputObject $observer -EventName "Completed" -Action {
       param($o,$e)
       Write-Host "Progress $($e.Current) of $($e.Upperbound) Result $($e.Message)"
    }

    $params = $offlineCache.GetMethodParameters("Synchronize")
    $params.Paths = $filesToSync
    $params.Flags = $OfflineFilesSyncControlFlagSyncOut+$OfflineFilesSyncControlCrKeepLatest
    $offlineCache.InvokeMethod($observer,"Synchronize",$params,$null)