简体   繁体   English

Powershell中的批处理setlocal模拟

[英]batch setlocal analogue in Powershell

Imagine that we have such a batch script 想象我们有这样一个批处理脚本

@echo off
setlocal
cd C:\Users\user\Work\SomeWorkingDirectory
endlocal

So, if such script will be started, for example, from C:\\Users\\user\\ , then after script execution current directory in terminal still will be C:\\Users\\user\u003c/code> , not C:\\Users\\user\\Work\\SomeWorkingDirectory . 因此,如果将例如从C:\\Users\\user\\启动此类脚本,则在脚本执行后,终端中的当前目录仍为C:\\Users\\user\u003c/code> ,而不是C:\\Users\\user\\Work\\SomeWorkingDirectory

So, the question is: are there any setlocal / endlocal analogues in Powershell? 因此,问题是:Powershell中是否有任何setlocal / endlocal类似物? Googled it, can't find. 用谷歌搜索,找不到。

PowerShell's scoping rules are different from those of WinBatch. PowerShell的作用域规则与WinBatch的作用域规则不同。

For most variables, they will only be visible within the script or function in which they are defined. 对于大多数变量,它们仅在定义它们的脚本或函数中可见。 Environment variables, eg, $env:Path can be modified, but the modification will only persist for the duration of the PowerShell session. 可以修改环境变量,例如$env:Path ,但是该修改将仅在PowerShell会话期间持续存在。 For persistent changes, and more information about environment variables, see about_Environment_Variables . 有关持久性更改以及有关环境变量的更多信息,请参见about_Environment_Variables

For paths, as you seem to be asking, you can use the Push-Location and Pop-Location cmdlets (by default, aliased to pushd and popd , respectively). 对于路径,您可能会问,可以使用Push-LocationPop-Location cmdlet(默认情况下,别名分别为pushdpopd )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM