I need to add an object from property into a file path powershell

Viewed 33

I need to get an item from a list of servers, so i have my csv file created.

$servers = Import-Csv C:\Temp\user1\servers.csv 

#Copy Items- Invoke 

$servers = Import-Csv C:\Temp\user1\servers.csv | ForEach-Object {Invoke-Command -ComputerName $_.computername -ScriptBlock { get-item -Path $("\\$_.computername\c$\Program Files\app1\app1.yml") | Copy-Item -Destination "C:\Temp\app1\app1"}} 

It's erroring out because file path '\.computername\c$\Program Files\app1\app1.yml' is not found.

Its detecting the actually computer name in for that parameter, so my guess is my syntax is not set correctly with the $_.computername in the file path. Not sure how I can get the path string to recognize the object in the server.csv file

1 Answers

you try to access a variable $_ from a scriptblock running on a remote computer - use $using to access the variable

$code = {
$comp = $using:computername
get-item -Path $("\\$comp\c$\Program Files\app1\app1.yml") | Copy-Item -Destination "C:\Temp\app1\app1"}
}

$servers = Import-Csv C:\Temp\user1\servers.csv | ForEach-Object {
$computername = $_.computername
Invoke-Command -ComputerName $computername -ScriptBlock $code
}

Btw. by using invoke-command you are establishing a PSR connection to the target machine. Makes no sense then to access the file on the target machine by specifying an UNC path "\$comp\c$\Program Files\app1\app1.yml", you can simply specify the local path: "c:\Program Files\app1\app1.yml" and so you do not need to pass over the computername.

Related