[powershell] Find character position and update file name

What function might I use to find a character position in a string using PowerShell 2.0.

i.e I would use CHARINDEX or PATINDEX if using SQL Server.

I looked at using the Select-String cmdlet but it doesn't seem to do what I need it to do.

Ultimately I'm looking to find a "_" character in a file name and strip off everything to the following "." .

Example file name 237801_201011221155.xml

Final Solution, The below strips out all characters from and including <_> to <.> for all .xml files in the current directory

Get-Childitem *.xml | Rename-Item -newname `
  { $_.name -replace $_.name.SubString($_.name.IndexOf("_"), `
       $_.name.LastIndexOf(".") - $_.name.IndexOf("_") ),''}

Will end up with 237801.xml

This question is related to powershell powershell-2.0

The answer is


If you split the filename on underscore and dot, you get an array of 3 strings. Join the first and third string, i.e. with index 0 and 2

$x = '237801_201011221155.xml' 
( $x.split('_.')[0] , $x.split('_.')[2] ) -join '.' 

Another way to do the same thing:

'237801_201011221155.xml'.split('_.')[0,2] -join '.'

I know this thread is a bit old but, I was looking for something similar and could not find it. Here's what I came up with. I create a string object using the .Net String class to expose all the methods normally found if using C#

[System.String]$myString
 $myString = "237801_201011221155.xml"
 $startPos = $myString.LastIndexOf("_") + 1 # Do not include the "_" character
 $subString = $myString.Substring($startPos,$myString.Length - $startPos)

Result: 201011221155.xml


If you're working with actual files (as opposed to some sort of string data), how about the following?

$files | % { "$($_.BaseName -replace '_[^_]+$','')$($_.Extension)" }

(or use _.+$ if you want to cut everything from the first underscore.)


If you use Excel, then the command would be Find and MID. Here is what it would look like in Powershell.

 $text = "asdfNAME=PC123456<>Diweursejsfdjiwr"

asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456

 $text.IndexOf("E=")

7 - this is the "FIND" command for Powershell

 $text.substring(10,5)

C1234 - this is the "MID" command for Powershell

 $text.substring($text.IndexOf("E=")+2,8)

PC123456 - tada it has found and cut our text

-RavonTUS