'Copy and paste files through clipboard in Powershell
In the folder E:\Files there are 2 files, which I want to copy and paste into D:\Dest:
E:\Files\
- File1.txt
- File2.txt
Using the keyboard I would simply select the 2 files, push ctrl+c, and in the destination folder D:\Dest\ I then push ctrl+v.
Now I want to achieve this using Powershell. So I copy the files into the clipboard:
Set-Clipboard -Path E:\Files\*
But how to paste those files now into the destination folder? Obviously, I will need Get-Clipboard. But it's not quite clear to me, how to use it, in order to paste the files.
I know I could copy the contents of these 2 files and then by using Set-Content create those files in D:\Dest\ on my own and copy the content into them. But is there any direct way? Because with Set-Clipboard those files already are in the clipboard. They just need to be pasted. I can use ctrl+v and it works. But I want to paste them through Powershell. Any ideas?
Solution 1:[1]
Here's the script I use to paste files/directories:
$fileDrop = get-clipboard -Format FileDropList
if($fileDrop -eq $null)
{
write-host "No files on the clipboard"
return
}
foreach($file in $fileDrop)
{
if($file.Mode.StartsWith("d"))
{
$source = join-path $file.Directory $file.Name
$e = "copy-item -Recurse $source $($file.Name)"
$e
Invoke-Expression $e
}
else
{
$file.Name
$file | copy-item
}
}
Solution 2:[2]
You could use the .NET Clipboard class:
Add-Type -AssemblyName System.Windows.Forms
$files = [System.Collections.Specialized.StringCollection]::new()
$files.Add('YOUR_FILE_PATH_HERE')
[System.Windows.Forms.Clipboard]::SetFileDropList($files)
This copies YOUR_FILE_PATH_HERE to the local clipboard.
You could use this, for example, when you're in a local terminal and need to copy file(s) to a remote session without PowerShell remoting (e.g., RDP or Citrix) without opening the directory in Explorer.
It's a little unwieldy, so if I used it a lot, I'd probably put it in a function like Copy-FileToClipboard and add it to my PowerShell profile.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mike Hillberg |
| Solution 2 |
