You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化PowerShell中判断所有者域名的if/else语句?

优化方案

首先你这段代码有两个明显问题:一是两个if-else块逻辑完全重复,冗余度很高;二是所有elseif里错误地用了未定义的$String变量,应该替换成当前要判断的邮箱变量($PrimaryOwner或$SecondaryOwner)。

下面是几种简化思路,按简洁性和可维护性排序:

1. 用哈希表+复用函数(最推荐)

把域名匹配规则放到哈希表中,然后写一个通用函数处理邮箱判断,后续要新增域名规则只需要修改哈希表,不用改逻辑代码:

# 定义域名匹配规则:键是匹配模式,值是对应的标签
$domainMappings = @{
    "*gmail*"    = "Gmail"
    "*Outlook*"  = "Outlook"
    "*Live*"     = "Live"
    "*Yahoo*"    = "Yahoo"
    "*hotmail*"  = "Hotmail" # 原代码少了通配符,补上后能匹配xxx@hotmail.com这类邮箱
}

# 通用判断函数
function Get-DomainLabel {
    param(
        [string]$EmailAddress
    )
    # 遍历哈希表,找到第一个匹配的规则
    foreach ($pattern in $domainMappings.Keys) {
        if ($EmailAddress -like $pattern) {
            return $domainMappings[$pattern]
        }
    }
    # 无匹配项时返回Custom
    return "Custom"
}

# 初始化变量并调用函数获取标签
$PrimaryOwner = "example@gmail.com"
$SecondaryOwner = "example@yahoo.com"

$DomainLabel = Get-DomainLabel -EmailAddress $PrimaryOwner
$AltDomainLabel = Get-DomainLabel -EmailAddress $SecondaryOwner

2. 用Switch语句简化重复逻辑(快速修复)

如果不想写函数,也可以用switch语句替代冗余的if-else,再通过脚本块复用逻辑:

$PrimaryOwner = "example@gmail.com"
$SecondaryOwner = "example@yahoo.com"

# 封装判断逻辑的脚本块
$getLabel = {
    param($email)
    switch -Wildcard ($email) {
        "*gmail*"    { "Gmail"; break }
        "*Outlook*"  { "Outlook"; break }
        "*Live*"     { "Live"; break }
        "*Yahoo*"    { "Yahoo"; break }
        "*hotmail*"  { "Hotmail"; break }
        default      { "Custom" }
    }
}

# 执行脚本块获取对应标签
$DomainLabel = &$getLabel $PrimaryOwner
$AltDomainLabel = &$getLabel $SecondaryOwner

补充说明

  • 原代码中"hotmail"没有通配符,只能精确匹配字符串"hotmail",改成*hotmail*才能正常匹配带hotmail域名的邮箱地址,优化后的代码已修正这个问题。
  • 哈希表和switch结构比嵌套的if-else更易读,后续调整或新增域名规则时也更高效。

内容的提问来源于stack exchange,提问作者aasenomad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 03:01:01