【发布时间】:2015-02-26 20:04:25
【问题描述】:
我有一个成功运行的 powershell 脚本。我已经把它测试死了。将其作为计划任务运行时会出现问题。 WMI 查询不返回任何对象。我已经使用在用于运行计划任务的帐户的上下文下运行的 powershell 控制台进行了测试,并且它也在这些条件下成功运行。仅当作为计划任务运行时,WMI 查询才会失败。
...
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'
用于发出查询的函数中捕获的异常:
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)
【问题讨论】:
-
样本应该简短而简单。据我所知,你能删除 90% 的不必要的代码吗?这将使我们更容易看到真正的问题,更多的人会尝试帮助您。如果问题出在
getMSMQMessageCount函数内部,那么我们只需要那个函数,调用它的函数和与它一起使用的参数。和例外。就像你提供的那样。 :-) -
缩短了代码示例......人们通常要求一切......无法获胜
-
看起来不错,谢谢。澄清一下:你应该提供所有重要的东西,但尽可能少。这就是规则,stackoverflow.com/help/mcve。 :-) 前任。函数本身是不够的,因为您要传入队列名称值,所以我们也需要它。如果该值是使用不同的函数检索/生成的,我们也需要它。但是,如果在这些步骤之前很久就失败了,我们就不需要所有的导出逻辑、日志记录等。
-
我应该注意,如果在 SYSTEM 帐户下运行任务,这将毫无问题。
标签: powershell scheduled-tasks wmi