Windows Powershell GetForegroundWindow() returns multiple processes when run via Task Scheduler

549 Views Asked by At

I am trying to run a PowerShell script periodically using task scheduler. I would like to return the name of the process currently in use. I am using the code found here to do so. This works when I run the script from PowerShell. The process returned is "powershell" as expected. However, when I run this using task scheduler, all of the currently running processes are returned, not just the foreground window process. The script saves the process details in the file "process_file.out".

The script I am using is below:

#set working directory to path of script
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
Set-Location -Path $scriptPath -Passthru

Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class Tricks {
    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();
}
"@

$a = [tricks]::GetForegroundWindow()

$b=get-process | ? { $_.mainwindowhandle -eq $a } | Get-Unique
$c=$b.ProcessName
$c | Out-File -FilePath process_file.out

An example of the first portion of the output file "process_file.out" when run using task scheduler is below:

acrotray
aesm_service
AGMService
AGSService
ApplicationFrameHost
armsvc
audiodg
backgroundTaskHost
chrome
cmd
...etc
                              
0

There are 0 best solutions below