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
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: http://msdn.microsoft.com/en-us/library/system.string.aspx
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).
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With