I’m trying to use the Task class in Powershell to run an operation asynchronously. But I’m getting the following exception:
Id : 1
Exception : System.AggregateException: One or more errors occurred. ---> System.Management.Automation.PSInvalidOperationException: There is no Runspace available to
run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script
block you attempted to invoke was: Write-Host "hey!"
at System.Management.Automation.ScriptBlock.InvokeAsDelegateHelper(Object dollarUnder, Object dollarThis, Object[] args)
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
---> (Inner Exception #0) System.Management.Automation.PSInvalidOperationException: There is no Runspace available to run scripts in this thread. You can
provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was:
Write-Host "hey!"
at System.Management.Automation.ScriptBlock.InvokeAsDelegateHelper(Object dollarUnder, Object dollarThis, Object[] args)
at System.Threading.Tasks.Task.Execute()<---
Status : Faulted
IsCanceled : False
IsCompleted : True
CreationOptions : DenyChildAttach
AsyncState :
IsFaulted : True
AsyncWaitHandle : System.Threading.ManualResetEvent
CompletedSynchronously : False
My code:
$delegate = [System.Action]{ Write-Host "Test" }
[System.Threading.Tasks.Task]::Run($delegate)
Open Start. Search for PowerShell, right-click the top result, and select the Run as administrator option. (Optional) Type the following command to confirm the task exists and press Enter: Get-ScheduledTask -TaskName "TAKS-NAME" In the command, make sure to replace "TAKS-NAME" with the name of the task.
To retrieve the existing tasks in the task scheduler using PowerShell, we can use the PowerShell command Get-ScheduledTask. We can use the Task Scheduler GUI to retrieve the scheduled tasks. To retrieve using PowerShell, use the Get-ScheduledTask command.
With PowerShell you can sequentially execute multiple commands at once or pipe output commands to automate common tasks. Designed for app makers and administrators to automate tasks with environments and associated apps, flows, and connectors.
It would take a lot of work to get PowerShell working with Task
. Task
is too much of a low level construct for PowerShell to function with it directly.
To perform PowerShell operations asynchronously use jobs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With