如何声明字符串数组(在多行上)

ibi*_*iza 9 arrays powershell

为什么$dlls.Count返回单个元素?我尝试声明我的字符串数组:

$basePath = Split-Path $MyInvocation.MyCommand.Path

$dlls = @(
    $basePath + "\bin\debug\dll1.dll",
    $basePath + "\bin\debug\dll2.dll",
    $basePath + "\bin\debug\dll3.dll"
)
Run Code Online (Sandbox Code Playgroud)

Kor*_*ill 16

你应该使用类似的东西:

$dlls = @(
    ($basePath + "\bin\debug\dll1.dll"),
    ($basePath + "\bin\debug\dll2.dll"),
    ($basePath + "\bin\debug\dll3.dll")
)

or

$dlls = @(
    $($basePath + "\bin\debug\dll1.dll"),
    $($basePath + "\bin\debug\dll2.dll"),
    $($basePath + "\bin\debug\dll3.dll")
)
Run Code Online (Sandbox Code Playgroud)

正如你的答案所示,分号也起作用,因为它标志着一个语句的结束......将被评估,类似于使用括号.

或者,使用另一种模式,如:

$dlls = @()
$dlls += "...."
Run Code Online (Sandbox Code Playgroud)

但是,您可能希望使用ArrayList并获得性能优势......

请参阅PowerShell阵列初始化


Mar*_*ndl 9

您正在组合路径,因此使用Join-Path cmdlet:

$dlls = @(
    Join-Path $basePath '\bin\debug\dll1.dll'
    Join-Path $basePath '\bin\debug\dll2.dll'
    Join-Path $basePath '\bin\debug\dll3.dll'
)
Run Code Online (Sandbox Code Playgroud)

您不需要使用任何逗号、分号或括号。另请参阅此答案

  • 啊谢谢你。为什么逗号是可选的?为什么 powershell 似乎没有任何一致的语法?这只是更令人困惑,哈哈 (5认同)
  • @ibiza我不会称它们为可选的,因为这意味着它们也可以工作,但事实并非如此。因此,必须不要使用逗号(除非您将条目括在括号中,如其他答案中所示)。 (2认同)