我正在尝试生成一个输出字符串,例如Item1, Item2
,并用逗号分隔符将其连接起来。为此,我们在Select-Object -Property
中启动一个空数组。
检查此代码:
$Test = @(
[PSCustomObject]@{
Name = 'Test'
}
[PSCustomObject]@{
Name = 'Test2'
}
) | Select-Object -Property @{N = 'Problem'; E = { @() } },
@{N = 'EmployeeType'; E = { $null } }, *
foreach ($R in $Test) {
$R.Problem += 'Item1'
$R.Problem += 'Item2'
}
$Test | Select-Object -Property @{Name = 'Problem'; Expression = { $_.Problem -join "; " } }, * -ExcludeProperty Problem | fl
结果:
Problem : Item1Item2
Name : Test
Problem : Item1Item2
Name : Test2
为什么属性Problem
串联为String
而不是Array
?如何将其转换为Array
?
答案 0 :(得分:5)
要实例化计算所得属性的表达式中的空数组,Option Explicit
'Copy a range
Sub CopyRange()
Dim ws1 As Workbook, ws2 As Workbook
'It's better to declare sheets and avoid activate
Set ws1 = Workbooks("Book1")
Set ws2 = Workbooks("Book2")
'Copy from ws1(Book1), sheet "Test" & range A1:A5 to ws2 (Book2), sheet "sheet1" & range A1
ws1.Worksheets("Test").Range("A1:A5").Copy
ws2.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues
End Sub
是不够的,因为PowerShell会将其展平并且变为$ null。
改为使用@()
,@()
返回:
$Test = @( [PSCustomObject]@{ Name = 'Test' } [PSCustomObject]@{ Name = 'Test2' } ) | Select-Object -Property @{N = 'Problem'; E = { ,@() } }, @{N = 'EmployeeType'; E = { $null } }, * foreach ($R in $Test) { $R.Problem += 'Item1' $R.Problem += 'Item2' } $Test | Select-Object -Property @{Name = 'Problem'; Expression = { $_.Problem -join "; " } }, * -ExcludeProperty Problem | fl
答案 1 :(得分:0)
不幸的是,这种创建空数组的方法行不通。
PS C:\users\js> $test[0].problem.gettype()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $test[0].problem.gettype()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PS C:\users\js> $test[0].problem -eq $null
True
顺便说一句,使用“ + =”杀死幼犬。