Environment variable, PowerShell session and started from CMD
I am trying to run a PowerShell command from a Command Prompt window (run as administrator) but it fails. Whereas, when I run the same command from a PowerShell window, it works fine.
Here is the command without error in a PowerShell window:
Powershell [Environment]::SetEnvironmentVariable("HostIPv4", "192.168.255.14:", "Machine")
The command prompt window crashes:
C:\test>powershell [Environment]::SetEnvironmentVariable("HostIPv4", "192.168.255.14:", "Machine")
At line:1 char:39
+ [Environment]::SetEnvironmentVariable(HostIPv4, 192.168.255.14:, Mach ...
+ ~
Missing ')' in method call.
At line:1 char:39
+ [Environment]::SetEnvironmentVariable(HostIPv4, 192.168.255.14:, Mach ...
+ ~~~~~~~~
Unexpected token 'HostIPv4' in expression or statement.
At line:1 char:47
+ [Environment]::SetEnvironmentVariable(HostIPv4, 192.168.255.14:, Mach ...
+ ~
Missing argument in parameter list.
At line:1 char:73
+ ... ironment]::SetEnvironmentVariable(HostIPv4, 192.168.255.14:, Machine)
+ ~
Unexpected token ')' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndParenthesisInMethodCall
What could be the problem?
source to share
PowerShell command line parsing removes double quotes, use single quotes:
powershell [Environment]::SetEnvironmentVariable('HostIPv4', '192.168.255.14:', 'Machine')
Also note that you need to reopen a new process window to see the results (this is a known shell behavior, see also: C # Sets Environment Variable )
source to share
iRon's helpful answer explains the problem and works , but I suggest taking an overall more robust approach to invoking PowerShell commands fromcmd.exe
-
Use
-Command
explicitly because in PSv6 the default will change to-File
expecting a script filename, not a command. -
Use
-NoProfile
to avoid unnecessary loading of PowerShell profiles and a more predictable runtime. -
Double-quote the entire PowerShell command to protect it from potentially unwanted interpretation before
cmd.exe
.
powershell -NoProfile -Command "[Environment]::SetEnvironmentVariable('HostIPv4', '192.168.255.14:', 'Machine')"
Using '
instead "
inside the command line is an easy way to avoid having to use inline characters "
, which works great here, but if you need inline "
(for string interpolations), avoid them as either \"
(sic) or """
(sic).
source to share