Good day all, I'm trying to write a script that will check if a User is valid and export the results to a .csv file. I'm using the "for each" and erroraction -silentlycontinue cmdlet to check a list of Users from a .csv file and then verify on the Microsoft Teams admin center if that is a Valid User.
The problem I'm having is if I add the "$errorActionpreference" cmdlet which suppresses errors (or Users Not Found on Screen) the results in the CSV File are empty, If I remove the $errorAction cmdlet (hashed out in the script below), then it works fine by exporting the valid Users BUT it spits out a lot of errors on the screen.
The scripts just need to suppress error messages for invalid Users, Move to the next User in the csv file, and finally export the results of the valid Users to another csv file.
$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
CodePudding user response:
Instead of trying to ignore the errors, why not just handle them properly?
$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}
}
}