Help using custom psobject while using foreach to loop through computer list

This topic contains 1 reply, has 2 voices, and was last updated by  Don Jones 9 months, 1 week ago.

  • Author
    Posts
  • #61828

    nick c
    Participant

    I am still new to learning powershell and I am having trouble with the code I wrote below. I keep receiving an RPC error when trying to send the commands to remote computers. Please look my code over to let me know what I'm doing wrong. Thanks for your help!

    
    #variables
    
    $machines = get-content C:\Users\office\Desktop\Machines.txt
    $array = @()
    
    foreach ($machine in $machines){
    $FreeGB = (gwmi win32_logicaldisk -ComputerName $machine -Filter drivetype=3).freespace /1gb -as [int]
    $Serial = (gwmi win32_bios -ComputerName $machine).serialnumber
    $Architecture = (gwmi win32_operatingsystem -ComputerName $machine).osarchitecture
    $OS = (gwmi win32_operatingsystem -ComputerName $machine).caption
    $computername = (gwmi win32_operatingsystem -ComputerName $machine).pscomputername
    
    $properties = @{Computer = $computername;
    FreeGB = $FreeGB;
    Serial = $Serial;
    Architecture = $Architecture;
    OS = $OS
    
    $output = New-Object psobject -Property $properties}
    
    $array += $output}
    Write-Output $output | ft -AutoSize
    
    
  • #61830

    Don Jones
    Keymaster

    So, a couple of observations.

    You're burning a lot of time querying the same WMI class multiple times. Just query it once, get all the properties, and then pick whichever ones you want.

    $wmi_os = Gwmi Win32_Operatingsystem
    $os = $wmi_os.caption
    

    There's no need whatsoever to accumulate your results in an array. Just write-output each object as you create it. See https://devopscollective.gitbooks.io/the-big-book-of-powershell-gotchas/content/manuscript/accumulating-output-in-a-function.html.

    Now, in regards to your actual question, it'd be a lot easier to help if you shared the error message you're getting.

You must be logged in to reply to this topic.