Copy Filenames to Clipboard with PowerShell

Have you ever wanted to copy a large amount of data to the Windows clipboard, but haven’t known quite how to do it? How about this scenario: you have a folder full of files, and you want to get a list of the files’ full names / paths. That’s pretty easy to do with a simple Get-ChildItem PowerShell command, but how do you then get the data into say, an e-mail, or paste it into a file? Sometimes it’s just easiest to have the data copied to the Windows clipboard for a more arbitrary usage.

This simple PowerShell script will take a folder path and copy all of the file paths to the Windows clipboard.

Important: The Windows clipboard requires that the application be running in Single-Threaded Apartment (STA) mode, so if you’re using PowerShell v2, please be sure to run PowerShell with the –STA parameter. If you use Multi-Threaded Apartment (MTA), the [Clipboard]::SetText() static method will fail.

[cc lang=”powershell”]
function Copy-FileNamesToClipboard {
# The CmdletBinding() attribute

# Define parameters for the PowerShell v2 advanced function
param (
# Define a mandatory parameter called Path, which will be the path to gather files from
[Parameter(Mandatory = $true)]
[string] $Path

process {
# Load the Presentation Core assembly, which contains the System.Windows.Clipboard class

# Initialize the text variable to an empty string
$text = [string]::Empty;

# Get a list of files in the specified directory
$FileList = Get-ChildItem -Path $Path;

# For each file in the directory, add the file path and a new line to $text
foreach ($File in $FileList) {
$text += (“{0}`n” -f $File.FullName);

# Set the Clipboard text to the string we just got

Copy-FileNamesToClipboard -Path c:\Users\Trevor\Documents\;