How do I properly handle spaces in file names passed as arguments to a PowerShell script via a SendTo shortcut?

StackOverflow https://stackoverflow.com/questions/14060434

  •  12-12-2021
  •  | 
  •  

Question

I've written a (very) simple script that appends the current date to a given file name in PowerShell, and I've set it up with a SendTo shortcut for easy access.

However, it doesn't handle file names with spaces in them very well. If a file name is "thisFile.txt" it correctly adds the date, making it "thisFile.txt.20121227", but if the file name is "this File.txt" it doesn't work from the SendTo shortcut I've set up.

It does work from the command line for both types of file names, however, and I've been scratching my head trying to figure out why.

This is the snippet of code I've been using:

$enddate = (Get-Date).toString("yyyyMMdd")
$filename = $arg

foreach ($filename in $args) {
    Rename-Item $filename $filename"."$enddate
}

This is in the Target field for the shortcut I've set up:

"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe " -NonInteractive  -WindowStyle Hidden -NoProfile -noexit &"C:\Scripts\adddate.ps1"

OTHER TIPS

You might want to do a little debugging.

I would wager that your filename with spaces is getting split into an array.

In your for loop, write the output of the $filename variable to a file. You might find that you need to add a little logic to your script that says "hey, this doesn't have an extension! i need to append more items in the area until this is a filename with an extension!", or perhaps until "test-path $filename" returns true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top