PowerShell script doesn't work correctly from Windows Task Scheduler

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 15:13:16

Did you mean to assign the results of the Get-WmiObject ... | Foreach-Object { line to the $GetAppRequest variable? What I mean is that the output of the Foreach-Object loop are being caught by that assignment which doesn't look intentional since you don't use that variable again.

I'd suggest that you perform the assignment to the variable then pass the variable to the Foreach-Object cmdlet separately with some logging in between. Also, we could wrap the Get-WmiObject in a try{}catch{} construction to capture any errors the cmdlet might throw; to ensure the error is caught, we set -ErrorAction Stop:

try {
  $GetAppRequest = Get-WmiObject -Class SMS_UserApplicationRequest -Namespace root/SMS/site_$SiteCode -ErrorAction Stop
}
catch {
  log -message "Get-WmiObject cmdlet failed" -type "Error"
  log -message $_.Exception.Message.ToString() -type "Error"
}

if(-not $GetAppRequest) {
  log -message "Failed to retrieve WMI data" -type "Error"

} elseif(-not ($GetAppRequest = $GetAppRequest | Where-Object {$_.CurrentState -like "1"})) {
  log -message "No results with CurrentState = 1" -type "Info"
}

$GetAppRequest | ForEach-Object {
  ...

Check with "run only when the user is logged on" and hidden checkbox unchecked.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!