Powershell Timer for Windows performance Recorder (WPR)

489 views Asked by At

I'm doing a timer that counts to milliseconds, and when milliseconds reached their end its stops the script. Why I wont the code repeating until its finish its because the Windows performance recorder is working behind the scene and wpr is working with time and we have to stop the wpr manually. The problem is the timer that I have doesn't stop the WPR when its remotely launched. timer working great locally.

Here the code below:

$scriptwpr =  {
            wpr -start cpu
            function Stop-Script
            {
                Write-Host "Called Stop-Script."
                wpr -stop C:\$env:computername-PerformanceAnalyzer.etl
                #[System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.CloseAsync()
           }

            $elapsedEventHandler = {

                param ([System.Object]$sender, [System.Timers.ElapsedEventArgs]$e)
                Write-Host "Event handler invoked."
                ($sender -as [System.Timers.Timer]).Stop()
                Unregister-Event -SourceIdentifier Timer.Elapsed
                Stop-Script
            }

            $timer = New-Object System.Timers.Timer -ArgumentList 120000 # setup the timer to fire the elapsed event after 20 minutes
            Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier Timer.Elapsed -Action $elapsedEventHandler
            $timer.Start()
 }

Invoke-command -script $scriptwpr -computer computernamehere

Do you have a better way to resolve my problem?

1

There are 1 answers

1
Daniel On BEST ANSWER

I'm far from an expert on remote code execution however it seems to me that after the last line of in your scriptblock $timer.Start(), the powershell session on the remote system ends and along with it your timer object and eventhandler.

Try instead using a PSSession which can be kept alive even after your code has run to completion

$session = New-PSSession -ComputerName computernamehere
Invoke-Command -script $scriptwpr -Session $session

Later cleanup your session by using Remove-PSSession $session