We help IT Professionals succeed at work.
Get Started

Powershell: Extra blank lines in pipeline to CLIP command?

Bill Prew
Bill Prew asked
Last Modified: 2020-03-09
I'm trying to get a file path and place it into the clipboard using Powershell.  Below is what I have, and while it likely could be optimized, it seems to be finding a single file path as I desire.  But the output that ends up in the clipboard includes some extra blank lines above and below the actual file path I want.  I've tried a number of ways to try and remove these with no success, so looking for help.

For background I'm trying to query the Windows recently used files and pull out the single most recent one that was for a *.pdf or *.png file.  That logic seems to be working (feel free to suggest improvements), but the problem is the result file path has blank lines above and below in the clipboard after this runs.

I may be mixing up objects and strings (still rooted in a DOS CMD background) or maybe there is something else involved.

$WScript = New-Object -ComObject WScript.Shell; Get-ChildItem -Path "$env:APPDATA\Microsoft\Windows\Recent\*.lnk" | Sort-Object -Property LastWriteTime -Descending | ForEach-Object {$WScript.CreateShortcut($_.FullName).TargetPath} | Select-String -Pattern '\.(pdf|png)$' | Select-Object -First 1 | Clip

Open in new window

Watch Question
Most Valuable Expert 2019
Most Valuable Expert 2018
This problem has been solved!
Unlock 2 Answers and 7 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE