我想生成下表:
AAA BBB CCC
--- --- ---
10 10 10
10 10 10
10 10 10
10 10 10
10 10 10
所以我使用foreach循环编写以下代码来生成列名:
$property = @('AAA', 'BBB', 'CCC') | foreach {
@{ name = $_; expression = { 10 } }
}
@(1..5) | select -Property $property
但是我收到以下错误,说nameis not a string:
select : The "name" key has a type, System.Management.Automation.PSObject, that is not valid; expected type is System.String.
At line:4 char:11
+ @(1..5) | select -Property $property
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Select-Object], NotSupportedException
+ FullyQualifiedErrorId : DictionaryKeyIllegalValue2,Microsoft.PowerShell.Commands.SelectObjectCommand
要使代码正常工作,我必须将其转换$_为string如下所示:
$property = @('AAA', 'BBB', 'CCC') | foreach {
@{ name = [string]$_; expression = { 10 } }
}
@(1..5) | select -Property $property
或者像下面这样:
$property = @('AAA', 'BBB', 'CCC') | foreach {
@{ name = $_; expression = { 10 } }
}
$property | foreach { $_.name = [string]$_.name }
@(1..5) | select -Property $property
问题是:$_已经是string. 为什么我必须string再次转换它?为什么select认为name是PSObject?
为了确认它已经是 a string,我编写了以下代码来打印 的类型name:
$property = @('AAA', 'BBB', 'CCC') | foreach {
@{ name = $_; expression = { 10 } }
}
$property | foreach { $_.name.GetType() }
以下结果证实它已经是string:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
True True String System.Object
True True String System.Object
我知道还有许多其他更简单的方法可以生成表格。但我想了解为什么我必须将 a 转换string为string才能使代码正常工作,以及为什么select不认为stringa 是string. 对于它的价值,我$PSVersionTable.PSVersion的是:
Major Minor Build Revision
----- ----- ----- --------
5 1 18362 1474