26

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?

1
  • 4
    Be careful about using Write-Host - it only writes to the host console. You can't capture that output into a variable. If you simply remove Write-Host and have just the string sitting there it will 1) implicitly use Write-Output and 2) you will be able to capture that output to a variable e.g. gci c:\code | %{$_.FullName+"`$build-config\$($_.basename)\.dll" Commented Oct 20, 2010 at 14:33

4 Answers 4

31

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
Sign up to request clarification or add additional context in comments.

2 Comments

$_.Name includes the extension. I suspect the intent was to replace the current extension with .dll instead of tacking on an additional .dll. :-)
He says he has a list of folders. So, $_.Name should be OK. Otherwise, $_.BaseName is OK.
14

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

Comments

7

Try the Join-Path cmdlet:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.