我正在尝试将多个对象属性组合到一个对象中。
当我有以下代码时,对象属性将被组合。
$computer = gwmi win32_computersystem | select numberOfProcessors, NumberOfLogicalProcessors, HypervisorPresent
$osInfo = gwmi win32_operatingsystem | select version, caption, serialnumber, osarchitecture
Foreach($p in Get-Member -InputObject $osInfo -MemberType NoteProperty)
{
 Add-Member -InputObject $computer -MemberType NoteProperty  -Name $p.Name -Value $osInfo.$($p.Name) -Force
}
$computer
Run Code Online (Sandbox Code Playgroud)
但是,如果我将上述计算机和osInfo变量替换为
$computer = Get-Process | Select processname, path
$osInfo = Get-Service | Select name, status
Run Code Online (Sandbox Code Playgroud)
那么for循环执行后$computer变量就不具有变量的属性了。$osInfo即:第二个对象不与第一个对象组合。
原始代码处理返回与同一源相关的两个单个对象的 cmdlet。
您尝试将其与返回多个对象数组的 cmdlet 一起使用。
下面基本上合并了两个数组。
$computer = 'Server01'
$collection = @()
$services = Get-Service | Select name, status
$processes = Get-Process | Select processname, path
foreach ($service in $services) {
    $collection += [pscustomobject] @{
        ServiceName   = $service.name
        ServiceStatus = $service.status
        ProcessName   = ""
        ProcessPath   = ""
    }
}
foreach ($process in $processes) {
    $collection += [pscustomobject] @{
        ServiceName   = ""
        ServiceStatus = ""
        ProcessName   = $process.processname
        ProcessPath   = $process.path
    }
}
$collection
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我只会使用$services和这两行来$processes完成。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           37537 次  |  
        
|   最近记录:  |