Reputation: 11
$Computers = Get-Content "C:\TEMP\MSGLOG\COPY.txt"
ForEach ($computer in $computers)
{
Invoke-Command -ComputerName $computer -ScriptBlock {
Copy-Item "C:\\Program Files (x86)\\DST\\messaging*.log" -Destination "MYMACHINE\temp\MSGLOG\$Computer\"
}
}
So what I am trying to do its copy logs from ~400computers onto my machine. Each computer is using a date naming format for these logs so I want to copy these file into a folder named after what computer they came from but after many many attempts I cannot figure this out.
Upvotes: 1
Views: 475
Reputation: 11264
If you are using PowerShell 5.1 on your host and your remotes you can use Copy-Item
with its FromSession
or ToSession
parameters. Example from microsoft:
$Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\PattiFul"
Copy-Item "C:\MyRemoteData\test.log" -Destination "D:\MyLocalData\" -FromSession $Session
Upvotes: 0
Reputation: 28993
$computer
is defined on your local computer, but the scriptblock runs on the remote computer. When the remote computer tries to use $computer
it gets an empty string.
You either need the $using:computer
form which will bring the value into the scriptblock and over to the remote computer:
$Computers = Get-Content "C:\TEMP\MSGLOG\COPY.txt"
ForEach ($computer in $computers)
{
Invoke-Command -ComputerName $computer -ScriptBlock {
Copy-Item "C:\Program Files (x86)\DST\messaging*.log" -Destination "\\MYMACHINE\temp\MSGLOG\$using:Computer\"
}
}
or you need a variable which the remote computer has already, like $env:COMPUTERNAME
.
Upvotes: 1
Reputation: 1640
I don't see a need to Invoke-Command
in this situation. You should be able to copy from the \\hostname\C$\.
Ex (Untested):
$Computers = Get-Content "C:\TEMP\MSGLOG\COPY.txt"
$MyMachine = "myMachine"
foreach($Computer in $Computers)
{
Copy-Item -Path "\\$Computer\C$\Program Files (x86)\DST\" -Include "messaging*.log" -Destination "\\$MyMachine\temp\MSGLOG\$Computer\" -Verbose -WhatIf
}
If that gives you the results you are looking for, just remove -whatif
and run again.
Note: Your example shows the destination to be a share. From the name of MyMachine
I would assume this is local. If so, change the -Destination
to a local path (just to avoid unnecessary slowdown) . Also, included -verbose
in order to print what it is doing during the Copy-Item
process
Upvotes: 1