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
If you're working with actual files (as opposed to some sort of string data), how about the following?
(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.
asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456
7 - this is the "FIND" command for Powershell
C1234 - this is the "MID" command for Powershell
PC123456 - tada it has found and cut our text
-RavonTUS
The string is a .NET string so you can use .NET methods. In your case:
will return 3, which is the first occurrence of space in the string. For more information see: http://msdn.microsoft.com/en-us/library/system.string.aspx
For your need try something like:
Or you could use regexps:
(has to be adjusted depending on exactly what you need).
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
Another way to do the same thing:
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#
Result: 201011221155.xml