0
votes

I am trying to receive "On Progress" events when Syncronize method is invoked on Win32_OfflineFiles cache in PowerShell v3 (I'm restricted from using later version). According to MSDN documentation here the process is:

To monitor progress, implement a WMI event sink to receive SWbem.OnProgress event notifications. The strMessage parameter contains a text string that is encoded with the following colon-delimited format...

The PowerShell examples to receive a WMI event provided here I can't see how they could be translated to my use case.

Example snippet from a VBScript which works:

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

While I can see Register-CimIndication, Register-WMIEvent can be used for WMI event, and Register-ObjectEvent for .NET objects I can't see example how this works with invoking WMI methods, as Register-WMIEvent takes a WMI event class or WMI event query.

Current PowerShell code with no callback:

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

1 Answers

0
votes

I resolved this by using ManagementOperationObserver and InvokeMethod with Register-ObjectEvent

$filesToSync contains an array of files to sync.

$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)