Reputation: 19
I need to change the encoding of a file from UTF8-BOM to UTF8 different files where the date is different. I have a variable with the Data that I need but I have problems passing that variable to the Get-Content param.
$Today = Get-Date -Format "yyyyMMdd"
Get-Content 'D:\Folder_1\Test_file.'+$(${Today})+'.csv' | Set-Content -Encoding Ascii 'D:\Folder_2\Test_file.'+$(${Today})+'.csv'
The file names are "Test_file.20220923.csv" for example.
The error:
Get-Content : A positional parameter cannot be found that accepts argument '+20220923+.
Upvotes: 0
Views: 333
Reputation: 437833
'D:\Folder_1\Test_file.'+$(${Today})+'.csv'
is an expression (a string concatenation via the +
operator).
In order to pass an expression as an argument to a command, you must enclose it in (...)
, the grouping operator.[1]
Therefore (applies analogously to your Set-Content
call):
Get-Content ('D:\Folder_1\Test_file.'+${Today}+'.csv')
Note that I've omitted the unnecessary use of $(...)
, the subexpression operator, which is typically only needed inside expandable (double-quoted) string ("..."
), and then only for embedding expressions or commands (a variable reference such as $Today
by itself can be embedded as-is).
The equivalent command using an expandable string:
Get-Content "D:\Folder_1\Test_file.${Today}.csv"
As for what you tried:
# WRONG: Passes *two* arguments.
Get-Content 'D:\Folder_1\Test_file.'+$(${Today})+'.csv'
Even though 'D:\Folder_1\Test_file.'+$(${Today})+'.csv'
contains no spaces, PowerShell breaks this compound token into two arguments, verbatim D:\Folder_1\Test_file.
and (for instance) verbatim +20220923+.csv
.[2]
It is the latter, i.e. the extra positional argument causes Get-Content
to report an error, because it only supports one positional argument (which binds to its -Path
parameter).
[1] $(...)
is often seen in practice instead, but $(...)
is only ever needed in two cases: (a) to embed entire statement(s), notably loops and conditionals, in another statement, and (b) to embed an expression, command, or statement(s) inside "..."
, an expandable (interpolating) string. Just (...)
is enough to pass a single command or expression as a command argument. While not likely, the unnecessary use of $(...)
can have side effects - see this answer.
[2] In case you're wondering how a compound token such as 'D:\Folder_1\Test_file.'+${Today}+'.csv'
is parsed and results in these two arguments, see this answer.
Upvotes: 1