gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:45:03 25 4
gpt4 key购买 nike

我正在尝试将自定义列添加到从我们的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com