Tee-Object无法将输出命令注释保存到文件

时间:2016-11-08 07:23:45

标签: powershell active-directory

我在中有此代码,而Tee-Object无法将所有Write-Host命令保存到file.txt。我可以做些什么来修复这段代码?

Import-Module ActiveDirectory
Add-Type -AssemblyName System.Web 
$users = Get-Content -Path 'G:\Shares\xx xxx\ResetPassword\UserList.txt'
ForEach ($user in $users) 
{
$unsecuredpwd = [System.Web.Security.Membership]::GeneratePassword(10, 3)
$password = ConvertTo-SecureString -AsPlainText $unsecuredpwd -Force
Get-ADUser $user | Set-ADAccountPassword -NewPassword $password -Reset
Get-ADUser $user | Set-AdUser -ChangePasswordAtLogon $true
Enable-ADAccount -Identity $user
Write-Host “uzytkownik: $user”
Write-Host “haslo: $unsecuredpwd”
Write-Host “ `r`n`r`n”
} | Tee-Object -FilePath G:\Shares\xx xxx\ResetPassword\Output.txt
Read-Host -Prompt "click enter to exit"

2 个答案:

答案 0 :(得分:1)

Write-Host 不会向管道发送任何内容,因此您应该使用类似Write-Output的内容。还有一个Out-File cmdlet,它比Tee-Object更适合,因为你只是将输出保存到文件中。

这就是你必须编写脚本的方法:

Import-Module ActiveDirectory
Add-Type -AssemblyName System.Web 
Get-Content -Path 'G:\Shares\xx xxx\ResetPassword\UserList.txt' | ForEach-Object {
    $user = $_
    $unsecuredpwd = [System.Web.Security.Membership]::GeneratePassword(10, 3)
    $password = ConvertTo-SecureString -AsPlainText $unsecuredpwd -Force
    Get-ADUser $user | Set-ADAccountPassword -NewPassword $password -Reset
    Get-ADUser $user | Set-AdUser -ChangePasswordAtLogon $true
    Enable-ADAccount -Identity $user
    Write-Output "uzytkownik: $user"
    Write-Output "haslo: $unsecuredpwd"
    Write-Output " `r`n`r`n"
} | Out-File -FilePath G:\Shares\xx xxx\ResetPassword\Output.txt
Read-Host -Prompt "click enter to exit"

答案 1 :(得分:1)

你有两个问题。

  1. Thread不会写入管道,只显示在屏幕上。
  2. foreach(...){}循环也不输出到管道,因此Write-Host没有任何东西可以作为输入。
  3. 尝试改为使用Tee-ObjectForEach-Object

    Write-Object