将所有用户和密码输出到文件 [英] Outputting all users and passwords to a file

查看:105
本文介绍了将所有用户和密码输出到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个脚本,该脚本将在CSV文件中容纳几个用户,然后更改其密码并在Active Directory中启用它。问题是我似乎无法让所有用户都输出到如下所示的CSV或文本文件:

Im trying to create a script where it will take a few users in a CSV file, then change their password and enable it in Active Directory. The trouble is I cant seem to get all the users to output to either a CSV or a text file that looks like this:

User1   Password
User2   Password
User3   Password
User4   Password

我已经尝试过 Write-Host 那没有用,所以我在玩一个数组,但是我似乎还是不明白。有人可以帮我解决我做错的事情,以便让所有用户输出到表中吗?

I have tried Write-Host and that didn't work, so I was playing with an array, but I still can't seem to get it. Can someone please help me with what I'm doing wrong, so that I can get all the users outputted to a table?

这是我正在使用的代码:

Here is the code that I am using:

if (-not (Get-Module ActiveDirectory)){
  Import-Module ActiveDirectory
}

#Construct an out-array to use for data export
$OutArray = @()

# User setup           
$users = Import-Csv "C:\accounts.csv"

foreach ($user in $users) {
  # set up random number generator
  $rand = New-Object System.Random

  #Generate a new password
  $NewPassword = [char]$rand.next(65,90) + [char]$rand.next(65,90) +
                 [char]$rand.next(48,57) + [char]$rand.next(97,122) +
                 [char]$rand.next(48,57) + [char]$rand.next(97,122) +
                 [char]$rand.next(97,122) + [char]$rand.next(35,38)

  #setup username variables
  $username = $user.samAccountName

  #enable ad account
  Enable-ADAccount -Identity $username

  #set-ad password 
  Set-ADAccountPassword $username -NewPassword (ConvertTo-SecureString -AsPlainText "$NewPassword" -Force) -PassThru -Reset

  #$outarray += $Username,$NewPassword
  #Write-Host "Password has been set for:" $username  $NewPassword
}

#After the loop, export the array to CSV
$outarray | Export-Csv "c:\login.csv"


推荐答案

而不是

$outarray += $Username,$NewPassword

创建一个新的 PsObject 并将其添加到数组中:

Create a new PsObject and add it to the array:

$OutArray += New-Object PSObject -Property @{UserName=$username; Password=$NewPassword}  

并使用以下命令导出:

$OutArray | Export-Csv "c:\login.csv" -NoTypeInformation

使用您的方法( $ outarray + = $ Username,$ NewPassword ),您刚刚创建了一个包含用户名和密码的字符串列表(无分配)。

With your approach ($outarray += $Username,$NewPassword), you just created a string list containing usernames and passwords (without assignments).

您可能想看看导出Csv 帮助。

这篇关于将所有用户和密码输出到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆