Home > Mobile >  How to get results from Get-ScheduledTask into PowerShell variables
How to get results from Get-ScheduledTask into PowerShell variables

Time:05-19

I have a PowerShell script that starts a task on a remote server. The task takes hours to run so I need to have a loop in my code to check the task every few minutes to see if it's still running before the script proceeds to the next step. I tried running the following:

$svc_cred = Get-Credential -Credential <DOMAIN>\<ServiceAccount>
$global:Remote_session = New-PSSession -ComputerName <Server> -Credential $svc_cred 
Invoke-Command -Session $global:Remote_session -ScriptBlock {
  $results = Get-ScheduledTask -TaskName  "Export_users" -TaskPath "\"
  Write-Output "Taskname: $results.TaskName"
  Write-Output "State:    $results.State"
}

But this produces the output:

Taskname: MSFT_ScheduledTask (TaskName = "Export_users", TaskPath = "\").TaskName
State:    MSFT_ScheduledTask (TaskName = "Export_users", TaskPath = "\").State

My desired outpout is:

Taskname: Export_users
State:    Running

How do I code this to allow access the script to check if State is equal to "Running"?

CodePudding user response:

You can use the State property of a scheduled task on a while loop, like this:

Start-ScheduledTask -TaskName 'SomeTaskName'
while ((Get-ScheduledTask -TaskName 'SomeTaskName').State -ne 'Ready') {
    ##Wait a while
    Start-Sleep -Seconds 10
}

CodePudding user response:

The comment from Santiago Squarzon answered my question.

"Taskname: $($results.TaskName)" and "State: $($results.State)" or even simpler, $results | Select-Object TaskName, State – Santiago Squarzon

  • Related