【问题标题】:How to use a variable that was set on a remote machine, on a local machine如何在本地机器上使用在远程机器上设置的变量
【发布时间】:2019-07-25 19:24:16
【问题描述】:

我正在编写一个脚本,该脚本从存储在远程计算机上的 XML 文档中获取远程计算机上文件夹的位置。然后我想将文件夹复制到本地 PC。这是我目前拥有的代码:

Invoke-Command -Session $TargetSession -ScriptBlock {
    if (Test-Path "$env:USERPROFILE\pathto\XML") {
        [xml]$xml = Get-Content $env:USERPROFILE\pathto\XML
        $XMLNode = $xml.node.containing.file.path.src
        foreach ($Log in $XMLNode) {
            $LogsP = Split-Path -Path $Log -Parent
            $LogsL = Split-Path -Path $Log -Leaf
        }
    } else {
        Write-Host "There is no XML file!"
    }
    Copy-Item -Path "$LogsP" -FromSession $TargetSession -Destination "$env:TEMP" -Force -Recurse -Container

$logsP 永远不会填充到 Invoke-Command 脚本块之外。我尝试使用return,尝试将其设置为全局变量,并尝试在脚本块中使用Copy-Item 命令(无论我使用 Winrm/ PS远程处理)。有谁知道我如何在脚本块之外填充$logsP

【问题讨论】:

    标签: xml powershell remoting copy-item


    【解决方案1】:

    不要在脚本块内的变量中收集父路径。只需让它回显到 Success 输出流,并将 Invoke-Command 的输出收集到本地计算机上的变量中。

    $LogsP = Invoke-Command -Session $TargetSession -ScriptBlock {
        if (Test-Path "$env:USERPROFILE\pathto\XML") {
            [xml]$xml = Get-Content $env:USERPROFILE\pathto\XML
            foreach ($Log in $xml.node.containing.file.path.src) {
                Split-Path -Path $Log -Parent
            }
        }
    }
    
    $LogsP | Copy-Item -FromSession $TargetSession -Destination "$env:TEMP" -Force -Recurse -Container
    

    【讨论】:

    • 哦,我知道你在那里做了什么!我没有意识到我可以将Invoke-Command 设置为一个变量。这很神奇!如果有多个父路径,它将如何工作?只需将其放入数组中并使用foreach 循环?
    • 如果 XML 文档中有多个路径,则 $LogsP 设置为 C:\Some\file\path C:\Some\Other\Path 并在使用 Copy-Item 时出错。这可以通过使用foreach 循环来解决吗?
    • @Excallypurr 如果您的 XML 在单个值中包含多个路径,则需要拆分该字符串以获取单独的路径。
    猜你喜欢
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2022-08-20
    • 2016-04-02
    • 2020-02-11
    相关资源
    最近更新 更多