Search code examples
powershellcopy-item

Can't get my powershell copy task to work


I'm having some trouble with PS. I'm trying to copy a folder from my computer to a list of other computers on the same network. If I run the command against a machine name by typing out the machine name (destination), PS will copy the folder. If I use the following command, the resulting error is "The network path was not found"

If I do the command with one computer at time, the copying is successful. Like so:

Copy-Item -Path $FileLocation -Destination \\computername\C$

But if I do it this way, I get the error:

$pc | % {copy-item -path $filelocation -destination "\\$_.assetname\C$\"}

Here are the steps taken to get to the line above:

$pc = import-csv desktop\365list.csv

The column header in the csv is AssetName. Then I define the file path to the folder

$FileLocation = c:\\users\<username>\desktop\odt 

"odt" is the name of the folder I'm trying to copy over to the list of computers in the csv

$pc | % {copy-item -path $filelocation -destination "\\$_.assetname\C$\"}

I have also tried without quotes:

$pc | % {copy-item -path $filelocation -destination \\$_.assetname\C$\}

and I get the same error. What am I doing wrong with this simple copy task?


Solution

  • You need to enclose it in a sub expression.

    $pc | Foreach-Object {copy-item -path $filelocation -destination "\\$($_.assetname)\C$\"}
    

    Only the base variable can be expanded without it inside a string. Without the string in a scriptblock it will error. A good way to troubleshoot is to simply output and see if it's what you are expecting

    $pc | Foreach-Object {"\\$($_.assetname)\C$\"}
    

    See this test

    $pc = @'
    assetname
    test
    '@ | ConvertFrom-Csv
    
    $pc | ForEach-Object {"\\$_.assetname\c$"}
    
    \\@{assetname=test}.assetname\c$
    

    Without quotes

    $pc | ForEach-Object {\\$_.assetname\c$}
    
    The network path was not found
    At line:1 char:23
    + $pc | ForEach-Object {\\$_.assetname\c$}
    

    Finally with the subexpression

    $pc | ForEach-Object {"\\$($_.assetname)\c$"}
    
    \\test\c$