Micah
Micah

Reputation: 116170

How do I concatenate strings with variables in PowerShell?

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?

Upvotes: 26

Views: 104620

Answers (4)

craika
craika

Reputation: 1162

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.)

Upvotes: 14

Shay Levy
Shay Levy

Reputation: 126902

Try the Join-Path cmdlet:

Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
    Join-Path -Path  $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)" 
}

Upvotes: 7

Jacob Ballard
Jacob Ballard

Reputation: 1

This will get all dll files and filter ones that match a regex of your directory structure.

Get-ChildItem C:\code -Recurse -filter "*.dll" | where { $_.directory -match 'C:\\code\\myproj.\\bin\\debug'}

If you just want the path, not the object you can add | select fullname to the end like this:

Get-ChildItem C:\code -Recurse -filter "*.dll" | where { $_.directory -match 'C:\\code\\myproj.\\bin\\debug'} | select fullname

Upvotes: 0

ravikanth
ravikanth

Reputation: 25820

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

Upvotes: 31

Related Questions