简体   繁体   中英

powershell command not running in .bat file?

I am trying to make a simple script to set my gcc variables. as a .bat file.

the variable is set like this

$env:Path += ";C:\Users\Brett\Compilers\MinGW\bin"

this runs just fine when I type/paste it into power shell.

but when I paste into a script myscript.bat, and run it through powershell I get this error:

C:\Users\Brett\Compilers>"$env:Path += ";C:\Users\Brett\Compilers\MinGW\bin""
The filename, directory name, or volume label syntax is incorrect.
PS C:\Users\Scruffy\Compilers>

PowerShell is a seperate execution enviroment from with Windows Command Line (cmd.exe)

If you want to run powershell commands from a batch file you need to save the powershell script (.ps1) and pass it into powershell.exe as a command line argument.

Example:

powershell.exe -noexit c:\scripts\test.ps1

More Information is available here on Microsoft TechNet

In general, leave batch stuff to .BAT files and put PowerShell stuff into .ps1 files.

I can duplicate your results here - but those are to be expected. Cmd.exe sees a string then a path and then gets quite confused as the syntax is not one that the command prompt can handle. So it gives that error message.

If you want to add stuff to your path, then why not put the statement inside a .ps1 script file?

As mentioned by others, you need to save the code in a .ps1 file and not .bat.

This line (from Setting Windows PowerShell path variable ) will do the trick:

$env:Path = $env:Path + ";C:\Users\Brett\Compilers\MinGW\bin"

Or even shorter:

$env:Path += ";C:\Users\Brett\Compilers\MinGW\bin" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM