【问题标题】:Powershell test-path issue: Checking if folder exists on serverPowershell测试路径问题:检查服务器上是否存在文件夹
【发布时间】:2014-01-28 21:18:43
【问题描述】:

我在 ServerA 上有一个 powershell 脚本 (test.ps1)。所有脚本应该做的是检查服务器上是否存在文件夹。我正在从客户端(在同一网络内)执行脚本

test.ps1

test-path E:\automation
# returns whether this folder exists on ServerA

我正在从 ComputerB 的 powershell 调用该脚本。

PS > pushd \\serverA\scripts
PS > .\test.ps1

输出:

False

预期输出:

True

问题:

The script is trying to locate the folder on the "local system" (ComputerB) rather than ServerA

【问题讨论】:

    标签: powershell directory remote-server


    【解决方案1】:

    您是否尝试过 powershell 远程处理:

    输入-PSSession -ComputerName ServerA

    这将允许在 ServerA 上运行 powershell 命令

    【讨论】:

    • 我认为 pushd 会这样做。谢谢。会试试的。
    • Pushd 会记住您移动到的路径。
    • 所以我们在计算机 B 上运行 Enter-PSSession 命令,对吗?
    • 正确。您需要在 ServerA 上启用 psremoting
    • @Chriseyre2000, pushd 记住您 移动的路径。所以你可以稍后popd 到初始位置。但一般来说,是的,它是cd,带有一些附加功能。
    【解决方案2】:

    这应该有效:

    invoke-command \\serverA\scripts\test.ps1 -computername serverB

    【讨论】:

    • 如何将参数传递给这个脚本 (test.ps1)?
    【解决方案3】:

    你可以用 PSSession 做到这一点。我的工作代码:

    $ip = "<server ip / dns name>"
    $user = "<your user name>"
    $s = New-PSSession -ComputerName $ip -Credential $user
    
    $serverTestFolder = "c:\"
    
    if (Invoke-Command -Session $s -ScriptBlock {Test-Path -path $args[0]} -ArgumentList $serverTestFolder) {
        # here you are when folder exist on remote server
    }
    

    重要的是,您需要通过ArgumentList 将变量$serverTestFolder 作为参数传递,然后通过$args 使用它([0] 是参数在ArgumentList 中的位置)。

    【讨论】:

      【解决方案4】:
      Test-Path "filesystem::\\\Srv\share"
      

      【讨论】:

      • 不共享怎么办?
      • 请添加描述如何解决问题。 How to Answer
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      相关资源
      最近更新 更多