Trim all but last 5 of serial number

Welcome Forums General PowerShell Q&A Trim all but last 5 of serial number

This topic contains 6 replies, has 6 voices, and was last updated by

 
Participant
3 years ago.

  • Author
    Posts
  • #31323

    Participant
    Points: 0
    Rank: Member

    Sorry for the newb question but I am really stuck here. I am trying to use

    $SERIAL = (Get-WmiObject win32_bios).serialnumber

    Which returns to me something like "MXL1160602"

    All I need is the "60602"

    I have tried all sorts of trims and replaces and I can not get it to give me the output I want.

    I am not getting any errors, when I run the command with a trim or replace it goes through but it still gives me the whole result. The only thing I have found to work so far is $serial -replace "MXL", ""

  • #31325

    Participant
    Points: 1
    Rank: Member

    $SERIAL.substring($SERIAL.length – 6, 6)

    BTW. Your title says trim all but the last six. Your example shows only the last five.

  • #31327

    Member
    Points: 0
    Rank: Member

    I'd do this: "MXL1160602" -replace '.*?(?=.{1,6}$)'

    But then again, I'm one of those weird people who likes to use regex. 😛

    (The advantage, though, is that this works regardless of the length of the string. Using String.SubString() will throw an exception if the string is fewer than 6 characters, unless you add a bit of extra code to check for that condition.)

  • #31328

    Member
    Points: 0
    Rank: Member

    Another option that works regardless of length:

    New-Object string (,@($serial.ToCharArray() | Select-Object -Last 6))

    Or, in PowerShell v5:

    [string]::new(@($serial.ToCharArray() | Select-Object -Last 6))

  • #31335

    Participant
    Points: 5
    Rank: Member

    Another option that works regardless of length:

    $Serial.Substring( [math]::Max( 0, $Serial.Length – 6 ) )

  • #31356

    Participant
    Points: 2
    Rank: Member

    here is my attempt

    [string]$serial = $serial[-5..-1]

  • #31397

    Participant
    Points: 0
    Rank: Member

    My question is does the serial number data being returned need to be cleaned first?
    I gathered serial numbers yesterday and they all had extra characters at the end (5 spaces).

    Are you collecting serial numbers from one or many pcs?

The topic ‘Trim all but last 5 of serial number’ is closed to new replies.