我正在解析 Windows 系统 ($system) 的所有登录。我正在尝试获取域、用户、 session ID 的元组/数组。
$logged_on_users = Get-WmiObject Win32_LoggedOnUser -ComputerName $system
然后我调用类型的函数在每个值中提取两个变量(Antecedent 和 Depedent):
$all_user_sessions = @()
foreach ($x in $logged_on_users){
$t = @()
$t += $x.GetPropertyValue("Antecedent").tostring()
$t += $x.GetPropertyValue("Dependent").tostring()
$all_user_sessions += $t
}
单行数组理解的语法是什么(如果可能的话)?我有:
$all_user_sessions = ($logged_on_users | % { @($_.GetPropertyValue("Antecedent").tostring(), $_.GetPropertyValue("Dependent").tostring() ) })
当我添加
foreach ($s in $all_user_sessions){
echo $s.GetType().FullName
}
类型是字符串,不是数组。
最佳答案
这听起来有点奇怪,但您需要在 ForEach-Object
循环中的数组前添加一个逗号:
$all_user_sessions = ($logged_on_users | % { ,@($_.GetPropertyValue("Antecedent").tostring(), $_.GetPropertyValue("Dependent").tostring() ) })
在编写代码时,您正在将所有内容添加到一个数组中。像这样放置逗号将创建每个索引的数组(实际上是一个对象)。
关于数组理解中的 PowerShell 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090546/