如何通过PowerShell脚本调用VS2019开发者命令提示符执行代码
问题
需要通过PowerShell脚本动态生成代码,并在VS2019开发者命令提示符(DCP)中自动执行仅能在DCP环境运行的tf命令。示例场景为获取DevOps源代码控制中指定文件夹的最新文件,对应命令如下:
cd "C:\someroot\foldername" tf get
DCP的启动脚本路径为:C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\Tools\VsDevCmd.bat
此前尝试的方法均失败:
- 使用
Start-Process传递命令参数,返回错误Invalid command line argument: 'cd':Start-Process -FilePath "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\Tools\VsDevCmd.bat" -ArgumentList "cd ""C:\root\folder name"" ; tf get" Start-Process -FilePath "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\Tools\VsDevCmd.bat" -WorkingDirectory "C:\root\folder name" -ArgumentList "tf get" - 通过快捷方式打开DCP,但无法添加后续执行命令:
Invoke-Item "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools\Developer Command Prompt for VS 2019.lnk"
可行方案
方法1:通过cmd.exe间接调用VsDevCmd.bat执行命令
VsDevCmd.bat是CMD环境脚本,需通过cmd.exe启动,利用/c参数让CMD执行完指定命令后退出,注意路径转义与命令拼接:
# 定义目标文件夹路径 $targetFolder = "C:\root\folder name" # 拼接命令:先初始化DCP环境,再切换目录执行tf get $cmdCommand = "`"C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\Tools\VsDevCmd.bat`" && cd `"$targetFolder`" && tf get" # 启动CMD执行命令,-Wait表示等待命令执行完成 Start-Process -FilePath "cmd.exe" -ArgumentList "/c", $cmdCommand -Wait
若需保持窗口打开查看输出,可将/c替换为/k:
Start-Process -FilePath "cmd.exe" -ArgumentList "/k", $cmdCommand
方法2:生成临时批处理文件执行
动态生成包含环境初始化与目标命令的批处理文件,再通过CMD执行,适合复杂多步操作:
# 定义目标文件夹 $targetFolder = "C:\root\folder name" # 生成临时批处理文件路径 $tempBatPath = Join-Path $env:TEMP "RunTfGet.bat" # 写入批处理内容 @" @echo off call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\Tools\VsDevCmd.bat" cd "$targetFolder" tf get pause # 可选,保留窗口查看执行结果 "@ | Out-File -FilePath $tempBatPath -Encoding ASCII # 执行批处理文件 Start-Process -FilePath "cmd.exe" -ArgumentList "/c", "`"$tempBatPath`"" -Wait # 执行完成后删除临时文件(可选) Remove-Item $tempBatPath -Force
内容的提问来源于stack exchange,提问作者Fletch
相关产品推荐
相关产品推荐

