Reputation: 227
So, my command works just fine when I run it directly in PowerShell, but throws errors when I try to use it in my batch script. What I'm trying to do, is add a directory to the system path, but from a batch file (I have reasons). I know how to do it, and been successful in doing so, just can't seem to fix this.
I read some information that multiple commands are separated by semicolons, which I believe is probably what the problem is here, but if it is, I don't know how to escape it in the command.
This is the command I'm trying to use in my batch file.
@echo off
powershell "[Environment]::SetEnvironmentVariable('path', "$([Environment]::GetEnvironmentVariable('path', 'machine'));C:\to\a\new\path",'Machine');"
These are the errors that come up when running it.
At line:1 char:106
+ ... , $([Environment]::GetEnvironmentVariable('path', 'machine'));C:\usr\ ...
+ ~
Missing ')' in method call.
At line:1 char:117
+ ... ment]::GetEnvironmentVariable('path', 'machine'));C:\usr\bin,'Machine ...
+ ~
Missing argument in parameter list.
At line:1 char:127
+ ... t]::GetEnvironmentVariable('path', 'machine'));C:\usr\bin,'Machine');
+ ~
Unexpected token ')' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndParenthesisInMethodCall
I really believe the problem is just that first semicolon that I'm trying to use in a string.
Upvotes: 1
Views: 365
Reputation: 227
I figured it out... I wasn't the semicolons, but the quoting.
I found how to fix it by reading Powershell in a batch file - How do you escape metacharacters? (in the "Quoting headaches" bit).
So now it works when the command is formatted like so:
powershell "[Environment]::SetEnvironmentVariable('path', \""$([Environment]::GetEnvironmentVariable('path', 'machine'));C:\to\a\new\path\"",'Machine')"
Upvotes: 2