我正在尝试创建一个 powershell 脚本来维护用户。当前环境。带有 ADFS、AD 和本地 Exchange Server 2010 的 Office365。全部集成在一起。对于当前问题,我正在尝试从 csv 导入用户列表,并将它们应用于 Exchange 或 Active Directory 中的特定分发组。在我的环境中,两者同步并相互更新。我想根据员工的员工编号执行此操作,该员工编号在 Active Directory 中存储为 extensionattribute5。我还想创建成功/失败日志。以下是我的脚本。接下来是错误消息。测试文件包含两列,显示名称和 EmpNo。我在这里做错了什么/遗漏了什么。似乎无法让它工作。
import-module activedirectory
$Users=Import-csv c:\test.csv
$failedUsers = @()
$usersAlreadyExist =@()
$successUsers = @()
$VerbosePreference = "Continue"
$LogFolder = "C:\temp"
ForEach($User in $Users)
{
try {
if (!(get-aduser -Filter "extensionattribute5 -like '$($_.EmpNo)'")){
Add-ADGroupMember -Identity 'IMS S3' -Member SAMAccountName
Write-Verbose "[PASS] Created $EmpNo"
$successUsers += $EmpNo
}
else {
Write-Warning "[WARNING] [$($EmpNo)] already exists in Distribution Group"
$usersAlreadyExist += $EmpNo
}
}
catch {
Write-Warning "[ERROR]Can't create add [$($EmpNo)] : $_"
$failedUsers += $EmpNo
}
}
if ( !(test-path $LogFolder)) {
Write-Verbose "Folder [$($LogFolder)] does not exist, creating"
new-item $LogFolder -Force
}
Write-verbose "Writing logs"
$failedUsers | out-file -FilePath $LogFolder\FailedUsers.log -Force -Verbose
$usersAlreadyExist | out-file -FilePath $LogFolder\usersAlreadyExist.log -Force -Verbose
$successUsers | out-file -FilePath $LogFolder\successUsers.log -Force -Verbose
错误消息如下:在 C:\users\new3.ps1:16 char:72 + ... if (!(get-aduser -Filter "extensionattribute5 -like '$($_.EmpNo)'")) + ~ if (condition) 后缺少语句块。+ CategoryInfo : ParserError: (:) [], ParseException + FullyQualifiedErrorId : MissingStatementBlock
答案1
您有一个单引号,它引用了 Get-Aduser 过滤器中带有扩展属性的“-like”比较运算符。您需要在 -like 之前添加双引号,并在比较中删除单引号后的双引号:
import-module activedirectory
$Users=Import-csv c:\test.csv
$failedUsers = @()
$usersAlreadyExist =@()
$successUsers = @()
$VerbosePreference = "Continue"
$LogFolder = "C:\temp"
ForEach($User in $Users)
{
try {
if (!(get-aduser -Filter "extensionattribute5" -like '$($_.EmpNo)')){
Add-ADGroupMember -Identity 'IMS S3' -Member SAMAccountName
Write-Verbose "[PASS] Created $EmpNo"
$successUsers += $EmpNo
}
else {
Write-Warning "[WARNING] [$($EmpNo)] already exists in Distribution Group"
$usersAlreadyExist += $EmpNo
}
}
catch {
Write-Warning "[ERROR]Can't create add [$($EmpNo)] : $_"
$failedUsers += $EmpNo
}
}
if ( !(test-path $LogFolder)) {
Write-Verbose "Folder [$($LogFolder)] does not exist, creating"
new-item $LogFolder -Force
}
Write-verbose "Writing logs"
$failedUsers | out-file -FilePath $LogFolder\FailedUsers.log -Force -Verbose
$usersAlreadyExist | out-file -FilePath $LogFolder\usersAlreadyExist.log -Force -Verbose
$successUsers | out-file -FilePath $LogFolder\successUsers.log -Force -Verbose