21

Why does $dlls.Count return a single element? I try to declare my array of strings as such:

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

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

4 Answers 4

29

You should use something like:

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

As your answer shows, the semicolons also work because that marks the end of a statement...that would be evaluated, similar to using parenthesis.

Alternatively, use another pattern like:

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

But then you might want to use ArrayList and gain performance benefits...

See PowerShell array initialization

Sign up to request clarification or add additional context in comments.

1 Comment

[string[]]$Script:developmentApps = "git", "vscode", "gpg4win", "postman", "grepwin" in multiline ?
11

You are combining paths, thus, use the 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'
)

You don't need to use commas, semicolons nor parentheses. Also see this answer.

2 Comments

ah thank you. why are commas optional? why does powershell not seem to have any consistent syntax? this is just more confusing lol
@ibiza I wouldn't call them optional, since that would imply having them would work as well, which is not the case. So it is mandatory not to use commas (unless you wrap the entries in parentheses as demonstrated in other answers).
5

I found it, I must use semi-colons instead of commas...anyone can explain why?

It's clearly commas according to pretty much any source (such as this one)

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

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

1 Comment

All of this works: using comma, semicolon, or simply new lines. (tested in PowerShell 6.2)
2

Sorry for re-opening, but to me seems like it's missing the simplest and more natural way of declaring arrays in powershell:

$basePath = Split-Path $MyInvocation.MyCommand.Path
$dllDir = "$basePath\bin\debug"
$dlls = `
   "$dllDir\dll1.dll",
   "$dllDir\dll2.dll",
   "$dllDIr\dll3.dll"

The backtick after the declaration of the dlls variable is just an escape for the new line character, just for readability.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.