5

Here is a sample PowerShell script (it doesn't work) that illustrates what I want to do:

$BuildRoot = '_Provided from script parameter_'
$Files = 'a.dll', 'b.dll', 'c.dll'
$BuiltFiles = $Files | Join-Path $BuildRoot

I have a list of filenames, and a directory name, and I want to join them all together, simple. The problem is that this doesn't work because the Join-Path parameter -ChildPath accepts input from the pipeline ByPropertyName, so the following error is reported:

The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

I can "fix" it by changing the line to the following:

$BuiltFiles = $Files | Select @{ Name = "ChildPath"; Expression = {$_}} | join-path $BuildRoot 

Basically, the select operation is turning the object into a property value. This works, but it introduces a lot of syntactic noise to accomplish something that seems so trivial. If this is the only way to do it, so be it, but I'd like to make this script maintainable for people in the future, and this is a little hard to grok at first glance.

Is there a cleaner way to accomplish what I'm trying to do here?

1 Answer 1

6

You can accomplish this a little easier like so:

$Files = 'a.dll', 'b.dll', 'c.dll'
$Files | Join-Path $BuildRoot -ChildPath {$_}

Note: you don't want to put {} around the files. That creates a scriptblock in PowerShell which is essentially an anonymous function. Also, when a parameter is pipeline bound you can use the trick of supplying a scriptblock ({}) where $_ is defined in that scriptblock to be the current pipeline object.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I knew I was doing something wrong. I actually tried this, but with -ChildPath $_ not -ChildPath {$_}, which gave the same error. Yeah, the curly braces on the file list were a transcription error.

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.