PowerShell Clipboard Copy

If you don't know the kinds of things you can do with PowerShell, you might be missing out on a very inexpensive way to get odd tasks done.

For example, let's say I want a list of non-empty files in a directory, sorted by biggest file first, such that I can paste it into some program.

The first thing to do is get the list of files. Easy enough.

PS > $dirname = "C:\mydir"
PS > dir $dirname -file

    Directory: C:\mydir


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        12/9/2019  11:59 PM             42 ImageResizer1.cache
-a----        12/9/2019  11:59 PM          10843 ImageResizerBig.cache
-a----        12/9/2019  11:59 PM              0 Temporary1.cs
-a----        12/9/2019  11:59 PM              0 Temporary2.cs
-a----        12/9/2019  11:59 PM              0 Temporary3.cs

Next, let's filter out the ones that are empty.

PS > dir $dirname -file | where Length -ne 0


    Directory: C:\mydir


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        12/9/2019  11:59 PM             42 ImageResizer1.cache
-a----        12/9/2019  11:59 PM          10843 ImageResizerBig.cache

Note that I'm using Where-Object in its shorthand form. If your command of choice has a -Filter parameter, that will typically be more efficient.

OK, sorting time.

PS > dir $dirname -file | where Length -ne 0 |
     sort -Descending Length


    Directory: C:\mydir


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        12/9/2019  11:59 PM          10843 ImageResizerBig.cache
-a----        12/9/2019  11:59 PM             42 ImageResizer1.cache

Almost there. Now we'll grab the name, which is all we care about in this exercise.

PS > dir $dirname -file | where Length -ne 0 |
     sort -Descending Length | select Name

Name
----
ImageResizerBig.cache
ImageResizer1.cache

Wait... I don't want that property header, I just want the file names in the output! We can replace the select with a for-each command.

PS > dir $dirname -file | where Length -ne 0 |
     sort -Descending Length | ForEach-Object {$_.Name}
ImageResizerBig.cache
ImageResizer1.cache

Ah, much better. All that's left now is to use the old clip command to copy the output into the system clipboard. This gets a lot more boring to show, however, because there is no output at this point.

PS > dir $dirname -file | where Length -ne 0 |
     sort -Descending Length | ForEach-Object {$_.Name} |
     clip

At this point, I can simply paste my pretty lines over into whatever program I need them to be in (say, emacs or vscode).

Happy pipelining!

P.S.: there is a bunch of PowerShell line breaking in this post - see PowerShell Code Breaks: Break Line, Not Code to become an expert!

Tags:  powershell

Home