我有一个脚本,工作jsut罚款,现在突然停止工作。问题是,我的脚本需要一个电子表格,并使用它的电子邮件地址查询AD,然后找到用户的电子邮件,经理和经理电子邮件地址。我的脚本需要能够在输出电子表格中放置空白,以便输出电子表格与输入电子表格具有完全相同的行数,并且所有内容都在完全一样的命令。
目前,如果我的脚本发现一个没有列出管理员的用户,它会停止并且不会运行。我如何改变我的脚本,使它基本上是万无一失的,如果它找不到必要的信息,它需要在输出电子表格中输入“NA”或“Not Found”。
#NOTE: Source file must have email as the column header for this script to work!!!
#Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# Import the data from CSV file and assign it to variable
Import-Module ActiveDirectory
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$ErrorActionPreference = 'Stop'
$OpenFIleDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Please Select a CSV File to process"
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.Filter = "CSV (*.csv) | *.csv"
$OpenFileDialog.ShowDialog() | Out-Null
$Path = $OpenFileDialog.Filename
$user = Import-Csv -Path $Path
Function Get-FileName($initialDirectory) {
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null
$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$SaveFileDialog.Title = "Where do you want to save the file?"
$SaveFileDialog.initialDirectory = $initialDirectory
$SaveFileDialog.filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*";
$SaveFileDialog.ShowDialog() | Out-Null
$SaveFileDialog.filename
}
$SaveMyFile = Get-Filename
$params = @{
Properties = 'mail', 'samaccountname', 'manager'
}
$object = {
param(
$mail,
$samAccountName = 'Not Found',
$manager = 'Not Found',
$managerEmail = 'Not Found'
)
[pscustomobject]@{
Mail = $mail
SamAccountName = $samAccountName
Manager = $manager
ManagerEmail = $managerEmail
}
}
[System.Windows.Forms.MessageBox]::Show('Script Starting . . .','Begin Script')
$user | ForEach-Object {
# if there is no value in this column for this object
if([string]::IsNullOrWhiteSpace($_.email)) {
#skip it, go next
return
}
$params['Filter'] = "mail -eq '$($_.email)'"
$aduser = Get-ADUser @params
if(-not $aduser) {
return & $object -Mail $_.email
}
$manager = $aduser.Manager | Get-ADUser -Properties mail
& $object $aduser.Mail $aduser.SamAccountName $manager.Name $manager.mail
} | Export-CSV -Path $SaveMyFile -NoTypeInformation
[System.Windows.Forms.MessageBox]::Show('Script Complete.','Completed')
2条答案
按热度按时间brqmpdu11#
如果
$aduser.Manager
是$null
,则以下调用可预见地失败,并显示您引用的错误消息($null
不是要查找的有效标识):下面的代码应该会绕过该错误:
如果
$aduser.Manager
是$null
(或空字符串),则Get-AdUser
调用被 * 绕过 ,$null
(从技术上讲,一个“自动化Null”值,其 * 在表达式上下文中的行为类似于$null
)存储在$manager
中。此外,要在构造的
[pscustomobject]
中获得所需的默认值,必须在之后添加一个条件:请注意,这两个更新的代码段都利用了PowerShell在条件中的 * 隐式到布尔强制转换 *,其规则总结在this answer的底部。
qxgroojn2#
见下文