Stolken
Stolken

Reputation: 11

Get the current ScheduledJob name

In Powershell, I created a ScheduledJob using the command Register-ScheduledJob -ScriptBlock {...}. This ScheduledJob executes a ScriptBlock. How can I retrieve the name of the currently running ScheduledJob from the ScriptBlock?

E.g.

Register-ScheduledJob -ScriptBlock { $CurrentScheduledJob | Out-File -FilePath ScheduledJob.txt}

The task in the Windows Task Scheduler is running the command:

powershell.exe -NoLogo -NonInteractive -WindowStyle Hidden -Command "Import-Module PSScheduledJob; $jobDef = [Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition]::LoadFromStore('asdfdsafsdf', 'C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs'); $jobDef.Run()"

I tried to save the variable $jobDef but it is empty.

Thank you

Upvotes: 1

Views: 610

Answers (1)

TravisEz13
TravisEz13

Reputation: 2413

I ran a ScheduledJob and exported all variable and environment variable and did not find the name or id of the job.

I found a work around:

$jobName = 'testName'
Register-ScheduledJob -ScriptBlock { param($name)
         $name | out-file C:\name.txt
    } -name $jobName -ArgumentList @($jobName)

If using a parameter is not a solution for you, and you absolutely must retrieve it at run time, then this is a feature request. You can ask for this at the PowerShell user voice

Upvotes: 1

Related Questions