PowerShell: Copy-Item within PSSession ignores -Filter -Include -Exclude

Viewed 307

Using the PowerShell command Copy-Item to copy files works fine locally, but when running it in a PSSession, the options -Filter, -Include and -Exclude show no effect while copying files from the remote host to the local machine. I am running PowerShell 5.1 both on the local and the remote machine.

Here, the examples:

  • Local --> local: works fine (i.e. it copies only txt-files)

    Copy-Item -Path C:\run\* -Filter *.txt -Destination C:\test\
    
  • Remote --> local: does not work correctly (disregards from the filter settings and copies all files)

    $sess = New-PSSession -ComputerName <ComputerName> -Credential $cred
    Copy-Item -FromSession $sess -Path C:\run\* -Filter *.txt -Destination C:\test\
    

    The same holds when using -Include *.txt or -Exclude *.csv.

  • Local --> remote: works fine (copiyng only txt-files):

    $sess = New-PSSession -ComputerName <ComputerName> -Credential $cred
    Copy-Item -ToSession $sess -Path C:\run\* -Filter *.txt -Destination C:\test\ 
    

Thanks for any hints on what I am doing wrong!

1 Answers

We all have come to know that with PowerShell there are multiple ways to do X or Y. Why not just use Invoke-Command?

$sess = New-PSSession -ComputerName <ComputerName> -Credential $cred

Invoke-Command -Session $sess -ScriptBlock {
    Copy-Item -Path 'C:\run\*' -Filter '*.txt' -Destination 'C:\test\'
}

Or just directly

Invoke-Command -ComputerName $ServerName -Credential $cred -ScriptBlock { 
    Copy-Item -Path 'C:\run\*' -Filter '*.txt' -Destination 'C:\test\' 
}
Related