Powershell InStr() and Mid()

First of all, PowerShell does not have an InStr() or Mid() function, at least version one does not.
I was trying to extract the Group name from the Common Name in AD and I wanted
everything between the first = sign and the first “,” comma. (I know there are other ways)
So I found that in Powershell you can get the first position of a character by using indexof() like so:

$b = $a.indexof("="     # so the first = is at character 9

I don’t want the equal sign so I add 1

$b = $b + 1

Next I get the index of the first comma.

$c = $a.indexof(",")

Then I get the number of characters between $c and $b

$d = $c - $b

Finally I get the substring I wanted:
The substring starts at the first character, in this case $b and then includes
the number of characters in your substring, in this case $d. 

$e = $a.substring($b,$d)

And here is my MID function:

Function MID($path) {
$b = $a.indexof("=")
$b = $b + 1
$c = $a.indexof(",")
$d = $c - $b
$e = $a.substring($b,$d)
$ws.Cells.Item($row,4) = $e      #This puts my substring in an Excel Spreadsheet in column 4

3 thoughts on “Powershell InStr() and Mid()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s