如何运行.cmd文件和命令

时间:2015-09-09 06:00:17

标签: powershell build

我转到文件夹C:\projects并运行初始化环境的脚本init.cmd,我转到任何项目,例如C:\projects\my_app并运行构建项目的命令build。我需要在PowerShell中自动化它。怎么样?我的尝试:

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
}

2 个答案:

答案 0 :(得分:1)

尝试这种方式:

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"
}  

此外,如果您对脚本输出不感兴趣并且只是希望它们被执行,您可以使用Out-Null这样:

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
}

答案 1 :(得分:1)

批处理脚本可以直接从PowerShell运行,并且应该同步执行,即调用应该只在执行完成后返回。

有多种方法可以调用批处理脚本,但我个人更喜欢使用调用运算符(&):

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

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

请注意,必须指定批处理脚本的(绝对或相对)路径,因为PowerShell不会在搜索路径中包含当前目录。