0

I am attempting to create something along the lines of the following:

Get-ChildItem -path *.txt* -recurse | $a = $_.Name.Length | Format-Table Name, $a

This is a contrived example, but assume that I wanted to make use of $_Name.Length several times, but substitute $1 or $a in its place.

How do I accomplish this?

1 Answer 1

2

Use an intermediate calculated property:

Get-ChildItem -Path *.txt* -Recurse | Select-Object *, @{ n='a'; e={ $_.Name.Length } } |  
  Format-Table Name, a

Note:

  • This uses a property on the output object rather than a variable to carry the value of interest.

  • In doing so, it changes the type of the objects passed through the pipeline to type [pscustomobject] - a custom type with the added a property. This may or may not be a problem (not a problem with piping to Format-Table).


By contrast, if your plan is to simply process the input objects in a ForEach-Object process block anyway, you can simply define a variable inside that block:

Get-ChildItem -Path *.txt* -Recurse | ForEach-Object { 
  $a=$_.Name; $a.Substring(0, $a.IndexOf('.txt')) 
}

(As an aside: This example command doesn't strictly need a helper variable, because it can more succinctly expressed as:
Get-ChildItem -Path *.txt* -Recurse | ForEach-Object { $_.Name -replace '\.txt.*$' }).

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

5 Comments

The goal is to use it in existing calculated properties, many of which rely on $_.Name.Length without having to type it out repeatedly.
I'm receiving an error, likely because I am not referencing a variable. I'm trying to take $_.Name and bind it to a temp variable -- let's call it $a -- so that I can do something like the following: $a.Substring(0,$a.IndexOf(".apx")) instead of $_Name..Substring(0,$_Name.IndexOf(".apx")).
@toolshed: Note that my solution provides the value of interest as a property value, not as a variable, and that your question asks for a shortcut to $_.Name.Length, not $_.Name. I'm not clear on what you're trying to achieve, so please update you question with an example command that is truly representative of what you're trying to achieve.
@toolshed Maybe it's just an example, but $_.Basename looks easier to me.
@LotPings: .BaseName is generally handy, but look at the wildcard expression: *.txt* would also match files such as file.txt.zip, in which case .BaseName would yield a different result.

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.