Page 1 of 1

How to wrap filename with blanks inside?

Posted: 28 Feb 2024 07:10
by tobwz
In a DOS batch script I wrote a command to start a powershell command:

Code: Select all

Powershell.exe -noprofile -noexit -command "& {D:\tmp\testargs.ps1 %args%}"
As long as the filename does not contain any blanks the command above works.
As soon as it contains blanks I have a problem. The following does not work:

Code: Select all

Powershell.exe -noprofile -noexit -command "& {'D:\tmp\test args.ps1' %args%}"
Command prompt output shows me the following error:
At line:1 char:27
+ & {'D:\tmp\test args.ps1' 'D:\tmp\236 236.pdf'}
+ ~~~~~~~~~~~~~~~~~~~~
Unexpected token ''D:\tmp\236 236.pdf'' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken


How else can I use a filename (and possibly path) with blanks inside?

Re: How to wrap filename with blanks inside?

Posted: 01 Mar 2024 10:13
by jfl
The problem is not the space, but the quotes you added around the pathname of the program. These quotes are indeed necessary because of the space. But when you add them, PowerShell stops considering this object as a reference to a program to execute, and considers it as a string object.
To fix that, and make sure it understands it's a program to be executed, you need to add an additional ampersand ahead of it:

Code: Select all

&'D:\tmp\test args.ps1'
Also, the outside block "&{ }" around the whole PowerShell code is useless. Example:

Code: Select all

C:\JFL\Temp>Powershell.exe -noprofile -command "& {'C:\JFL\Tools\echo args.ps1' one 'a b c' three}"
Au caractère Ligne:1 : 33
+ & {'C:\JFL\Tools\echo args.ps1' one 'a b c' three}
+                                 ~~~
Jeton inattendu « one » dans l’expression ou l’instruction.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken


C:\JFL\Temp>Powershell.exe -noprofile -command "& {&'C:\JFL\Tools\echo args.ps1' one 'a b c' three}"
Arg1 = one
Arg2 = "a b c"
Arg3 = three

C:\JFL\Temp>Powershell.exe -noprofile -command "&'C:\JFL\Tools\echo args.ps1' one 'a b c' three"
Arg1 = one
Arg2 = "a b c"
Arg3 = three

C:\JFL\Temp>
There are lots of traps like this in PowerShell, and this is why I still prefer using Batch where I can. :evil: