Home > Mobile >  How to call a batch file from Powershell, using a custom .cmd to run it?
How to call a batch file from Powershell, using a custom .cmd to run it?

Time:09-17

I need to run the following batch file:

cd ..
msbuild reve_host.vcxproj

In order for msbuild to work, it needs to be run through a specific shell. Its path is stored in $executorPath in my Powershell script, which looks like this:

$executorPath = 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools\VC\x64 Native Tools Command Prompt for VS 2019'
Write-Host "STAGE: CLEAN."

Here are several ways of executing that I have tried, that have not worked:

  1. Invoke-Command '$executorPath "BUILD.bat"'
  2. Invoke-Command '$executorPath ".\BUILD.bat"'
  3. Invoke-Command -ScriptBlock {& $executorPath 'BUILD.bat'}
  4. Invoke-Command -ScriptBlock {& $executorPath '.\BUILD.bat'}
  5. $($executorPath 'BUILD.bat')
  6. $($executorPath '.\BUILD.bat')

With 1 and 2, I get:

Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.

With 3 and 4, I get:

The term 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools\VC\x64 Native Tools Command Prompt for VS 2019' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

None of these work. How do I run this?

CodePudding user response:

I found an alternative solution. Using this module allows MsBuild to be called directly from Powershell and saves the hassle of manually calling the correct shell. This circumvents the problem, instead of solving it though.

CodePudding user response:

Or Simply:

#Test cmd file:
@Echo off
for %%i in (1,2,3,4,5,6,7,8,9,10) DO Echo. Hello there
exit /B 200
PS> & G:\BEKDocs\Batch\batch1.cmd
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there

#To Use your example code:

PS> $ExecutionPath = "G:\BEKDocs\Batch\batch1.cmd"

PS> & $ExecutionPath
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there
 Hello there

PS> 

EDIT: It also works if the extension is .bat!

  • Related