0

Trying to get these two to work but keep getting errors. Basically looking to pickup all files from C:\Temp\Test with .txt extension and copy it to Server1 and Server2 D:\Temp\Test.

Doesn't work...

$servers = "Server1","Server2"
$SourcePath = (Get-ChildItem C:\Temp\Test *.txt).Name
$servers | ForEach {
Invoke-Command $servers -ScriptBlock {
$CompName = (Get-WmiObject -Class Win32_ComputerSystem).Name
$DestPath = "\\$CompName\D$\Temp\Test"
Copy-Item $SourcePath -Destination $DestPath -Recurse
}
}
2

1 Answer 1

2

This is a common mistake actually. When you use Invoke-Command to invoke your scriptblock on the remote server it creates a new instance of PowerShell on that remote computer. That new instance of PowerShell has no idea what the $SourcePath variable is, since it was never set in that new instance. To work around this give your scriptblock a parameter, and then supply the value of $SourcePath when you invoke to scriptblock. It can be done like this:

$servers = "Server1","Server2"
$SourcePath = (Get-ChildItem C:\Temp\Test *.txt).Name
$servers | ForEach {
    Invoke-Command $servers -ScriptBlock {
        Param($SourcePath)
        $CompName = (Get-WmiObject -Class Win32_ComputerSystem).Name
        $DestPath = "\\$CompName\D$\Temp\Test"
        Copy-Item $SourcePath -Destination $DestPath -Recurse
    } -ArgumentList $SourcePath
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.