Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate strings with variables in PowerShell?

Tags:

I'm trying to build a file path in PowerShell and the string concatenation seems to be a little funky.

I have a list of folders:

c:\code\MyProj1 c:\code\MyProj2 

I want to get the path to a DLL file here:

c:\code\MyProj1\bin\debug\MyProj1.dll c:\code\MyProj2\bin\debug\MyProj2.dll 

Here's what I'm trying to do:

$buildconfig = "Debug"  Get-ChildItem c:\code | % {     Write-Host $_.FullName + "\" + $buildconfig + "\" + $_ + ".dll" } 

This doesn't work. How can I fix it?

like image 378
Micah Avatar asked Oct 20 '10 13:10

Micah


2 Answers

Try this

Get-ChildItem  | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" } 

In your code,

  1. $build-Config is not a valid variable name.
  2. $.FullName should be $_.FullName
  3. $ should be $_.Name
like image 122
ravikanth Avatar answered Sep 29 '22 01:09

ravikanth


You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.

Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name} 

(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)

like image 37
craika Avatar answered Sep 29 '22 03:09

craika