You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本中调用WMI对象方法后如何刷新其属性

WMI实例属性刷新解决方案

核心问题答复

通过Get-WmiObject获取的WMI实例对象默认会在本地缓存属性值,调用实例方法后缓存不会自动更新,所以直接读取属性得到的还是操作前的旧值。
并不是所有WMI对象都有专门命名的独立刷新函数,但所有这类WMI实例都内置了Get()方法,调用该方法即可从WMI仓库拉取最新的实例数据,完成属性刷新。

代码修改方案

你只需要在调用Stop()/Start()方法之后,先调用一次$hostInstance.Get(),再读取ServiceState属性即可拿到最新状态。考虑到BizTalk主机实例启停属于异步操作,建议添加几秒等待保证操作执行完成,修改后的示例代码如下:

$hosts = Get-WmiObject MSBTS_HostInstance -Namespace 'root/MicrosoftBizTalkServer'
    
foreach($hostInstance in $hosts) 
{       
    $name = $hostInstance.hostname
    $state = $hostInstance.ServiceState
    $stateName = Get-ServiceStateDescription $state
    
    Write-Diagnostic "Biztalk host instance '$name'. State: $stateName ($state)."
    
    # 已启动场景
    if (($hostInstance.ServiceState -eq 4))  
    {
      Write-Diagnostic "Stopping host instance '$name'..."
      $hostInstance.Stop()
      # 可根据实际环境调整等待时长
      Start-Sleep -Seconds 2
      # 刷新对象属性
      $hostInstance.Get()
      
      $state = $hostInstance.ServiceState
      $stateName = Get-ServiceStateDescription $state
      Write-Diagnostic "Stopped host instance '$name' stopped.  State: $stateName ($state)"
    }       
    
    # 已停止场景
    if (($hostInstance.ServiceState -eq 1))  
    {
        Write-Diagnostic "Starting host instance '$name'..."
        $r = $hostInstance.Start()
        # 可根据实际环境调整等待时长
        Start-Sleep -Seconds 2
        # 刷新对象属性
        $hostInstance.Get()
      
        $state = $hostInstance.ServiceState         
        $stateName = Get-ServiceStateDescription $state
        Write-Diagnostic "Starting host instance '$name' started.  State: $stateName ($state)." 
    }
}

补充说明

PowerShell 3.0及以上版本更推荐使用CIM cmdlet替代WMI cmdlet,Get-CimInstance获取的实例刷新方式为重新查询:$hostInstance = Get-CimInstance -InputObject $hostInstance,稳定性和安全性更优。

内容的提问来源于stack exchange,提问作者Jeremy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 13:57:02