gpt4 book ai didi

powershell - Powershell脚本更改父Powershell的目录

转载 作者:行者123 更新时间:2023-12-03 00:01:23 25 4
gpt4 key购买 nike

当运行通过cd(或set-location / push-location / etc。)更改目录的Powershell脚本时,运行该脚本的控制台也将终止于该目录中。

例:
script.ps1

cd c:\tmp
# do stuff

如果我从 c:\users\me运行它,我最终会在 c:\tmp中运行。
PS C:\users\me> .\script.ps1
PS C:\tmp> |

现在我知道我可以使用 push-location,以后再使用 pop-location。但是,如果脚本在中间某个位置停止(通过Exit),则此操作将无效。

我该如何解决?为什么脚本没有自己的位置堆栈?

最佳答案

您可以始终使用Try/Catch/Finally。将当前目录路径设置为变量,然后将cd c:\tmp设置为Try之前,并将目录更改为Finally中的变量?

示例1

$path = (Get-Item -Path ".\" -Verbose).FullName
cd c:\temp
Try
{
#Do stuff
#exit is fine to use
#this will output the directory it is in, just to show you it works
Write-Host (Get-Item -Path ".\" -Verbose).FullName
}
Catch [system.exception]
{
#error logging
}
Finally
{
cd $path
}

示例2使用popdpushd
pushd c:\temp
Try
{
#Do stuff
#exit is fine to use
#this will output the directory it is in, just to show you it works
Write-Host (Get-Item -Path ".\" -Verbose).FullName
}
Catch [system.exception]
{
#error logging
}
Finally
{
popd
}

我还建议您查看arco444的建议,即通过 -File参数调用powershell脚本。根据可能作为选项工作的方案。

关于powershell - Powershell脚本更改父Powershell的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27529662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com