Powershell脚本,用于仅将有效的AD用户导出到csv并抑制在AD中找不到的用户

pjngdqdw  于 2023-02-04  发布在  Shell
关注(0)|答案(1)|浏览(179)

大家好,我正在尝试编写一个脚本,该脚本将检查用户是否有效并将结果导出到.csv文件。我正在使用“for each”和erroraction -silentlycontinue cmdlet检查.csv文件中的用户列表,然后在Microsoft Teams管理中心验证该用户是否为有效用户。
我遇到的问题是,如果我添加“$errorActionpreference”cmdlet来抑制错误(或屏幕上找不到用户),CSV文件中的结果为空,如果我删除$errorAction cmdlet(在下面的脚本中散列),则它可以通过导出有效用户正常工作,但它会在屏幕上吐出大量错误。
脚本只需要抑制无效用户的错误消息,移动到csv文件中的下一个用户,最后将有效用户的结果导出到另一个csv文件。

$path = Read-Host -Prompt "`nEnter the path of .csv file:"
if (Test-Path -Path $path) { break }
Write-Host "Wrong file or path specified. Please enter the correct 
path to file!" -ForegroundColor Red
     
Write-Host "File has been located in the path specified!" - 
ForegroundColor Green
$CsvFilePath = Import-CSV -Path $path     

# $ErrorActionPreference = "silentlycontinue"
   
     $results = foreach ($Users in $CsvFilePath) {
     $User = $Users.UserPrincipalName
     Get-CsOnlineUser $User | Select-Object  UserPri*, LineURI, 
     TeamsUpgradeE*,IsSipEnabled, Enterprise*, 
    @{l="AssignedPlan";e={$_.AssignedPlan 
     - join "; "}}, @{l="FeatureTypes";e={$_.FeatureTypes -join "; 
    "}}
     }
    # $ErrorActionPreference = "silentlycontinue
    
  #Export Results: Prompt for Path, If file does not exist, create it!#
  $resultspathfilelocation = Read-Host -Prompt "`nEnter file path 
  to export results of 
  the Post Checks: "
  $FileName = "$resultspathfilelocation"
    if(Get-Item -Path $FileName -ErrorAction Ignore){
      Write-Host "File found in directory specified!"
      }
     else{
      New-Item -Verbose $FileName -ItemType File
     }
   $results | Export-Csv $resultspathfilelocation
ozxc1zmp

ozxc1zmp1#

与其试图忽略错误,为什么不正确地处理它们呢?

$Results = foreach ($Users in $CsvFilePath) {
    Try {
        $User = $Users.UserPrincipalName
        $ThisUser = Get-CsOnlineUser $User -ErrorAction Stop
    # Output as custom object
        [pscustomobject]@{UPN = $User
                    TeamsUpgradeEffectiveMode = $ThisUser.TeamsUpgradeEffectiveMode
                    IsSipEnabled = $ThisUser.IsSipEnabled
                    AssignedPlan = ($ThisUser.AssignedPlan -join "; ")
                    FeatureTypes = ($ThisUser.FeatureTypes -join "; ")
                    Error = ''}
    }
    Catch {
    # User not found or error, output object with blank fields except for error
        [pscustomobject]@{UPN = $User
                    TeamsUpgradeEffectiveMode = ''
                    IsSipEnabled = ''
                    AssignedPlan = ''
                    FeatureTypes = ''
                    Error = $_.Exception.Message}
    }
}

相关问题