Home > Software engineering >  Powershell Substring to pull number from select-string variable but getting error
Powershell Substring to pull number from select-string variable but getting error

Time:06-11

So I run this first set of commands and everything works fine, it returns "com".

$subdomain = "USA.website.com"
$firstref = $subdomain.IndexOf(".")
$lastref = $subdomain.LastIndexOf(".")
$subdomain.Substring($lastref 1)

If I run this

$firstref = $global:Order.IndexOf(".")
$lastref = $global:Order.LastIndexOf("#")
$global:Order.Substring($lastref 1)

I get this error

Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo] does not contain a method named 'IndexOf'.
At line:1 char:1
  $firstref = $global:Order.IndexOf(".")
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidOperation: (:) [], RuntimeException
      FullyQualifiedErrorId : MethodNotFound

$global:Order comes from a select-string that contains this

PS C:\Windows\system32> $global:Order

C:\temp1\A1\{A114E31A-7A77-4F17-BD6E-74B8E85C9739}.eml:17:New Order: #1820


PS C:\Windows\system32>

Is there something different about a global variable? Thats what the error would suggest. Or is it the white space in the variable? What I'm ultimately trying to achieve is getting that order number at the end of the line.

CodePudding user response:

Select-String outputs an instance of MatchInfo, this instance doesn't have a .IndexOf(..) method same goes for .LastIndexOf(..) and .SubString(..):

   TypeName: Microsoft.PowerShell.Commands.MatchInfo

Name               MemberType Definition
----               ---------- ----------
Equals             Method     bool Equals(System.Object obj)
GetHashCode        Method     int GetHashCode()
GetType            Method     type GetType()
RelativePath       Method     string RelativePath(string directory)
ToEmphasizedString Method     string ToEmphasizedString(string directory)
ToString           Method     string ToString(), string ToString(string directory)

This is what the error message you were getting is telling you basically.

What you see in the console as output from Select-String is actually the string representation of the object, .ToString() in Windows PowerShell and .ToEmphasizedString(String) in PowerShell Core.

If you want to reference the line where the pattern was matched you can refer to the .Line property from this instance:

$Order.Line.IndexOf(".")
$Order.Line.LastIndexOf.IndexOf("#")
$Order.Line.Substring($lastref   1)

As aside, in most cases, you can use a $script: scoped variable instead of a $global: scoped one. See about_Scopes for more info.

  • Related