i'm not understanding what i'm doing wrong here since i seem to do the same thing but only one works.
i have a text file with a number list that i want to process (round the values):
39.145049
40.258140
41.400803
42.540093
43.664530
and here my script:
$a = get-content "input.txt"
$b = $a -join ','
$b | % {$_.ToString("#.###")}
this results in the following error:
Cannot find an overload for "ToString" and the argument count: "1".
At D:\script.ps1:9 char:9
+ $b | % {$_.ToString("#.###")}
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
however if i take the result after joining which is:
39.145049,40.258140,41.400803,42.540093,43.664530
and create the following script:
$b = 39.145049,40.258140,41.400803,42.540093,43.664530
$b | % {$_.ToString("#.###")}
it works just fine and outputs:
39.145
40.258
41.401
42.54
43.665
where am i going wrong on this one?
答案 0 :(得分:1)
发生这种情况的原因是输入的类型不同。
$b1 = $a -join ','
$b2 = 39.145049,40.258140,....
$b1.GetType().Name
String
$b2.GetType().Name
Object[]
由于第一种情况下的输入是单个字符串,因此foreach循环不会将其处理为十进制值的集合,而是一个字符串。因此,
$b | % {$_.ToString("#.###")}
要做(作为伪代码):
'39.145049,40.258140,41.400803,42.540093,43.664530'.ToString("#.###")
数组版本正在做
39.145049.ToString("#.###")
40.258140.ToString("#.###")
41.400803.ToString("#.###")
Powershell能够在以后的情况中确定这些值是数字。在第一种情况下,它只是一个字符串,因此自动转换不起作用。
在第一种情况下实际起作用的是将值强制转换为数字。像这样
$a | % {$([double]$_).ToString("#.###")}
39,145
40,258
41,401
42,54
43,665