Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a very large folder of files, of which I organize with a script of mine that refines the files just down to what I need. These items are named similarly to the following examples:

  • Foo (Bar).txt
  • My File (This is) (My File).doc
  • Example (File) (Stuff) (Things).xml

I need to pull every character of the filename after (but including) the first open parenthesis "(" without including the file extension. My desired output for this example would be:

  • (Bar)
  • (This is) (My File)
  • (File) (Stuff) (Things)

I was fiddling with the following line to no avail, and I'm not sure if this would even be the best way of going about this problem:

Get-ChildItem "*" | ForEach-Object { $_.SubString( $_.IndexOf('\(')+1 ) }
share|improve this question
up vote 2 down vote accepted

I think you're close. Firstly, just strip the name of the path and the extension by using the BaseName property of FileInfo. Then just take the substring starting at the index returned by IndexOf:

Get-ChildItem * | ForEach-Object { $_.BaseName.SubString( $_.BaseName.IndexOf('(') ) }

though you may want to add some error handling in cases where there is no (. Perhaps something like this:

Get-ChildItem * | ForEach-Object { $start = $_.BaseName.IndexOf('('); if($start -ge 0){$_.BaseName.SubString( $_.BaseName.IndexOf('(') )} }
share|improve this answer
Well, the upvote is because this is very useful to me; hope the OP finds it the same! – Debra Oct 1 '13 at 6:40
Very helpful! The first line works great, although I'm not sure why you included the "P" in your second line. If you remove it it works great. I've also added "Select -uniq" to the end of the line to remove duplicate entries. What I've ended with is the following, thanks for your help: Get-ChildItem * | ForEach-Object { $start = $_.BaseName.IndexOf(''); if($start -ge 0){$_.BaseName.SubString( $_.BaseName.IndexOf('(') )} else{$ErrorAction} } | Select -uniq – root Oct 1 '13 at 23:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .