2

I'm new to Powershell. When I run the following command from within a ps1 file:

add-computer -DomainName "example.com" -NewName "adfsserver" -restart

...I get this error:

A positional parameter cannot be found that accepts argument 'example.com'
+ add-computer ?DomainName "example.com" -NewName "adfsserver" -restart

Interestingly, if I simply open a PowerShell window and paste this command in, it works fine (though it prompts me for credentials).

For me, a positional parameter is a parameter whose value is determined by its relative position in a parameter list. I don't see that I'm using any positional parameters, I'm using named parameters (or named keys, whatever Powershell calls it). According to the examples here I'm using -DomainName correctly. I can't tell it it is objecting to "-DomainName" or "example.com".

And for the life of me I don't understand why the command works perfectly fine when I type it in manually - does Windows have different PowerShell parsers that work differently in different places?

Ken Krueger
  • 1,005
  • 14
  • 26
  • 4
    Make sure your dash is not an endash or emdash. The `?` indicates an unrecognized character, which is typical of ASCII and endash and emdash characters. You are likely copying from a location where visibly it is hard to tell a difference – AdminOfThings Jul 26 '21 at 18:53
  • 1
    In addition to @AdminOfThings helpful comment, you could use [`Splatting`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-7.1#:~:text=Splatting%20is%20a%20method%20of,collection%20with%20a%20command%20parameter.&text=Beginning%20in%20Windows%20PowerShell%203.0,all%20parameters%20of%20a%20command.) to avoid this kind of errors. – Santiago Squarzon Jul 26 '21 at 19:29

1 Answers1

3

As AdminOfThings points out, the add-computer ?DomainName part of your error message implies that the - character in -DomainName was misinterpreted by PowerShell, causing the token to be interpreted as a positional argument rather than a parameter name.

Therefore, the example.com argument became another - and therefore unrecognized - positional argument.

While using the ASCII-range - "dash" (strictly speaking: hyphen-minus, U+002D) is definitely preferable as the parameter-name sigil, PowerShell does accept non-ASCII variations such as (en dash, U+2013), and when it doesn't, the implication is that PowerShell is misinterpreting your source code, something that is fixed by re-saving your script with UTF-8 encoding with a BOM - see this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775