'Powershell Copy-Item in a loop as job
Im trying to copy a file to a lot of computers using jobs with powershell:
$computers = Get-Content computers.txt
ForEach($computer in $computers)
{
Start-Job -ScriptBlock{Copy-Item "\\\server1\ccmc\file.exe" -Destination "\\\\$computer\c$\windows\temp" -Force}
}
but im having Problems with "-Destination" powershell gives me following error:
Der angegebene Pfadname ist ungültig. -> German for invalid pathname
+ CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand
+ PSComputerName : localhost
when i manually put in the computername in "-destination" like "\\pc1\c$..." it works just fine
Also if i try it without "Start-Job -Scriptblock{}" it works too
ISE Powershell shows correct computername in $computer during runtime
Solution 1:[1]
Powershell jobs run as a separate instance of powershell, so they don't get your variables unless you use -InputObject or -ArgumentList. I like to use -Verbose or -WhatIf on commands to troubleshoot what actually ran:
$computername = 'Server01'
$job = start-job -InputObject $computername -ScriptBlock {
Copy-Item -Path "\\server1\ccmc\file.exe" -Destination "\\$computer\c$\windows\temp" -Verbose
}
sleep 3
# return the output of a specific job
$job.ChildJobs[0]|Format-List Error,Verbose
Output example:
# Working normally:
Error : {}
Verbose : {Performing the operation "Copy File" on target "Item: \\server1\ccmc\file.exe
Destination: \\Server01\c$\windows\temp\file.exe".}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cpt.Whale |
