仅添加真实MAC地址

发布于 2025-01-11 08:58:02 字数 1070 浏览 1 评论 0 原文

在工作日期间,我有现场技术人员外出走动,他们偶尔需要向 AD 中的无线访问组添加 MAC 地址。我们并不完全支持他们自行进入 AD,我们一直在使用脚本来允许他们以正确的方式添加 MAC 地址。 我已经承担起完全防止这件事白痴的责任,而且我几乎已经做到了,减去了一个明显的问题。我无法阻止他们添加值大于“f”的 MAC 地址。

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}

到目前为止,这就是我处理所有事情的地方,显然这不仅仅是本节,但现在这就是我住的地方。

我能够删除可能输入的任何冒号,并且我的 -notmatch 部分包含所有可能的值。

如果我将 -notmatch '[A-Za-z0-9]' 更改为 -notmatch '[A-Fa-f0-9]' 它仍然允许我添加假货带有 z 之类的 MAC 地址。我该如何限制此部分接受的字符?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里寻她 2025-01-18 08:58:02

我认为您应该能够利用 .NET 物理地址类为此。您可以创建一个函数来解析用户的输入:

function Test-MacAddress {
    param(
        [Parameter(ValueFromPipeline)]
        [string] $MacAddress
    )

    process {
        try {
            [pscustomobject]@{
                ParsedMAC = [PhysicalAddress]::Parse($MacAddress.ToUpper().Replace(':', '-'))
                UserInput = $MacAddress
            }
        }
        catch {
            Write-Warning 'Invalid MAC Address!'
        }
    }
}

Read-Host 'input mac address' | ParseMAC

工作原理示例:

PS /> Test-MacAddress 01-23-45-67-89-AB

ParsedMAC    UserInput
---------    ---------
0123456789AB 01-23-45-67-89-AB

PS /> Test-MacAddress 001122334455

ParsedMAC    UserInput
---------    ---------
001122334455 001122334455

PS /> Test-MacAddress f0:e1:d2:c3:b4:a5

ParsedMAC    UserInput
---------    ---------
F0E1D2C3B4A5 f0:e1:d2:c3:b4:a5

PS /> Test-MacAddress 00112233445z

WARNING: Invalid MAC Address!

注意: .ToUpper().Replace(':', '-') 需要使其与.NET 4.x 及之前版本兼容。

来自备注的有效格式#system-net-networkinformation-physicaladdress-parse(system-string)" rel="nofollow noreferrer">PhysicalAddress.Parse(String)

  • 001122334455
  • 00-11-22-33-44-55
  • 0011.2233.4455
  • 00:11:22:33:44:55
  • F0-E1-D2-C3-B4-A5
  • f0-e1-d2-c3-b4-a5

更进一步,我们可以实现自定义参数转换属性,处理可能的输入字符串并使其与 Windows PowerShell 5.1 以及 PowerShell 7+ 兼容,同时验证输入的 Mac 地址:

using namespace System.Management.Automation

class MacTransform : ArgumentTransformationAttribute {
    [object] Transform([EngineIntrinsics] $EngineIntrinsics, [object] $InputData) {
        if($InputData -isnot [string]) {
            return [PhysicalAddress] $InputData
        }
        return [PhysicalAddress] ($InputData.ToUpper() -replace '[.:-]')
    }
}

function Test-MacAddress {
    param(
        [Parameter(ValueFromPipeline, Mandatory)]
        [MacTransform()]
        [PhysicalAddress] $MacAddress
    )

    process {
        $MacAddress
    }
}

@(
    001122334455
    '00-11-22-33-44-55'
    '00112233445z' # This one should fail
    '0011.2233.4455'
    '00:11:22:33:44:55'
    'F0-E1-D2-C3-B4-A5'
    'f0-e1-d2-c3-b4-a5'
) | Test-MacAddress

I think you should be able to leverage the .NET PhysicalAddress Class for this. You can create a function to parse the user's input:

function Test-MacAddress {
    param(
        [Parameter(ValueFromPipeline)]
        [string] $MacAddress
    )

    process {
        try {
            [pscustomobject]@{
                ParsedMAC = [PhysicalAddress]::Parse($MacAddress.ToUpper().Replace(':', '-'))
                UserInput = $MacAddress
            }
        }
        catch {
            Write-Warning 'Invalid MAC Address!'
        }
    }
}

Read-Host 'input mac address' | ParseMAC

Example of how it works:

PS /> Test-MacAddress 01-23-45-67-89-AB

ParsedMAC    UserInput
---------    ---------
0123456789AB 01-23-45-67-89-AB

PS /> Test-MacAddress 001122334455

ParsedMAC    UserInput
---------    ---------
001122334455 001122334455

PS /> Test-MacAddress f0:e1:d2:c3:b4:a5

ParsedMAC    UserInput
---------    ---------
F0E1D2C3B4A5 f0:e1:d2:c3:b4:a5

PS /> Test-MacAddress 00112233445z

WARNING: Invalid MAC Address!

Note: The use of .ToUpper().Replace(':', '-') in the function is required to make it compatible with .NET 4.x and previous versions.

Valid Formats from Remarks of PhysicalAddress.Parse(String):

  • 001122334455
  • 00-11-22-33-44-55
  • 0011.2233.4455
  • 00:11:22:33:44:55
  • F0-E1-D2-C3-B4-A5
  • f0-e1-d2-c3-b4-a5

Taking it a step further, we could implement a custom argument transformation attribute that handles the possible input strings and makes it compatible with Windows PowerShell 5.1 as well as PowerShell 7+ while validating the input Mac Addresses:

using namespace System.Management.Automation

class MacTransform : ArgumentTransformationAttribute {
    [object] Transform([EngineIntrinsics] $EngineIntrinsics, [object] $InputData) {
        if($InputData -isnot [string]) {
            return [PhysicalAddress] $InputData
        }
        return [PhysicalAddress] ($InputData.ToUpper() -replace '[.:-]')
    }
}

function Test-MacAddress {
    param(
        [Parameter(ValueFromPipeline, Mandatory)]
        [MacTransform()]
        [PhysicalAddress] $MacAddress
    )

    process {
        $MacAddress
    }
}

@(
    001122334455
    '00-11-22-33-44-55'
    '00112233445z' # This one should fail
    '0011.2233.4455'
    '00:11:22:33:44:55'
    'F0-E1-D2-C3-B4-A5'
    'f0-e1-d2-c3-b4-a5'
) | Test-MacAddress
初心 2025-01-18 08:58:02

Santiago Squarzon 的有用答案使用 .NET API 为您的问题提供了最佳解决方案。


至于你尝试过的

'[A-Fa-f0-9]'匹配一个属于指定范围的字符,这意味着输入字符串中的一个这样的字符使得表达式的计算结果为$true - 即使存在这些范围之外的其他字符。

因此,您必须确保组成输入字符串的所有字符都落入预期范围内:

-notmatch '^[a-f0-9]+$'

或者,反转逻辑并查找至少一个无效字符:

-match '[^a-f0-9]'

注意:

  • <代码>- match / -notmatch 运算符默认执行子字符串匹配;因此,为了匹配整个字符串,需要开始和结束锚点^$

  • [af] 足以匹配小写和大写字母,因为 -match / -notmatch默认情况下不区分大小写,就像 PowerShell 的一般情况一样。如果需要区分大小写,请使用 -cmatch / -cnotmatch

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文