Search code examples
powershellpowershell-3.0powershell-4.0

I have an issue with using Copy-Item and a Veriable for destination


This Might be an easy one. But I can figure out what is going wrong with my simple copy script. I have a shared directory that I am copying items from. I am printing out the destination path to console so I know it is correct But I am receiving a powershell error I do not understand.

Here is my script

#Files to copy
#Get Installers from folder
$APPS = Get-ChildItem \\Server1\shared\APPS -Name 

#ForEach loop to identify and move files
ForEach($APP in $APPS) {
    $dest = "\\Server1\Shared\APPS\$APP"
    #Write-host to see destination path on console
    write-host $dest 
    #copy item from destination path to local directory
    Copy-Item $dest -Destination "c:\apps\"
    
 }

This seems straight forward. But I don't understand why I am receiving the following error

 \\Server1\Shared\APPS\LTCDesktopSetup.exe
Copy-Item : The filename, directory name, or volume label syntax is incorrect.
At C:\Users\computer1\documents\PowerShell\Moving Installer to local drive.ps1:13 char:2
    +     Copy-Item $dest -Destination "c:\apps\"
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Copy-Item], IOException
    + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand

Solution

  • Augusto,

    I'd suggest this syntax:

    $APPS = (Get-ChildItem "\\mybooklive\CMShared\NAS-Downloads" -filter *.exe).FullName
    
    ForEach ($App in $Apps) {
        copy-item "$APP" -Destination "G:\Test\Copy-Test" -Force
    }
    

    or the more compact:

    $APPS = (Get-ChildItem "\\mybooklive\CMShared\NAS-Downloads" -filter *.exe).FullName |
        copy-item -Destination "G:\Test\Copy-Test" -Force
    

    Getting FullName vs Name so you don't have to add the source path back in. Using -Filter so you only get .exe files (this is an assumption from the variable name $Apps). The force will take care of some IO problems like the file already existing.

    HTH Naturally, you'll have to substitute your paths for my test ones.