简体   繁体   中英

Long running Powershell command to to run with schtasks

I have various bits of automation on remote servers which I use through a Python script using pywinrm . I have lots of Powershell stuff commands I've automated already, but I've never had to run a long running Powershell command however.

I'm now trying to schedule some performance counters to capture during a performance test, and have come up with the following to capture what I want:

Start-Job { & Get-counter "\Processor(_Total)\% Processor Time", "\Memory\Available Bytes" -SampleInterval 2 -MaxSamples 10 | Export-counter -Path $home\Desktop\perf_data.csv -FileFormat CSV }

However, as part of my automation, I want to provide a command to schtasks to run this at a particular time across all servers. Currently the process starts with the following command, but no output is produced - I think the task just dies as soon as its started:

schtasks /create /tn "Perf Test" /tr "powershell -noexit -command { & Start-Job { & Get-counter '\Processor(_Total)\% Processor Time', '\Memory\Available Bytes' -SampleInterval 2 -MaxSamples 10 | Export-counter -Path $home\Desktop\perf_data.csv -FileFormat CSV }}" /sc once /st 16:58:00 /sd 24/01/2018

I realise I could make this easier on myself by scheduling a script to run rather than a command, but I'd ideally like to just run this as a command.

Thanks in advance if anyone can help.

So I'm not terribly familiar with counters, but this solution should work for you:

$Command = [Convert]::ToBase64String(
    [Text.Encoding]::Unicode.GetBytes(@"
`$CounterParams = @{
    Counter = @(
        '\Processor(_Total)\% Processor Time'
        '\Memory\Available Bytes'
    )
    SampleInterval = 2
    MaxSamples = 10
}
Get-Counter @CounterParams |
    Export-Counter -Path $Env:UserProfile\Desktop\perf_data.csv -FileFormat CSV }
"@ )
)

schtasks.exe /create /tn "Perf Test" /tr "powershell -NoProfile -EncodedCommand $Command"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM