我仍在学习Powershell的基础知识,但是我遇到了一个我似乎无法解决的问题,因为我没有足够的知识。
我正在创建一个脚本来执行用户配置文件迁移,我希望代码从本地计算机收集配置文件,将 SID 转换回用户名并将其列在下拉框中(有效),但只列出一个用户。我有这个:
$Profiles = gwmi -Class Win32_UserProfile -Filter ("Special = False")
$output = foreach ($Profile in $Profiles)
{
try
{
$objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.sid)
$objuser = $objsid.Translate([System.Security.Principal.NTAccount])
$objusername = $objuser.value
}
catch
{
$objusername = $profile.sid
}
Write-Host $objuser.value
$array = @($objuser)
有什么想法吗?
啪!
您似乎在foreach
循环的每次迭代中覆盖了$array的内容。相反,请附加到它。
foreach ($Profile in $Profiles)
{
try
{
$objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.sid)
$objuser = $objsid.Translate([System.Security.Principal.NTAccount])
$objusername = $objuser.value
}
catch
{
$objusername = $profile.sid
}
Write-Host $objuser.value
$array += @($objuser)
}
但我可能是错的。您在此处仅粘贴了脚本的一部分(foreach
的大括号不平衡,并且我们无法深入了解该下拉列表是如何填充的),因此以后可能会有一些事情让您感到困惑。
查看代码中的注释。
$Profiles = gwmi -Class Win32_UserProfile -Filter ("Special = False")
#You never output anything in your foreach-loop, so $output will be empty.. Removed Write-Host later in code to fix this
$output = foreach ($Profile in $Profiles) {
try
{
$objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.sid)
$objuser = $objsid.Translate([System.Security.Principal.NTAccount])
$objusername = $objuser.value
}
catch
{
$objusername = $profile.sid
}
#You've already saved "objuser.value to a variable... use it.. :) Also, You're catching returned objects with $output = foreach, so I'd suggest outputing the usernames and not just write them to the console. Replace `Write-Host $objuser.value` with `$objusername`
$objusername
#You never closed your foreachloop. Added }
}
#Output collected usernames
$output
#This will always overwrite $array with a new array containing one user, objuser, only. Removed
#$array = @($objuser)