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

PowerShell PSSession中执行GCI提示路径不存在的问题及解决方法

问题描述

编写脚本时,使用Enter-PSSession连接远程服务器后执行gci命令,本地路径提示不存在,但手动进入会话后用FQDN格式的UNC路径却能正常返回结果。

示例代码:

Enter-PSSession server1 
gci 'c:\inetpub\mailroot\Queue'
gci '\\server1.domain.com\c$\inetpub\mailroot\Queue'

执行返回结果:

gci : Cannot find path 'C:\inetpub\mailroot\Queue' because it does not exist.
......
Directory: \\server1.domain.com\c$\inetpub\mailroot\Queue
insert folder contents here
原因分析

Enter-PSSession是交互式远程会话命令,在脚本中直接执行时,后续的gci 'c:\...'并不会在远程会话中运行,而是依然在本地PowerShell环境执行——本地没有对应路径,所以报错。而UNC路径\\server1.domain.com\c$...是通过SMB协议直接访问远程共享,不需要依赖PSSession上下文,因此能正常返回结果。

解决方法

要让脚本在远程会话中执行命令,推荐两种方式:

方式1:用Invoke-Command批量执行远程命令

无需进入交互式会话,直接指定远程服务器和要执行的脚本块:

Invoke-Command -ComputerName server1 -ScriptBlock {
    gci 'c:\inetpub\mailroot\Queue'
}

方式2:给Enter-PSSession传入脚本块(适合单条/少量命令)

如果需要基于Enter-PSSession执行命令,可通过-ScriptBlock参数直接指定远程执行的内容:

Enter-PSSession server1 -ScriptBlock {
    gci 'c:\inetpub\mailroot\Queue'
}

另外,若有大量命令需执行,可将命令保存为本地脚本文件,再通过Invoke-Command远程调用:

Invoke-Command -ComputerName server1 -FilePath .\RemoteScript.ps1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:54:06