I am writing a script that gets the location of a folder on a remote machine from an XML document stored on said remote machine. I want to then copy the folder over to the local PC. Here is the code I currently have:
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
is never populated outside of the Invoke-Command
scriptblock. I have tried using return
, I have tried setting it as a global variable, and I have tried using the Copy-Item
command from within the script block (it kept giving me an access denied error no matter what I changed with Winrm/PSRemoting). Does anyone know how I can populate $logsP
outside of the script block?
Don't collect the parent path in a variable inside the script block. Just let it be echoed to the Success output stream and collect the output of Invoke-Command
in a variable on your local computer.
$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