Romz
Romz

Reputation: 1457

How to run .cmd files and commands

I go to folder C:\projects and run script init.cmd that initializes environment, the I go to any project, e.g. C:\projects\my_app and run command build that builds the project. I need to automate it in PowerShell. How to that? My try:

Set-Location "C:\projects"
Invoke-Item init.cmd   # c:\projects\init.cmd

# Wait for init.cmd finish its work

$paths = Get-Content $paths_array
foreach ($path in $paths)
{
   Set-Location $path
   Invoke-Item build   # build is set in paths
   # Wait for build finish its work
}

Upvotes: 0

Views: 5020

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200453

Batch scripts can be run directly from PowerShell and should be executed synchronously, i.e. the call should only return after execution completed.

There are various ways to call a batch script, but personally I prefer using the call operator (&):

Set-Location "C:\projects"
& .\init.cmd

Get-Content $paths_array | ForEach-Object {
  Push-Location $_
  & .\build.cmd
  Pop-Location
}

Note that you must specify the (absolute or relative) path to the batch script, since PowerShell doesn't include the current directory in the search path.

Upvotes: 1

Dmitry VS
Dmitry VS

Reputation: 615

Try this way:

Set-Location "C:\projects"
$cmdpath = 'c:\windows\system32\cmd.exe /c'
Invoke-Expression "$cmdpath init.cmd"

$paths = Get-Content $paths_array
foreach ($path in $paths)
{
   Set-Location $path
   Invoke-Expression "$cmdpath build"
}  

Also if you are not interested in your scripts output and you just want them to be executed you can use Out-Null like this:

Set-Location "C:\projects"
$cmdpath = 'c:\windows\system32\cmd.exe /c'
Invoke-Expression "$cmdpath init.cmd" | Out-Null

$paths = Get-Content $paths_array
foreach ($path in $paths)
{
   Set-Location $path
   Invoke-Expression "$cmdpath build" | Out-Null
}

Upvotes: 1

Related Questions