PowerShell Command Separator Is ; and Not &


Ahh PowerShell, I still cannot fully embrace your powerful weirdness.

With normal NT command prompt I can restart my SQL Server by running =>

net stop mssqlserver  & net start mssqlserver

This does not work in PowerShell, you get the usual cryptic, nonsensical and useless error message:

PS C:\> net stop mssqlserver & net start mssqlserver
Ampersand not allowed. The & operator is reserved for future use; use "&" to pass ampersand as a string.
At line:1 char:23
+ net stop mssqlserver & <<<<  net start mssqlserver
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : AmpersandNotAllowed

Personally, I would change this error message to:

Ampersand not allowed.  You can use the semi-colon instead for a command separator in PowerShell.

Ok, given this logic, then I try:

PS C:\> net stop mssqlserver "&" net start mssqlserver
The syntax of this command is:


Ok, I give up.  Time to search the internet.

Found some mention of an undocumented semi-colon as command separator, this works =>

PS C:\> net stop mssqlserver ; net start mssqlserver
The SQL Server (MSSQLSERVER) service is stopping.
The SQL Server (MSSQLSERVER) service was stopped successfully.

The SQL Server (MSSQLSERVER) service is starting.
The SQL Server (MSSQLSERVER) service was started successfully.

Comments (6)

  1. Papy Normand says:

    or  "& : not recognized character " as i have often seen in the SQL Server error messages.

    But your error message is very good as it is clear ( and it has the advantage to warn that & is reserved for a future use ( do you know which one ? )

    More amusing : i did not know that ; is the separator used between 2 NT commands ( ; for T-SQL is known as marking the end of statements even if too many people prefer not to include it, maybe by laziness ? )

    Thanks because you learnt me something ( maybe i have forgotten it since i write always 1 command by line in a script )

  2. Tony says:

    Does 'restart-service mssqlserver'  from an elevated powershell prompt not work for you?

  3. Matt Neerincx says:

    Yes, of course I should learn the powershell secret command for re-starting the service! 🙂

  4. Petar says:

    It would be interesting to see how [net stop mssqlserver && net start mssqlserver ] will be translated to PS (two ampersands)?

  5. Matt says:

    This behavior is borrowed from unix shells.  foo ; var executes foo, then bar unconditionally, foo && bar executed foo, then if foo rerturns 0 (success) executes bar Finally, foo || bar will execute foo, and if foo fails (returns non-zero), it will execute bar.

    So behavior is unintuitive from a command shell perspective, but from a unix perspective, the behavior is very intuitive.