During the course of the work day I have field techs out and about and they'll occasionally need to add a MAC address to our Wireless Access group in AD. We don't fully support them getting into AD on their own and we've been using a script to allow them to add MAC addresses the right way. I have taken it upon myself to fully idiot-proof this thing and i'm nearly there minus one glaring issue. I can't stop them from adding MAC addresses with values greater than 'f'.
Write-Host "MAC Address must be entered as lowercase and without colons. EX: 14d6aa6ac9be" -ForegroundColor Yellow
$MACUserName = Read-Host -Prompt 'Please Input the MAC Address of the Device to be added to AD and press Enter'
$MACUserName = $MACUserName -replace '[\W]', ''
If ($MACUserName.Length -ne 12 -or $MACUserName -notmatch '[A-Za-z0-9]') {
Write-Host "MAC Address: " -ForegroundColor Red -NoNewline; Write-Host $MACUserName -ForegroundColor White -NoNewline; Write-Host " is not the correct length or contains invalid characters. Please verify MAC address" -ForegroundColor Red
Pause
Single-Device}
This is where i'm at with everything so far, obviously there is much more to this than just this section but for now this is where i live.
I'm able to get rid of any colons that might be entered in and my -notmatch section includes all possible values.
if i change -notmatch '[A-Za-z0-9]'
to -notmatch '[A-Fa-f0-9]'
It still lets me add fake MAC addresses with z's and whatnot. How do I go about limiting the characters this section will accept?
Santiago Squarzon's helpful answer offers the best solution to your problem, using a .NET API.
As for what you tried:
'[A-Fa-f0-9]'
matches one character that falls into the specified ranges, which means that one such character in the input string makes the expression evaluate to $true
- even if other characters outside these ranges are present.
Therefore you must make sure that all characters that make up the input string fall into the expected ranges:
-notmatch '^[a-f0-9]+$'
Alternatively, invert the logic and look for at least one invalid character:
-match '[^a-f0-9]'
Note:
The -match
/ -notmatch
operators perform substring matching by default; therefore, in order to match the entire string, start and end anchors ^
and $
are needed.
[a-f]
is enough to match both lowercase and uppercase letters, because -match
/ -notmatch
are case-insensitive by default, as PowerShell is in general. If case-sensitive matching is desired, use -cmatch
/ -cnotmatch