[英]How to get results from Get-ScheduledTask into PowerShell variables
I have a PowerShell script that starts a task on a remote server.我有一个在远程服务器上启动任务的 PowerShell 脚本。 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"?如何对此进行编码以允许访问脚本以检查状态是否等于“正在运行”?
You can use the State property of a scheduled task on a while loop, like this:您可以在 while 循环中使用计划任务的 State 属性,如下所示:
Start-ScheduledTask -TaskName 'SomeTaskName'
while ((Get-ScheduledTask -TaskName 'SomeTaskName').State -ne 'Ready') {
##Wait a while
Start-Sleep -Seconds 10
}
The comment from Santiago Squarzon answered my question. Santiago Squarzon 的评论回答了我的问题。
"Taskname: $($results.TaskName)" and "State: $($results.State)" or even simpler, $results | "Taskname: $($results.TaskName)" 和 "State: $($results.State)" 甚至更简单,$results | Select-Object TaskName, State – Santiago Squarzon
选择对象任务名称,状态 – Santiago Squarzon
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.