WMI query in powershell script returns no object when run in a scheduled task

拟墨画扇 提交于 2019-12-12 06:05:10

问题


I have a powershell script that runs successfully. I have tested it to death. The problem comes when running it as a scheduled task. The WMI query returns no object. I have tested with the a powershell console running under the context of the account used to run the scheduled task and it runs successfully under those conditions as well. Only when running as a scheduled task does the WMI query fail.

...

Function getMSMQMessageCount($queueName) {
    Add-content $LogFile "Querying $queueName"

    $query = "SELECT MessagesinQueue FROM Win32_PerfRawData_MSMQ_MSMQQueue WHERE Name = '$queueName'"
    try{
        $wmiObject = Get-WmiObject -Query $query
        $wmiObject.MessagesinQueue
    }catch{
        Add-content $LogFile "MSMQ Enumeration error $($_.Exception)" 
    }
}

$messaging = getMSMQMessageCount 'server\\private$\\messaging.application'

Exception caught in the Function used to issue the query:

System.Management.Automation.RuntimeException: Property 'MessagesinQueue' cannot be found on this object. Make sure that it exists.
   at System.Management.Automation.PropertyReferenceNode.GetValue(PSObject obj, Object property, ExecutionContext context)
   at System.Management.Automation.PropertyReferenceNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
   at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
   at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)

回答1:


I haven't tested your code, but it sounds like it requires administrator-rights to retrieve the data.

To use your account's administrator-rights, you need to check the Run with highest privileges-checkbox on the General page of the scheduled task. That is similar to answering yes in the UAC-dialog when you run it manually.



来源:https://stackoverflow.com/questions/28751730/wmi-query-in-powershell-script-returns-no-object-when-run-in-a-scheduled-task

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