我正在编写之前编写的脚本的新版本,但我正在将其升级为使用 MSGraph 来创建 Office 365 帐户。
我在这里遇到了一个问题,因为我创建了一个函数来测试用户是否存在:
#Function to check account existence
Function AccountExists
{
Param(
[string]$fxEmailAccount
)
#Validamos si la cuenta existe
$return = [System.Convert]::ToBoolean("TRUE")
try {
$user = Get-MgUser -UserId $fxEmailAccount
Write-Output $($user.Count())
}
catch {
$return = [System.Convert]::ToBoolean("FALSE")
}
return $return
}
$result = AccountExists -fxEmailAccount [email protected]
这对我来说部分有效,这里的问题是我如何正确检查帐户是否存在,因为 Get-MGUser 返回一个对象,每次我运行我的函数时,它有时会因为我实现的逻辑而失败。
我已经尝试使用 Get-MgUserCount,但这种方法也没有任何运气。
有人可以告诉我我可能做错了什么或没有很好地解释这样做吗?
谢谢,
您的函数可能可以简化为以下 PowerShell 惯用形式:
function Test-AccountExists {
param(
$UserId
)
[bool] (Get-MgUser -UserId $UserId -ErrorAction Ignore)
}
# Sample invocation
$result = Test-AccountExists -UserId [email protected]