问题
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