Select-Object 表达式语句中的变量未按预期工作

问题描述

我正在尝试向从 MECM 实例检索的某些对象的表输出添加自定义列。

以下代码显示代码的精确格式,仅从 Get-Process 收集数据。

$types = @{
     "chrome" = "This is Chrome"
     "winlogon" = "This is winlogon"
}

$procs = Get-Process | Select Name,Id | Where { ($_.Name -eq "winlogon") -or ($_.Name -eq "chrome") }
$procsCustom = $procs | Select Name,Id,@{
    Name = "TestColumn"
    Expression = {
        $name = $_.Name
        $types.$name
    }
}
$procsCustom  | Format-Table

代码按预期运行:

Name        Id TestColumn
----        -- ----------
chrome   12428 This is Chrome
chrome   12448 This is Chrome
chrome   12460 This is Chrome
winlogon   880 This is winlogon
winlogon  5076 This is winlogon

当我对我的实际代码做同样的事情时:

$refreshTypes = @{
    1 = "Manual Update Only"
    2 = "Scheduled Updates Only"
    4 = "Incremental Updates Only"
    6 = "Incremental and Scheduled Updates"
}

$colls = Get-CMCollection | Where { ($_.RefreshType -eq 4) -or ($_.RefreshType -eq 6) }
$collsCustom = $colls | Select Name,RefreshType,@{
    Name = "RefreshTypeFriendly"
    Expression = {
        $type = $_.RefreshType
        $refreshTypes.$type
    }
}
$collsCustom | Format-Table

未填充自定义列:

Name         RefreshType RefreshTypeFriendly
----         ----------- -------------------
Collection 1           6
Collection 2           4

以下代码显示 $_.RefreshType 被正确解析:

$collsCustom = $colls | Select Name,@{
    Name = "RefreshTypeFriendly"
    Expression = {
        $_.RefreshType
    }
}
$collsCustom  | Format-Table
Name         RefreshType RefreshTypeFriendly
----         ---------- -------------------
Collection 1          6                   6
Collection 2          4                   4

以下代码在表达式脚本块中为 $type 强制使用假值,并表明其余代码有效:

$collsCustom = $colls | Select Name,@{
    Name = "RefreshTypeFriendly"
    Expression = {
        $type = 1
        $refreshTypes.$type
    }
}
$collsCustom | Format-Table
Name         RefreshType RefreshTypeFriendly
----         ----------- -------------------
Collection 1           6 Manual Update Only
Colleciton 2           4 Manual Update Only

那么为什么预期的代码自定义列中没有输出任何内容?鉴于我上面提供的例子,我被难住了。

FWIW 我也尝试过使用数组语法 ($refreshTypes[$type]) 而不是对象属性语法 ($refreshTypes.$type) 但我得到了相同的行为。

感谢您的时间。

环境:
Win10 x64 20H2
Powershell 5.1

解决方法

看起来您的类型没有被解释为 int。尝试将 $type 转换为 Int

试试这个

Expression = {
    [int]$type = $_.RefreshType
    $refreshTypes.$type
}