3

我正在尝试将自定义列添加到从我们的 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,RefreshType,@{
    Name = "RefreshTypeFriendly"
    Expression = {
        $_.RefreshType
    }
}
$collsCustom  | Format-Table
Name         RefreshType RefreshTypeFriendly
----         ---------- -------------------
Collection 1          6                   6
Collection 2          4                   4

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

$collsCustom = $colls | Select Name,RefreshType,@{
    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

4

1 回答 1

3

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

尝试这个

Expression = {
    [int]$type = $_.RefreshType
    $refreshTypes.$type
}
于 2021-02-12T04:35:38.340 回答