Search code examples
powershellvariablessubstring

Using PowerShell, how can I use Substring to extract the computer name from output


I am new to PowerShell but I found I can use Substring to count to the right or left of a string within a variable. It appears though it is not supported for the output I am receiving. I am hoping someone can point me in the right direction. Thank you for any help.

Code to retrieve the computer name.

$compname = WmiObject -class Win32_ComputerSystem | Select-Object Name
$compname
$compname.Substring(9,0)

Here is the result and error:

Name

Computer-PC Method invocation failed because [Selected.System.Management.ManagementObject] does not contain a method named 'Substring'. At line:3 char:1

  • $compname.Substring(9,0)
  •   + CategoryInfo          : InvalidOperation: (Substring:String) [], RuntimeException
      + FullyQualifiedErrorId : MethodNotFound
    

Solution

  • This error occurs because you're trying to use the Substring method on an object.

    Take a look, if i do the same query that you did, it returns me an object with "Name" property:

    enter image description here

    And as the powershell error shows, you cannot call the substring method directly to an object. You must do it on a string, in this case, the property name. To solve you problem, you just need to call "Name" property in your query. Something like this:

    $computerName = (Get-WmiObject Win32_ComputerSystem).Name
    

    After that, you will be able to use "Substring" method because that query returns a string:

    enter image description here

    If any other problem occurs, i will be glad to help you :)