Home > other >  Why does using single quotes with variables yield error "A positional parameter cannot be found
Why does using single quotes with variables yield error "A positional parameter cannot be found

Time:10-26

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related