Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: concatenate strings with variables after cmdlet

Tags:

powershell

I often find myself in the situation where I have to concatenate a string with a variable after a cmdlet. For example,

New-Item $archive_path + "logfile.txt" -type file

If I try to run this, PowerShell throws the following error:

New-Item : A positional parameter cannot be found that accepts argument '+'.

Am I not concatenating the string correctly? I'd like to not have to declare another variable before each cmdlet that I do this in (e.g., $logfile = $archive_path + "logfile.txt", and then do New-Item $logfile -type file). Also, I won't always be concatenating a file path.

like image 246
skyline01 Avatar asked Oct 31 '15 00:10

skyline01


1 Answers

You get that error because the PowerShell parser sees $archive_path, +, and "logfile.txt" as three separate parameter arguments, instead of as one string.

Enclose the string concatenation in parentheses, (), to change the order of evaluation:

New-Item ($archive_path + "logfile.txt") -Type file

Or enclose the variable in a subexpression:

New-Item "$($archive_path)logfile.txt" -Type file

You can read about argument mode parsing with Get-Help about_Parsing.

like image 184
Mathias R. Jessen Avatar answered Oct 03 '22 00:10

Mathias R. Jessen