You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

启动PowerShell远程会话后如何自动切换工作目录?

解决PowerShell远程会话自动切换工作目录的问题

你遇到的核心问题是:Enter-PSSession 启动的是交互式远程会话,一旦进入这个会话,本地脚本的执行会暂停,直到你退出远程会话(执行Exit-PSSession)。所以你写在Enter-PSSession之后的cd或Set-Location命令,只会在你退出远程会话后在本地执行,根本不会在远程环境中运行,自然无法切换远程目录。

方案一:通过初始会话状态指定远程会话的起始目录

直接在启动远程会话时预先设置初始工作目录,进入会话后会自动处于目标路径下。修改后的脚本如下:

Clear-Host
$computer = Read-Host "enter remote computer name"
$softwareServer = "\\servername\software"

cd $softwareServer
Get-ChildItem .\ | Format-Table Name
$software = Read-Host "enter software name"

$softwarePath = "$softwareServer\$software"
$softwareDestination = "\\$computer\c$\software\$software"

# 避免目录已存在时报错,添加错误处理参数
mkdir \\$computer\c$\software\$software -ErrorAction SilentlyContinue
robocopy $softwarePath $softwareDestination /MIR

# 创建初始会话状态对象,设置远程会话的起始工作目录
$initialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$initialSessionState.ExecutionContext.SessionState.Path.SetLocation("c:\software\$software")

# 启动远程会话并应用初始目录设置
Enter-PSSession -Computer $computer -InitialSessionState $initialSessionState

方案二:重用持久会话预先切换目录

如果需要先执行远程操作再进入交互式会话,可以先创建持久远程会话,在其中完成目录切换后再进入交互式会话:

Clear-Host
$computer = Read-Host "enter remote computer name"
$softwareServer = "\\servername\software"

cd $softwareServer
Get-ChildItem .\ | Format-Table Name
$software = Read-Host "enter software name"

$softwarePath = "$softwareServer\$software"
$softwareDestination = "\\$computer\c$\software\$software"

mkdir \\$computer\c$\software\$software -ErrorAction SilentlyContinue
robocopy $softwarePath $softwareDestination /MIR

# 创建持久远程会话
$remoteSession = New-PSSession -Computer $computer

# 在持久会话中执行目录切换
Invoke-Command -Session $remoteSession -ScriptBlock {
    Set-Location "c:\software\$using:software"
}

# 进入已创建的持久会话(此时已处于目标目录)
Enter-PSSession -Session $remoteSession

进入远程会话后,直接执行Get-ChildItem就能看到目标目录下的文件,无需手动切换路径。

内容的提问来源于stack exchange,提问作者IT4Gov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:02:34