【发布时间】:2014-06-22 23:26:45
【问题描述】:
我创建了一个小脚本,用于创建 Windows 本地用户及其用于 FTP 访问的环境。该脚本运行良好,但它应该将详细信息写入 XML 文件。该脚本一次只创建一个用户。它将用户名存储在名为 $accountName 的变量中,全名存储在 $fullName 中,生成的密码存储在 $password 中,主目录存储在$directoryPath 和变量 $date 中的创建日期。 下面的代码有效,但它每次都会用最后创建的用户的详细信息覆盖文件,而不会将其附加到 XML 文件中。
#Writing out details to XML file
Write-Host -fore yellow "Writing out details to XML..."
# create a template XML to hold data
$template = @'
<FtpUsers>
<account>
<accountName></accountName>
<fullName></fullName>
<password></password>
<directoryPath></directoryPath>
<date></date>
</account>
</FtpUsers>
'@
$template | Out-File C:\ProgramData\InstanceLogFiles\FtpUsers.xml -encoding UTF8
# load template into XML object
$xml = New-Object xml
$xml.Load("C:\ProgramData\InstanceLogFiles\FtpUsers.xml")
# grab template user
$newuser = (@($xml.FtpUsers.account)[0]).Clone()
# use template to add local user accounts to xml
$newuser = $newuser.clone()
$newuser.accountName = $accountName
$newuser.fullName = $fullName
$newuser.password = $password$newuser.directoryPath = $directoryPath
$newuser.date = $date
$xml.FtpUsers.AppendChild($newuser) > $null
# remove users with undefined name (remove template)
$xml.FtpUsers.account |
Where-Object { $_.accountName -eq "" } |
ForEach-Object { [void]$xml.FtpUsers.RemoveChild($_) }
# save xml to file
$xml.Save("C:\ProgramData\InstanceLogFiles\FtpUsers.xml")
Write-Host -fore yellow "...Done!"
我看到“$template...”部分每次都会覆盖文件但是:
-我试图将“使用模板...”部分放入 for 循环中,但没有成功。
-我试图将模板写入一个单独的文件,但如果它不存在,脚本就会出错。
有人可以帮我找出问题出在哪里,我应该如何正确编码? 提前谢谢!
【问题讨论】:
标签: xml windows powershell