首页 > 解决方案 > Powershell 输出校正

问题描述

我正在尝试构建一个 PS 脚本(适用于 Office 365),它将帮助我管理日常任务,例如设置用户的电子邮件转发、添加电子邮件等

我已经开始了连接过程,我希望 powershell 向我询问用户名,然后运行一些命令并显示结果,这样我就可以通过“菜单”运行它:

它工作完美,做我想做的事,问题是,例如,如果有两个用户同名,比如“trevor”,结果会告诉我

特雷弗杰克逊和特雷弗布拉布拉

我怎样才能让脚本告诉我“我找到了两个同名的用户”?

这是代码的简短版本(与 O365 的连接不需要在这里)

    $askusername= Read-Host "What is the user name? you can write part of the user name to"

    write-host "`n"

    $checkuser = Get-Mailbox -Identity *$askusername*

    write-host  -ForegroundColor White -BackgroundColor Blue "Found this user: $checkuser"

    #menu
$menu = Read-Host -Prompt "
    `n1. Enalbe Email Forwarding from $checkuser to a spesific user WITH copy?
    `n2. Enable  Email Forwarding from $checkuser to a spesific user WITHOUT a copy?
    `n3. Disable Forwarding
    `n4. Exit
    `n  What would you like to do?"
    Switch($menu){
            1{Get-Mailbox -Identity *$askusername* |select name} (for testing)
            2{Write-Host "it's working" green}
            3{exit}
            }

标签: powershelloffice365

解决方案


    $askusername= Read-Host "What is the user name? you can write part of the user name to"

    write-host "`n"

    $checkuser = Get-Mailbox -Identity *$askusername*
    if($checkuser.count -eq 1){
        Write-Host  -ForegroundColor White -BackgroundColor Blue "Found this user: $($checkuser.Name)"    
    }else{
        $checkuser = $checkuser | Out-GridView  -PassThru -Title "Multiple Users found, please select the correct user."
    }

    write-host  -ForegroundColor White -BackgroundColor Blue "Found this user: $checkuser"

    #menu
$menu = Read-Host -Prompt "
    `n1. Enalbe Email Forwarding from $checkuser to a spesific user WITH copy?
    `n2. Enable  Email Forwarding from $checkuser to a spesific user WITHOUT a copy?
    `n3. Disable Forwarding
    `n4. Exit
    `n  What would you like to do?"
    Switch($menu){
            1{Get-Mailbox -Identity $checkuser | select name} #(for testing)
            2{Write-Host "it's working" green}
            3{exit}
            }

您需要计数,您必须检查结果是否超过 1 个对象。这些方面的东西可以告诉你是否有超过 1 个。

编辑:编辑您的脚本以提供计数和网格视图以选择您希望附加的用户。此外,您一直在选择列表中使用不正确的变量,您应该使用 checkuser var。


推荐阅读