首页 > 解决方案 > 如何在本地机器上使用在远程机器上设置的变量

问题描述

我正在编写一个脚本,该脚本从存储在远程机器上的 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/PSRemoting 进行什么更改,它都会一直给我一个拒绝访问错误)。有谁知道我如何$logsP在脚本块之外填充?

标签: xmlpowershellremotingcopy-item

解决方案


不要在脚本块内的变量中收集父路径。只需让它回显到 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

推荐阅读