如何声明一个字符串数组(跨多行)

21

为什么$dlls.Count只返回一个元素?我试图声明我的字符串数组如下:

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

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

可能是PowerShell数组初始化的重复问题。 - Kory Gill
4个回答

28

你应该使用类似于以下的内容:

$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")
)

正如您的回答所示,分号也起作用,因为它标志着语句的结尾......这将被评估,类似于使用括号。

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

$dlls = @()
$dlls += "...."

但是你可能想要使用ArrayList并获得性能上的好处...

请参见PowerShell数组初始化


[string[]]$Script:developmentApps = @" git vscode gpg4win postman grepwin "@ - Kiquenet

10

您正在组合一个路径,因此请使用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'
)

您不需要使用任何逗号、分号或括号。 还可以参见这个答案


5
谢谢。为什么逗号是可选的?为什么PowerShell似乎没有一致的语法?这更加令人困惑了lol。 - Bruno
2
@ibiza 我不会称它们为可选项,因为这会意味着拥有它们也可以起作用,但事实并非如此。因此,强制不使用逗号(除非您像其他答案中演示的那样将条目包装在括号中)。 - Ohad Schneider

4

我发现,我必须使用分号而不是逗号……有人能解释一下为什么吗?

根据几乎任何来源(例如此网站)都清楚地表明要使用逗号。

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

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

2
所有这些都可以工作:使用逗号、分号或者简单的换行。(在PowerShell 6.2中测试过) - MovGP0

0
抱歉重新开启,但对我来说,似乎缺少了在PowerShell中声明数组的最简单和更自然的方式。
$basePath = Split-Path $MyInvocation.MyCommand.Path
$dllDir = "$basePath\bin\debug"
$dlls = `
   "$dllDir\dll1.dll",
   "$dllDir\dll2.dll",
   "$dllDIr\dll3.dll"

在声明dlls变量之后的反引号只是对换行字符的转义,仅用于提高可读性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接