Reputation: 73
I am looking for a script that would add "-" after every two digits of a MAC Address. There is already a script here that fixes this.
$macs = Get-Content C:\Users\metho\Desktop\mac.txt
$output = foreach ($mac in $macs){
$mac.insert(2,"-").insert(5,"-").insert(8,"-").insert(11,"-").insert(14,"-")
}
$output | Out-File C:\Users\nmetho\Desktop\mac1.txt
The problem I have is that I am using a CSV file that contains four columns and therefore the above script does not work for me.
Description, MacAddress, IPAddess, Location
CJ0001, 00351AC0353C, 192.168.2.5, Room1
I am looking to modify only the MacAddress
field so that I get the "Mac Address" in this format 00-35-1A-C0-35-3C.
Can I use this script to achieve what I am looking for or do I need to start from scratch?
Upvotes: 1
Views: 2774
Reputation: 3518
This should work:
$macs | ForEach-Object {
Select Description, @{Name='MacAddress'; Expression={ ($_.MacAddress -split '([A-Z0-9]{2})' | Where-Object {$_}) -join '-' }}, IPAddess, Location
}
Breaking the expression down:
{ `
( `
$_.MacAddress -split '([A-Z0-9]{2})' ` # regex split the mac address up every two alpha-numeric chars
| Where-Object {$_} ` # filter to only return non-blank splits
) `
-join '-' # join the 2-char pairs with a '-'
}
EDIT
And here is a complete example, mixing your code, with mine, to input a file, then output it:
# remove comment before -Header if no header
$csv = Import-Csv -Path C:\Users\metho\Desktop\Macadd.csv # -Header Description, MacAddress, IPAddess, Location
$csv | ForEach-Object { Select HostName, @{Name='MacAddress'; Expression={ ($_.MacAddress -split '([A-Z0-9]{2})' | Where-Object {$_}) -join '-' }} } |
Export-Csv -Path C:\Users\metho\Desktop\MacAdd_v1.csv -NoTypeInformation
Although, this can be simplified, by not using variables, like this:
Import-CSV C:\Users\metho\Desktop\Macadd.csv |
ForEach-Object { Select HostName, @{Name='MacAddress'; Expression={ ($_.MacAddress -split '([A-Z0-9]{2})' | Where-Object {$_}) -join '-' }} } |
Export-CSV C:\Users\metho\Desktop\MacAdd_v1.csv -NoTypeInformation
Upvotes: 1
Reputation: 23355
This is tested and works. Per the discussion comments I've included a check for strings that aren't the expected length of a MAC address. This will also ensure it doesn't add further dashes if you run it subsequent times:
Import-CSV 'C:\Users\metho\Desktop\macadd.csv' | ForEach-Object {
If ($_.MacAddress.length -eq 12){
$_.MacAddress = $_.MacAddress.insert(2,"-").insert(5,"-").insert(8,"-").insert(11,"-").insert(14,"-")
} Else {
Write-Warning "The MAC Address $($_.MacAddress) is not 12 characters"
}
Write-Output $_
} | Export-CSV 'C:\Users\metho\Desktop\macadd_v1.csv' -NoTypeInformation
Upvotes: 2