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

0

6 Answers

The string is a .NET string so you can use .NET methods. In your case:

$index = "The string".IndexOf(" ") 

will return 3, which is the first occurrence of space in the string. For more information see:

For your need try something like:

$s.SubString($s.IndexOf("_") + 1, $s.LastIndexOf(".") - $s.IndexOf("_") - 1) 

Or you could use regexps:

if ($s -Match '(_)(.*)(\.)[^.]*$') { $matches[2] } 

(has to be adjusted depending on exactly what you need).

1

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

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 - Ta-da! It has found and cut our text.

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

2

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

Solution by OP migrated from question to an answer:

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like