在计划任务中运行时,powershell 脚本中的 WMI 查询不返回任何对象 [英] WMI query in powershell script returns no object when run in a scheduled task
问题描述
我有一个成功运行的 powershell 脚本.我已经测试过它了.将其作为计划任务运行时会出现问题.WMI 查询不返回任何对象.我已经使用在用于运行计划任务的帐户上下文下运行的 powershell 控制台进行了测试,并且它在这些条件下也能成功运行.仅当作为计划任务运行时,WMI 查询才会失败.
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.
要使用您帐户的管理员权限,您需要在计划任务的常规页面上选中以最高权限运行
-复选框.这类似于手动运行时在 UAC 对话框中回答是".
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.
这篇关于在计划任务中运行时,powershell 脚本中的 WMI 查询不返回任何对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!