-replace is cancelling out another request in script

Welcome Forums General PowerShell Q&A -replace is cancelling out another request in script

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

 
Participant
3 years, 10 months ago.

  • Author
    Posts
  • #22235

    Participant
    Points: 0
    Rank: Member

    Hi Everyone!

    I'm very new to PowerShell and been trying to use PS to gather information computer information.

    The command below is to gather Ethernet NIC name and Macaddresses and it's doing it. Awesome!

    Get-WmiObject win32_networkadapter -Filter "adaptertype='ethernet 802.3'" | Select name,macaddress

    But i added a -replace to change the format of the macaddress ":" to "-". Thing is, when i test run it, it is not showing name of the NIC anymore.

    Get-WmiObject win32_networkadapter -Filter "adaptertype='ethernet 802.3'" | Select name,macaddress | foreach {$_.macaddress -replace ":","-"}

    What am I missing? Thanks for in advance!

  • #22236

    Participant
    Points: 60
    Rank: Member

    Hi Kungfumang,

    It's because at the end of the pipeline, you are just telling it to display the mac address. Unless Select is at the end of a pipeline, all it will do is to select the specified properties from the previous action, and pass them through to the next item in the pipeline.

    Instead, you want to do something like this, which uses a calculated property in the format you require.

    Get-WmiObject -Class win32_networkadapter -Filter "adaptertype='ethernet 802.3'" |
    Select-Object -Property name, @{
        Name       = 'MACaddress'
        Expression = {
            $_.macaddress -replace ':', '-'
        }
    }
    
  • #22237

    Participant
    Points: 0
    Rank: Member

    Tim,

    Thank you very much for the very fast response. Your format works perfectly!

The topic ‘-replace is cancelling out another request in script’ is closed to new replies.