1

我有一个 PSCustomObject 数组包含在一个名为$attendance.

event name date       present
----- ---- ----       -------
A01   Mika 2021-02-22 1
A01   John 2021-02-22 0
B03   Mika 2021-02-24 0
B03   John 2021-02-24 1

present值必须修改为以下内容:

event name date       present
----- ---- ----       -------
A01   Mika 2021-02-22 Yes
A01   John 2021-02-22 No
B03   Mika 2021-02-24 No
B03   John 2021-02-24 Yes

我可以用一个ForEach-Object循环来改变它,但这会遍历整个对象。

$attendance | 
   ForEach-Object { 
      if ($_.present -eq '1') { $_.present = 'Yes' } else {$_.present = 'No' } 
   }

为了缩短代码,我尝试了以下变体,但无法将其折叠回$attendance变量中。

$attendance.present.replace('1','Yes').replace('0','No')

present是否有使用点符号来更改列值的单行或更简单的方法?

4

4 回答 4

2

另一种方法可能是Select-Object在此使用:

$attendance | Select-Object *, @{Name = 'present'; Expression = {('No','Yes')[[math]::Sign($_.present)]}} -ExcludeProperty present

输出:

event name date       present
----- ---- ----       -------
A01   Mika 2021-02-22 Yes    
A01   John 2021-02-22 No     
B03   Mika 2021-02-24 No     
B03   John 2021-02-24 Yes
于 2021-03-13T10:43:00.870 回答
1

不幸的是,使用点表示法$attendance.present创建了一个新数组,该数组不能用于操作PSCustomObject.

我能想到的最短的:

$attendance.foreach({ $_.present = ('No', 'Yes')[ $_.present ] })

无论present是整数还是字符串,这都有效。当用于索引数组时,PowerShell 会自动将字符串转换为整数。

稍长,使用三元运算符(需要 PS7+):

$attendance.foreach({ $_.present = $_.present -eq 0 ? 'No' : 'Yes' })

我更喜欢后者,因为我认为它更容易阅读。

于 2021-03-13T10:57:21.273 回答
1

I don't know a way to update all the values without using a loop but you can shorten your code to

$attendance | % {$_.present = @('Yes', 'No')[$_.present -eq '0']}

Another option might be to add a custom property doing the conversion

$attendance | 
    Add-Member -Name 'yesno' -MemberType ScriptProperty -Value {
        return  @('Yes', 'No')[$this.present -eq '0']
    }

Example Note that my csv delimiter is a comma so change accordingly

$attendance = @'
event,name,date,present
A01,Mika,2021-02-22,1
A01,John,2021-02-22,0
B03,Mika,2021-02-24,0
B03,John,2021-02-24,1
'@ | ConvertFrom-Csv
$attendance | Add-Member -Name 'yesno' -MemberType ScriptProperty -Value {return  @('Yes', 'No')[$this.present -eq '0']}

$attendance | ft -a

event name date       present yesno
----- ---- ----       ------- -----
A01   Mika 2021-02-22 1       Yes
A01   John 2021-02-22 0       No
B03   Mika 2021-02-24 0       No
B03   John 2021-02-24 1       Yes
于 2021-03-13T08:33:57.300 回答
-1

By using the Replace() method you're just manipulating the string stored in present, it will not update the value on $attendance, there is no string method to do it either.

于 2021-03-13T07:55:44.560 回答