Help with String Formatting

This topic contains 5 replies, has 5 voices, and was last updated by Profile photo of bd14pb gj bd14pb gj 3 weeks, 6 days ago.

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #53017
    Profile photo of bd14pb gj
    bd14pb gj
    Participant

    Hey All,

    Hoping the community can help with this one. I'm trying to put together a script that pulls the MAC addresses from computers in AD by grabbing the corresponding computer objects IP from DNS and than querying for MAC address. This snippet of my script grabs the MAC address successfully as a string but in doing so, there is either a NULL entry or blank space above the string. This causes issues when I try and pass this as a variable to a parameter in a CMDLET.

    Can someone assist in helping me get the string formatted correctly?

    $macentry=nbtstat -a $computer.hostname | select-string "mac address" | out-string
    $newmac=$macentry -replace ".*=" -replace ",.*"
    $newmac -replace " ", ""

    #53021
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Try running $newmac.Trim() against it to trim off whitespace. That's a method of System.String, if you want to look up more about it on MSDN. If it doesn't have any effect, then you're seeing something other than whitespace, although from here I can't tell you what that would be.

    #53029
    Profile photo of Aaron Hardy
    Aaron Hardy
    Participant

    Sounds like you're needing to Trim() the string of whitespace as the whitespace can cause issues. There may be a more efficient way but you can use:

    $macentry = nbtstat -a $computer.hostname | select-string "mac address" | out-string
    $newmac = $macentry -replace ".*=" -replace ",.*"
    ($newmac -replace " ", "").Trim()
    
    #53035
    Profile photo of Dan Potter
    Dan Potter
    Participant

    Is there a reason you're opting to use nbtstat?

    gwmi -query "Select MACAddress From Win32_NetworkAdapterConfiguration Where IPEnabled = True"

    #53048
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    Since you are using Select-String, you are already using RegEx to match the pattern. Here is a way to uses RegEx groups to get just the MAC address.

    $macentry=nbtstat -a $computer.hostname | Select-String "MAC Address = (?'MACAddress'..-..-..-..-..-..)"
    $macentry.Matches[0].Groups['MACAddress'].value

    With your original code you are getting 3 sets of (Vertical Tab then Linefeed) after your MAC Address

    • This reply was modified 3 weeks, 6 days ago by Profile photo of Curtis Smith Curtis Smith.
    #53053
    Profile photo of bd14pb gj
    bd14pb gj
    Participant

    Curtis,

    That did it for me! I know have the MAC address is proper format. Thanks for that.

    Thanks Everyone

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.