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

如何将远程主机Shadow Storage表格数据追加写入日志不覆盖

解决PowerShell日志覆盖问题:追加多主机Shadow Storage信息

问题说明

执行PowerShell脚本获取远程主机Shadow Storage信息时,每次写入日志文件都会覆盖原有内容,期望实现多主机信息依次追加,格式为每个服务器名称居中显示,下方紧跟对应存储信息表格。

原脚本问题分析

原脚本中Out-File默认使用覆盖模式,导致每次循环都会替换日志文件内容;同时Allocated Shadow Copy字段的表达式错误,与Used Shadow Copy使用了相同的PostContext[2],导致两个字段值重复。

修改后的脚本

$computerList = Get-Content "C:\Check_ShadowStorage\ServersList.txt"
$logPath = "C:\Check_ShadowStorage\Output.log"

# 可选:清空日志文件,避免多次运行重复追加(若需保留历史日志可删除此行)
"" | Out-File $logPath -Force

foreach($computer in $computerList)
{
    $shadowData = Invoke-Command -ComputerName $computer -Credential $credential -ScriptBlock {
        # 解析vssadmin输出,修正字段映射
        vssadmin list shadowstorage | Select-String -Context 0,5 '^Shadow Copy Storage' | 
        Select 
            @{Label="Volume"; Expression={$_.Context.PostContext[0].Trim().SubString(13,2)}},
            @{Label="Used Shadow Copy"; Expression={$_.Context.PostContext[2].Trim().SubString(32)}},
            @{Label="Allocated Shadow Copy"; Expression={$_.Context.PostContext[3].Trim().SubString(32)}},
            @{Label="Maximum Storage"; Expression={$_.Context.PostContext[4].Trim().SubString(35)}} |
        Format-Table Volume, 'Used Shadow Copy', 'Allocated Shadow Copy', 'Maximum Storage' -AutoSize
    }

    # 生成居中的服务器标题
    $serverTitle = "{0,50}" -f $computer
    # 将标题、空行、数据、分隔空行追加到日志
    $serverTitle, "", $shadowData, "" | Out-File $logPath -Append
}

关键修改点

  • 追加写入:给Out-File添加-Append参数,实现内容追加而非覆盖
  • 修正字段错误:将Allocated Shadow Copy的表达式从PostContext[2]改为PostContext[3],匹配vssadmin输出的实际行位置
  • 格式优化:添加服务器居中标题和空行分隔,让日志结构更清晰易读
  • 可选初始化:添加日志清空逻辑,避免多次运行时重复写入相同内容(按需保留)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 19:10:13