因为批处理文件(.bat
, .cmd
)运行在子进程 (via cmd.exe
),你从根本上无法改变PowerShell 的当前目录.
- 这适用于all在子进程中运行的调用,即对所有外部程序的调用以及对除 PowerShell 本身之外的脚本引擎解释的脚本的调用。
- 虽然子进程' 工作目录已更改,这对caller(父进程),并且没有内置机制允许给定进程更改其父进程的工作目录(这将是一个危险的功能)。
下一个最好的事情是做你的.bat
file 回声(输出)所需工作目录的路径并将结果传递给 PowerShellSet-Location https://learn.microsoft.com/powershell/module/microsoft.powershell.management/set-location cmdlet.
# Assuming that `.\changeDir.bat` now *echoes* the path of the desired dir.
Set-Location -LiteralPath (.\changeDir.bat)
一个简化的示例,通过cmd /c
call:
Set-Location -LiteralPath (cmd /c 'echo %TEMP%')
如果您正在寻找一个导航到给定目录的简短便捷命令,不要使用批处理文件 -use a 电源外壳脚本或函数反而;例如。:
function myDir { Set-Location -LiteralPath C:\Users\ET\test\myDir }
执行中myDir
然后导航到指定目录。
You can 将此功能添加到您的$PROFILE file https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Profiles,从而自动使其可用于future会议也.
你可以打开$PROFILE
在文本编辑器中或以编程方式添加该函数,如下所示,这可确保按需创建文件及其父目录:
# Make sure the $PROFILE file exists.
If (-not (Test-Path $PROFILE)) { $null = New-Item -Force $PROFILE }
# Append the function definition to it.
@'
function myDir { Set-Location -LiteralPath C:\Users\ET\test\myDir }
'@ | Add-Content $PROFILE