Powershell脚本让我很困惑

mlnl4t2r  于 2023-03-23  发布在  Shell
关注(0)|答案(2)|浏览(109)

我有一个脚本,工作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')
brqmpdu1

brqmpdu11#

如果$aduser.Manager$null,则以下调用可预见地失败,并显示您引用的错误消息($null不是要查找的有效标识):

$manager = $aduser.Manager | Get-ADUser -Properties mail

下面的代码应该会绕过该错误:

$manager = if ($aduser.Manager) { $aduser.Manager | Get-ADUser -Properties mail }

如果$aduser.Manager$null(或空字符串),则Get-AdUser调用被 * 绕过 $null(从技术上讲,一个“自动化Null”值,其 * 在表达式上下文中的行为类似于$null)存储在$manager中。
此外,要在构造的[pscustomobject]中获得所需的默认值,必须在之后添加一个条件:

if ($manager) {
  & $object $aduser.Mail $aduser.SamAccountName $manager.Name $manager.mail
} else {
  & $object $aduser.Mail $aduser.SamAccountName
}

请注意,这两个更新的代码段都利用了PowerShell在条件中的 * 隐式到布尔强制转换 *,其规则总结在this answer的底部。

qxgroojn

qxgroojn2#

见下文

#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

[System.Windows.Forms.MessageBox]::Show('Script Starting . . .','Begin Script')
$user | ForEach-Object {
    # Create PSCustomObject to store the results
    $email = $null
    $email = $_.email.Trim()
    $result = [pscustomobject]@{
        Mail           = if ([string]::IsNullOrEmpty($email)) { 'Not Found in csv' } else { $email }
        SamAccountName = 'Not Found'
        Manager        = 'Not Found'
        ManagerEmail   = 'Not Found'
    }
    
    if ($result.Mail -ne 'Not Found in csv') {
        try {
            $adUser = $null
            $adUser = Get-AdUser -Filter ("mail -eq '$email'") -ErrorAction Stop -Properties 'mail', 'samaccountname', 'manager'
            $result.SamAccountName = $adUser.SamAccountName
            $result.Manager        = $adUser.Manager
            try {
                if ($adUser.Manager) {
                    $manager = $null
                    $manager = Get-AdUser -Identity $adUser.Manager -ErrorAction Stop -Properties 'mail'
                    $result.ManagerEmail = $manager.name
                }
                else {
                    $result.ManagerEmail = 'No Manager'
                }
            }
            catch {
                $result.ManagerEmail = "Issue retrieving manager email $($_.Exception.Message)" 
            }
        }
        catch {
            $result.Mail = "$email Not Found in AD"
        }
        finally {
            $result
        }
    }
    else {
        $result
    }
} | Export-CSV -Path $SaveMyFile -NoTypeInformation

[System.Windows.Forms.MessageBox]::Show('Script Complete.','Completed')

相关问题