我有以下脚本来使用自动生成的32个字符的密码更新密码。然后它生成一个受密码保护的Word文档,这样我们就可以更新我们的安全密码库。生成密码工作正常。
给有密码保护的word文档分配密码时出现问题。我可以直接对字符串进行硬编码,例如:
$PL_Document.Password = 'blah'
在我硬编码的情况下,一切都很好。我得到一个密码保护的word文档与登录信息。
但是,当我尝试使用read -host读取它然后分配它时,脚本挂起。
Add-Type -AssemblyName System.Web
cls
#************ Create Document ******************************
function CreateDocument
{
$PL_Word = New-Object -ComObject Word.Application
#$PL_Word.Visible = $true
$PL_Document = $PL_Word.Documents.Add()
$PL_Report = 'C:TEMPMyDoc.docx'
$PL_Document.SaveAs([ref]$PL_Report,[ref]$SaveFormat::wdFormatDocument)
$PL_Selection = $PL_Word.Selection
#****************** Password Protect the Word File ********
$PL_PwdEntry = Read-Host ("Enter the password for the text document record") -AsSecureString
$PL_WdPWD = ConvertFrom-SecureString $PL_PwdEntry
$PL_Document.Password = $PL_WdPWD
#************** Write Password to Document *************************************
$PL_Selection.TypeParagraph()
$PL_Selection.TypeText("Username: $PL_UN")
$PL_Selection.TypeParagraph()
$PL_Selection.TypeText("Password: $PL_PWD")
#************** Close Document *************************************
$PL_Document.Close()
$PL_Word.Quit()
}
#****************** Create Password ************************
$PL_PWD = [System.Web.Security.Membership]::GeneratePassword(32,3)
Write-Host "`n`n"
$PL_UN = "Prime"+(Read-Host ("Enter the username. Entering the Primelending domain is not neccessary."))
Write-Host "`nSummary of the change" -f Yellow
Write-Host "============================" -f Yellow
Write-Host "`nUsername: " -NoNewline
Write-Host "$PL_UN" -f Yellow
Write-Host "New Password: " -NoNewline
Write-Host "$PL_PWD`n" -f Yellow
Write-Host "Do you want to update AD (Y/N)" -NoNewline -f Yellow
$PL_Query = Read-Host (" ")
If ($PL_Query.ToUpper() -eq "Y") {
Write-Host "`nMaking change" -f Green
#Set-ADAccountPassword -Identity $PL_UN -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$PL_PWD" -Force)
CreateDocument
}
else {Write-Host "`nAbandoning change" -f Green }
脚本的$PL_WdPWD = ConvertFrom-SecureString $PL_PwdEntry
部分将不会返回纯文本密码,而是密码的编码版本,其长度将比原始密码长得多。
根据我的记忆,Word的密码限制为255个字符,这个值很可能超过这个值,并且很可能是导致挂起的原因,因为Word无法处理它。
如果您使用的是PowerShell v7或更高版本,则将$PL_WdPWD = ConvertFrom-SecureString $PL_PwdEntry
更改为$PL_WdPWD = ConvertFrom-SecureString $PL_PwdEntry -AsPlainText
以获得密码的纯文本版本
$PL_PwdEntry = Read-Host ("Enter the password for the text document record") -AsSecureString
$PL_WdPWD = ConvertFrom-SecureString $PL_PwdEntry
$PL_WdPWD = Read-Host ("Enter the password for the text document record")
编辑以下注释
当传递$PL_WdPWD
变量给$PL_Document.Password
时,Word似乎挂起了,这是由于缺少引号。
为了解决这个问题,您可以更改
这一行$PL_Document.Password = $PL_WdPWD
$PL_Document.Password = "$PL_WdPWD"
注意:在更新的代码中,您仍然使用Read-Host -AsSecureString
,然后将其转换为ConvertFrom-SecureString
。这将不会为您提供您期望的密码,而是返回该密码的编码版本。关于这个问题的详细信息,请参阅我的原始回答。