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

标签 powershell variables 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,RefreshType,@{
    Name = "RefreshTypeFriendly"
    Expression = {
        $_.RefreshType
    }
}
$collsCustom  | Format-Table
Name         RefreshType RefreshTypeFriendly
----         ---------- -------------------
Collection 1          6                   6
Collection 2          4                   4

以下代码在表达式脚本 block 中强制为 $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

最佳答案

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

试试这个

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

关于powershell - Select-Object 表达式语句中的变量未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66166224/

相关文章:

function - PowerShell函数返回变量

html - 在字符串 (PowerShell) 中转义 HTML 特定字符的最佳方法是什么?

powershell - 如何在 PowerShell 中使用 curl 命令?

Powershell在一个选择对象中获取不同级别的节点值

regex - 如何从 Select-String 中获取捕获的组?

powershell - SWFUpload 使用 PowerShell 将文件上传到网站

c++ - 如何在 C++ 中初始化多个局部变量

javascript - 如何防止递归函数重新初始化累加变量?

ruby-on-rails - 使用正则表达式从文件中提取环境变量

powershell - 在PowerShell中选择带有变量的属性或参数