[英]Powershell batch of commands response into JSON
I'm trying to capture a list of users and groups on my windows host.我正在尝试捕获 Windows 主机上的用户和组列表。 I can capture the user and groups info and assign them to varaibles $users and $groups with the following commands:
我可以使用以下命令捕获用户和组信息并将它们分配给变量 $users 和 $groups:
$groups=$(Get-WmiObject win32_group | Select Name | Sort Name); $users=$(Get-WmiObject -Class Win32_UserAccount | Select Name | Sort Name)
What I can't figure out is how to pass these to the ConvertTo-JSON function where they each get their own keys ie, I'd like the response to look like this:我无法弄清楚的是如何将这些传递给 ConvertTo-JSON 函数,在那里它们每个人都获得自己的密钥,即,我希望响应如下所示:
{
"users": ["john", "geroge", "ringo"],
"groups": ["drums", "guitar"]
}
I have tried a few variations of this, but can't quite get the correct syntax for powershell and the ConvertTo-JSON function.我已经尝试了一些变体,但不能完全获得 powershell 和 ConvertTo-JSON 函数的正确语法。
$jsonBlob=$(\"groups\" : $(groups), \"users"\ : $(users); ConvertTo-Json $jsonBlob;
Any suggestions on how to achieve this?关于如何实现这一目标的任何建议?
Create a PSCustomObject
and Pipe that to ConvertTo-Json
创建一个
PSCustomObject
并将其通过管道传输到ConvertTo-Json
$groups = Get-WmiObject -Class Win32_Group | Sort-Object Name
$users = Get-WmiObject -Class Win32_UserAccount | Sort-Object Name
$jsonBlob = [PSCustomObject]@{"users" = $users.Name;"groups" = $groups.Name} | ConvertTo-Json
I would recommend using DirectorySearcher to look up users and groups.我建议使用 DirectorySearcher 来查找用户和组。 It will be more efficient and focused on just the name.
它将更有效率,并且只关注名称。
$usearcher = [adsisearcher]'(&(objectCategory=User)(objectclass=person))'
$gsearcher = [adsisearcher]'(objectCategory=group)'
$usearcher.PropertiesToLoad.Add("name")
$gsearcher.PropertiesToLoad.Add("name")
$usearcher.SizeLimit = 1000
$gsearcher.SizeLimit = 1000
$obj = [pscustomobject]@{
users = $usearcher.FindAll() | % { $_.properties['name'][0] }
groups = $gsearcher.FindAll() | % { $_.properties['name'][0] }
}
$json = $obj | ConvertTo-Json
This will run on the local domain of the account you are using to run this.这将在您用来运行它的帐户的本地域上运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.