Search code examples
windowspowershellscheduled-taskswindows-server-2008windows-server-2008-r2

Strange result from powershell script when executing via scheduled task


I'm running a powershell script, that when run from the ISE outputs one set of values but when the same task is run through task scheduler it seems to add a second value that doesn't display when run manually. The code that's being executed is as below:

import-module WebAdministration

$app_pool_name = <<app_pool_name_goes_here>>

$memused = ""
$cpuused = ""

$datetime = get-date -format s
$memused = Get-WmiObject Win32_process  | where CommandLine -Match "$app_pool_name"
$id = dir IIS:\AppPools\$app_pool_name\WorkerProcesses\ | Select-Object -expand processId
$cpuUsed = Get-WmiObject Win32_PerfFormattedData_PerfProc_Process | where IDProcess -Match $id

Add-Content -path C:\Winsys\PSOutput\$app_pool_name-CPU-RAM_test.txt -value "$datetime,$($memUsed.workingsetsize),$($cpuUsed.PercentProcessorTime)"

When running the script manually the output returned is:

Date,Mem,CPU

2016-08-02T14:09:36,15062687744,0

2016-08-02T14:09:38,15062425600,0

When running the script through task scheduler the output returned is:

Date,Mem,CPU

2016-08-02T13:58:25,15065047040 624189440,0

2016-08-02T14:05:01,15061901312 624713728,0

The difference being the Mem, for some reason it's adding an extra value. Does anyone know why this is?


Solution

  • Turns out this was my own error, there are two app pools with very similar names, the -match was catching both. But it still didn't explain why it was only showing both in task scheduler and not ISE. Ah well, resolved now by adding a -and -notmatch "text" section.

    E.g.

    Get-WmiObject Win32_process  | where {$_.CommandLine -Match "$app_pool_name" -and $_.CommandLine -notmatch "<<text in other command line>>"}
    

    Add Comment