前陣子有分享透過指令啟動站台,有感於 vscode 可以使用指令(vscode .) 快速開啟並且
快速進入編輯該目錄,我想仿照類似的使用「 vs2022 . 」開啟開目錄下的 .sln 專案
方法一:透過 PowerShell 設定 Path
其中依據你的 Visual Studio 版本,指定是 Community、Professional、Enterprise 目錄
但是這個方式,會需要完整指定 .sln 的 檔名,我希望使用 「vs2022 .」
需要在 C:\Users\username\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 編輯內容
若目錄下沒有 Microsoft.PowerShell_profile.ps1 的檔案,可以使用以下語法判斷並新增
並且將以下內容加入其中
function vs2022 {
param (
[string]$Path = "."
)
$fullPath = Resolve-Path $Path
$sln = Get-ChildItem -Path $fullPath -Filter *.sln -File | Select-Object -First 1
if ($sln) {
& "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\devenv.exe" $sln.FullName
} else {
Write-Host "❌ 找不到 .sln 檔案於 $fullPath"
}
}
存檔,設定完成後就可使用該語法直接開啟方案
但是這個方法就只能使用在 PowerShell 命令列,若其他命令列也想支援,那就要使用方法二
方法二:支援相關命令列工具支援開啟方案
建立 vs2022.bat 檔(例如目錄 - D:\tools\scripts\vs2022.bat)
將以下指令放入並且存檔
@echo off
setlocal
REM 如果沒有指定參數,就使用目前目錄
set "targetDir=%~1"
if "%targetDir%"=="" set "targetDir=."
pushd "%targetDir%"
for %%f in (*.sln) do (
"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\devenv.exe" "%%~dpff"
goto end
)
echo ❌ 找不到 .sln 檔案於 %targetDir%
:end
popd
endlocal
加入系統環境變數 PATH
開始 → 搜尋「環境變數」
編輯「系統變數」中的 Path
加入你的 .bat 檔所在資料夾路徑
接著就可以使用 vs2022 開啟
擴充功能
多個 .sln 檔會列出選單讓你選
若找不到 .sln,會改找 .csproj
可將內容調整為
@echo off
setlocal enabledelayedexpansion
REM 設定預設資料夾為目前目錄
set "targetDir=%~1"
if "%targetDir%"=="" set "targetDir=."
pushd "%targetDir%"
REM 搜尋 .sln 檔案
set "index=0"
for %%f in (*.sln) do (
set /a index+=1
set "file!index!=%%f"
)
if %index%==0 (
REM 若找不到 .sln,搜尋 .csproj
set "index=0"
for %%f in (*.csproj) do (
set /a index+=1
set "file!index!=%%f"
)
)
if %index%==0 (
echo ❌ 找不到 .sln 或 .csproj 檔案於 %targetDir%
goto end
)
if %index%==1 (
call :openFile "!file1!"
goto end
)
REM 顯示選單讓使用者選擇
echo 🔍 找到 %index% 個方案檔案:
for /L %%i in (1,1,%index%) do (
echo %%i. !file%%i!
)
set /p userChoice=請輸入要開啟的編號:
if defined file%userChoice% (
call :openFile "!file%userChoice%!"
) else (
echo ⚠️ 無效的選擇。
)
:end
popd
endlocal
exit /b
:openFile
echo 🚀 開啟: %~1
start "" "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\devenv.exe" "%CD%\%~1"
exit /b
執行如下
沒有留言:
張貼留言