数组理解中的 PowerShell 函数

标签 powershell

我正在解析 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/

相关文章:

powershell - 使用 powershell : Unwanted results 从 Outlook 获取今天的约会

powershell - 使用 ConvertTo-JSON 创建 JSON 时出现非法字符 '?' a

powershell - 7zip - powershell 排除带变量的文件/文件夹

powershell - 如何使用 Powershell 将 Set-Content 写入文件?

SQL 查询作为 Powershell 中的事务

powershell - 如何获得特定winrm属性的值?

unit-testing - Pester Mock 不适用于使用脚本 block 的 Invoke-Command

PowerShell 代码整理还是重新格式化?

powershell dsc 3.8.0.0版安装

windows - 7Zip Powershell 不工作