简体   繁体   中英

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM