我在powershell中有此代码,而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"
答案 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)
你有两个问题。
Thread
不会写入管道,只显示在屏幕上。Write-Host
没有任何东西可以作为输入。尝试改为使用Tee-Object
和ForEach-Object
:
Write-Object