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

PowerShell脚本问题:$drive变量未被识别致输出空白求修复

问题分析与修复方案

核心问题

远程执行的脚本块无法访问本地变量$drive。Invoke-Command的脚本块运行在目标服务器的独立会话中,默认无法直接引用本地会话里的变量,导致Where {$_.Name -eq $drive}中的$drive为空,过滤不到任何驱动器,最终输出空白。

修复方法

方法1:使用$using:作用域引用本地变量(PowerShell 3.0+推荐)

在远程脚本块中用$using:drive代替$drive,直接引用本地会话的变量:

$serverList = 'kr302vm', 'kr352fs', 'kr252py', 'kr101bu'
$driveList = 'D', 'E'
    
$output = foreach ($item in $serverList)    
{   
    foreach ($drive in $driveList)
    {
        # 使用$using:drive引用本地变量
        $spaceObjects_D = Invoke-Command -ComputerName $item {
            Get-PSDrive -PSProvider FileSystem | Where {$_.Name -eq $using:drive}
        } 
        $spaceObjects_D | Select-Object -Property PSComputerName, Name, 
            @{Label='Used (GB)'; expression={($_.Used/1GB).ToString('F2')}}, 
            @{Label='Free (GB)'; expression={($_.Free/1GB).ToString('F2')}}, 
            @{Label='Free (%)'; expression={($_.Free/($_.Used + $_.Free)).ToString('P')}}
    }
}   
$output | Export-Csv -Path "C:\test\diskusage_A.csv" -NoTypeInformation 

方法2:通过-ArgumentList传递变量

将$drive作为参数传递给远程脚本块,用$args[0]接收:

$serverList = 'kr302vm', 'kr352fs', 'kr252py', 'kr101bu'
$driveList = 'D', 'E'
    
$output = foreach ($item in $serverList)    
{   
    foreach ($drive in $driveList)
    {
        # 通过-ArgumentList传递变量,脚本块内用$args[0]接收
        $spaceObjects_D = Invoke-Command -ComputerName $item -ArgumentList $drive {
            Get-PSDrive -PSProvider FileSystem | Where {$_.Name -eq $args[0]}
        } 
        $spaceObjects_D | Select-Object -Property PSComputerName, Name, 
            @{Label='Used (GB)'; expression={($_.Used/1GB).ToString('F2')}}, 
            @{Label='Free (GB)'; expression={($_.Free/1GB).ToString('F2')}}, 
            @{Label='Free (%)'; expression={($_.Free/($_.Used + $_.Free)).ToString('P')}}
    }
}   
$output | Export-Csv -Path "C:\test\diskusage_A.csv" -NoTypeInformation 

额外优化建议

  • 添加-PSProvider FileSystem到Get-PSDrive,确保只返回磁盘驱动器,避免筛选到注册表、网络共享等非本地磁盘的驱动器。
  • 可添加错误处理逻辑,比如用-ErrorAction SilentlyContinue跳过无法连接的服务器,或捕获异常记录错误信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:32:43