首页 文章

获取PowerShell循环文件的用户列表

提问于
浏览
-1

我'm trying to modify this PowerShell script to allow input of users from a text or CSV file. I'已直接从Tim Rhymer拉出脚本 .

这是原始脚本:

Import-Module ActiveDirectory

function Get-ADUsersLastLogon() {
  $dcs = Get-ADDomainController -Filter {Name -like "*"}
  $users = Get-ADUser -Filter *
  $time = 0
  $exportFilePath = "c:lastLogon.csv"
  $columns = "name,username,datetime"

  Out-File -FilePath $exportFilePath -Force -InputObject $columns

  foreach ($user in $users) {
    foreach ($dc in $dcs) { 
      $hostname = $dc.HostName
      $currentUser = Get-ADUser $user.SamAccountName | Get-ADObject -Server $hostname -Properties lastLogon

      if ($currentUser.LastLogon -gt $time) {
        $time = $currentUser.LastLogon
      }
    }

    $dt = [DateTime]::FromFileTime($time)
    $row = $user.Name + "," + $user.SamAccountName + "," + $dt

    Out-File -FilePath $exportFilePath -Append -NoClobber -InputObject $row

    $time = 0
  }
}

Get-ADUsersLastLogon

我想我应该修改脚本的部分,设置 $user 的变量以及 foreach ($user in $users) 循环如何处理每个用户,但无法弄明白 .

1 回答

  • 0

    至于......

    允许从文本或CSV文件输入用户 .

    ......就是这就是......

    $users = Get-ADUser -Filter *
    

    ...你只需用你的文件替换它

    $users = Import-Csv -Path $UncToUserList.csv
    

    然而,通过你的问题,因为这是一个非常常见的,基本的PowerShell事情,我假设你是非常新的,并建议使用TechNet MVAMSChannel9YouTube上的所有免费学习资源,真正增加PowerShell . 以及免费提供eBooks,以尽可能避免学习周期中的混乱和挫折 .

    此外,您永远不应运行任何不受信任的代码或您不完全理解的代码 . 仅在可以在考虑 生产环境 运行之前完全恢复的测试环境中使用,以避免可能导致您出现RPE错误的事情 - “恢复生成事件” .

相关问题