结合powershell输出

Bra*_*wer 3 powershell active-directory

我正在尝试将两个函数的输出与默认Get-ADUser-cmdlet的输出结合起来。我对创建帐户的时间、它是否被锁定以及它的名称感兴趣。我还想知道用户最后一次登录的时间(使用多个 DC)以及该帐户是否用作共享邮箱。

我已经编写了两个自定义函数Get-ADUserLastLogonisSharedMailbox,这两个函数都使用该Write-Output函数来输出它们的输出。在Get-ADUserLastLogon这种情况下将是Lastlogon: time并且在isSharedMailbox这种情况下将被共享: yes/no。我也在Get-ADUserforeach 循环中使用标准调用

现在,的默认输出Get-ADUser是:

SAMAccountName LockedOut 创建
-------------- --------- -------
ACC False 23-10-2015 8:20:20

自定义函数的输出如下:

最后登录 : 1-1-1601 1:00:00

共享:是

我想要的是将 LastLogon 和 Shared 'headers' 组合到 Get-ADUser 中。所以输出将变成:

SAMAccountName LockedOut Created LastLogon Shared

当前代码的代码,其中帐户从 Excel 工作表导入:

foreach($username in $usernameWithTld){
    if ($username -eq $NULL){
        break
    }

    $usernameWithoutTld = $username.split('\')

    Get-ADUser $usernameWithoutTld[1] -Properties LockedOut, SamAccountName, 
    Created -ErrorAction Stop | Select-Object SAMAccountName, LockedOut, 
    Created

    Get-ADUserLastLogon -UserName $usernameWithoutTld[1]

   # Shared mailbox?

   isSharedMailbox -mailboxname $usernameWithoutTld[1]
}
Run Code Online (Sandbox Code Playgroud)

功能代码:

function isSharedMailbox([string]$mailboxname){
    $isObject = Get-ADUser  -Filter {name -eq $mailboxname} -SearchBase "..." | Select-Object DistinguishedName,Name

    if ($isObject -match "DistinguishedName"){
        $output = "Shared: no"
        Write-Output $output
    } else {
        $output = "Shared: No"
        Write-Output $output
    }

}


function Get-ADUserLastLogon([string]$userName){

  $dcs = Get-ADDomainController -Filter {Name -like "*"}
  $time = 0
  foreach($dc in $dcs)
  { 
    $hostname = $dc.HostName
    $user = Get-ADUser $userName | Get-ADObject -Properties lastLogon 
    if($user.LastLogon -gt $time) 
    {
      $time = $user.LastLogon
    }
  }
  $dt = [DateTime]::FromFileTime($time)
  Write-Output "LastLogon : $dt"

}
Run Code Online (Sandbox Code Playgroud)

我确信可以进行很多改进,我仍在学习如何编写(正确的)PowerShell。我希望有人能回答我的问题。

小智 5

您可以在Select-Object. 查看MSDN 页面的示例 4

在您的情况下,这将是:

Get-ADUser $usernameWithoutTld[1] -Properties LockedOut, SamAccountName, Created -ErrorAction Stop | `
Select-Object SAMAccountName, LockedOut, Created, @{Name='LastLogon';Expression={Get-ADUserLastLogon -UserName $usernameWithoutTld[1]}}, @{Name='IsSharedMailbox';Expression={isSharedMailbox -mailboxname $usernameWithoutTld[1]}}
Run Code Online (Sandbox Code Playgroud)

或者更好的是,您可以使用Get-ADUser放入管道的对象依次调用该特定对象的函数,并且在您的查询返回多个结果时很有用:

Get-ADUser $usernameWithoutTld[1] -Properties LockedOut, SamAccountName, Created -ErrorAction Stop | `
Select-Object SAMAccountName, LockedOut, Created, @{Name='LastLogon';Expression={Get-ADUserLastLogon -UserName $_.sAMAccountName}}, @{Name='IsSharedMailbox';Expression={isSharedMailbox -mailboxname $_.sAMAccountName}}
Run Code Online (Sandbox Code Playgroud)