1

I have an variable: $a = sfd. If I use New-Item '1'$a, then it will yield this error:

New-Item: A positional parameter cannot be found that accepts argument 'sdf'.

But if I use New-Item "1$a" then it works. According to How do I concatenate strings and variables in PowerShell? both two methods should work. Do you know why is that?

Ooker
  • 1,969
  • 4
  • 28
  • 58

2 Answers2

2

Because '1'$a is seen as two separate arguments and the New-Item cmdlet has only 1 positional parameter (-Path) unlike e.g. Write-Host which accepts multiple positional parameters:

$a = sfd
Write-Host '1'$a
1 sfd

(Note that the arguments are separated with a space in the displayed results)

There are several other ways to concatenate strings in PowerShell aside from "1$a", as e.g. New-Item ('1' + $a). For more information see Everything you wanted to know about variable substitution in strings

iRon
  • 20,463
  • 10
  • 53
  • 79
1

No clue why this is accepted by the Write-Host cmdlet in the linked example (probably because the cmdlet accepts an object). If I use it standalone ('1'$a) I receive the following error:

Unexpected token '$a' in expression or statement.

So even it will work with some cmdlets, I would never use the '1'$a syntax to join a string. Instead, use one of the following options:

  • "1$a"
  • ('1 ' + $a)
  • ('1{0}' -f $a)

The last example uses a format string and is useful when you have to concat multiple variables into a string to increase the readability. See: Understanding PowerShell and Basic String Formatting

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • as for the first method, is there a way to add an immediate character after the variable, but doesn't make PowerShell mistaken for a different variable? I try `1($a)2` but the result is `1(sdf)2` – Ooker Oct 26 '22 at 06:30
  • 1
    Yes, you can use a backtick: "1$a`2" – Martin Brandl Oct 26 '22 at 06:32