Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A helpful PowerShell module that lets you move (smallish) files over the clipboard - useful when you have RDP access to a machine but are not allowed to share drives.
function Write-EmbeddedFile
{
param
(
[string]$base64,
[string]$targetFile
)
process
{
$Content = [System.Convert]::FromBase64String($base64)
Set-Content -Path ".\$targetFile" -Value $Content -Encoding Byte
}
}
function Base64Encode-File
{
param
(
[Parameter(Mandatory = $true)]
[string]$file
)
process
{
$c = Get-Content $file -Encoding Byte
return [System.Convert]::ToBase64String($c)
}
}
<#
.Synopsis
Takes data on the clipboard generated by Send-ClipboardFile and turns it back into a disk file.
.Description
The clipboard data is broken up into the original filename, and the Base64-encoded contents. The contents are written
back to disk after decoding. You can override the original filename if required, but the one sent by Send-ClipboardFile will
be used by default
.Parameter alternativeName
If you want the file written to disk with a different name, specify it here. This will replace the file name that was sent
with the file's data.
#>
function Receive-ClipboardFile
{
param(
[string]$alternativeName = $null
)
$clip = Get-Clipboard
$bits = $clip.Split("`b")
if($bits.Length -ne 2)
{
throw "Data error. Expected 2 items of data on clipboard, but got $($bits.Length)"
}
$file = $bits[0]
if($alternativeName -ne $null -and $alternativeName.Length -gt 0)
{
$file = $alternativeName
}
$data = $bits[1]
Write-Host "Receiving file `"$file`" from $($clip.Length) bytes of data"
Write-EmbeddedFile $data $file
}
<#
.Synopsis
Encodes the specified file and saves it as text on the clipboard. Get it back with Receive-ClipboardFile.
.Description
Takes the specified file, and uses Base64 encoding to make it safe to stick onto the clipboard. The data copied includes both
the file name and its contents. This can then be pasted to another location using a shared clipboard or similar, and the Receive-ClipboardFile
command will turn it back into a disk file. Useful for sending a file to a remote machine that you can't share drives with, or that does not
have access to file sharing services like OneDrive.
.Parameter file
The disk file to encode. Must exist, and be readable.
#>
function Send-ClipboardFile
{
param(
[string]$file
)
if(!(Test-Path $file))
{
throw "Specified file '$file' cannot be found"
}
$fileName = Split-Path $file -leaf
$data = Base64Encode-File $file
"$fileName`b$data" | Set-Clipboard
Write-Host "File `"$file`" encoded to clipboard in $($data.Length) bytes"
}
Export-ModuleMember -Function 'Receive-ClipboardFile'
Export-ModuleMember -Function 'Send-ClipboardFile'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment