问题描述
我有两个问题:
- 如何将整数数组连接成逗号分隔的字符串?(1,2,3) => "1,2,3"
- 如何将整数数组转换为字符串数组?(1,2,3) => ("1", "2", "3")
$arraylist = New-Object 'system.collections.arraylist'
$arraylist.Add(1);
$arraylist.Add(2);
$csv = ??
#($arraylist-join -',') returns error: Cannot convert value "," to type "System.Int32". Error: "Input string was not in a correct format."
推荐答案
在您的问题中,您已注释掉以下代码段:
In your question, you've commented out the following snippet:
($arraylist-join -',')
因为它返回错误 Cannot convert value "," to type "System.Int32"...
这是因为','
前面的破折号-
.
The reason for this is the dash -
in front of ','
.
在 PowerShell 中,只有 operators 和 parameters 以破折号为前缀,并且由于 ','
两者都不是(它是一个 运算符的参数),PowerShell 解析器变得非常困惑,并试图将 -','
视为会导致负数的值表达式.
In PowerShell, only operators and parameters are prefixed with a dash, and since ','
is neither (it's an argument to an operator), the PowerShell parser gets super confused and tries to treat -','
as a value expression that would result in a negative number.
只要取消破折号就可以了:
Just void the dash and you'll be fine:
$arraylist -join ','
最后,您可以使用未经检查的强制转换运算符 -as
(PowerShell 3.0 和更新版本)轻松将整数数组转换为字符串数组:
Finally, you can easily cast an array of integers to an array of strings with the unchecked cast operator -as
(PowerShell 3.0 and newer):
$StringArray = 1,2,3,4,5 -as [string[]]
或使用显式转换(PowerShell 2.0 兼容):
or with an explicit cast (PowerShell 2.0-compatible):
$StringArray = [string[]]@(1,2,3,4,5)
这篇关于如何将整数数组连接成逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!