如何将整数数组连接成逗号分隔的字符串

Lie*_*ero 2 powershell

我有两个问题,acually:

  1. 如何将整数数组连接成逗号分隔的字符串? (1,2,3) => "1,2,3"
  2. 如何将整数数组转换为字符串数组?(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."
Run Code Online (Sandbox Code Playgroud)

Mat*_*sen 5

在您的问题中,您已注释掉以下代码段:

($arraylist-join -',')
Run Code Online (Sandbox Code Playgroud)

因为它返回错误 Cannot convert value "," to type "System.Int32"...

原因是-前面的破折号','

在 PowerShell 中,只有运算符参数以破折号为前缀,并且由于','两者都不是(它是运算符的参数),因此 PowerShell 解析器变得非常困惑并试图将其-','视为会导致负数的值表达式。

只要取消破折号,你就会没事的:

$arraylist -join ','
Run Code Online (Sandbox Code Playgroud)

最后,您可以使用未经检查的强制转换运算符-as(PowerShell 3.0 和更新版本)轻松地将整数数组转换为字符串数组:

$StringArray = 1,2,3,4,5 -as [string[]]
Run Code Online (Sandbox Code Playgroud)

或使用显式转换(PowerShell 2.0 兼容):

$StringArray = [string[]]@(1,2,3,4,5)
Run Code Online (Sandbox Code Playgroud)