none
array loop missing RRS feed

  • Question

  • I am have been working on below script i could not able to find cause of array looping, the problem is when i export into csv with pipe for $result for 3 servers, I get only last server report whereas first 2 are missed, can anyone where i am missing?
    
    $servers=get-content 'servers.txt'
    ForEach($server in $servers){
    
        $result=@()
        $disks=gwmi -computername $server -query "SELECT * FROM Win32_DiskDrive"
        ForEach($disk in $disks){
            $result+=New-Object PSObject -Property @{
                'System'=$disk.SystemName
                'Serial'=$disk.SerialNumber
                'Name'=$disk.Caption
                'Health'=$disk.Status;
                'Drive'=$disk.DeviceID;
                'Partition'=''
                'Size'=[math]::Truncate($disk.Size / 1GB);
                'FreeSpace'='';
                }
            $partitions=gwmi -computername $server -query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} WHERE AssocClass = Win32_DiskDriveToDiskPartition"
            ForEach($partition in $partitions){
                $logicaldisks=gwmi -computername $server -query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} WHERE AssocClass = Win32_LogicalDiskToPartition"
                ForEach($logicaldisk in $logicaldisks){
                    #if($logicaldisk){
                        $result+=New-Object PSObject -Property @{
                        'Label'=$logicaldisk.VolumeName
    		    'System'=$logicaldisk.SystemName
                        'Serial'=$logicaldisk.SerialNumber
                        'Name'=$logicaldisk.Caption
                        'Health'=$logicaldisk.Status;
                        'Drive'=$disk.DeviceID;
                        'Partition'=$logicaldisk.DeviceID;
                        'Size'=[math]::Truncate($logicaldisk.Size / 1GB);
                        'FreeSpace'=[math]::Truncate($logicaldisk.FreeSpace / 1Gb);
                        }
                    #}
                }
            }
        }
    
    }
    $result | Select System,Serial,Drive,Name,Partition,Label,Health,FreeSpace,Size  |  export-csv data.csv 


    regards DJ

    Thursday, December 7, 2017 10:24 AM

Answers

  • Move this: "$result = @()" outside of the loop.  You are erasing it before each server.


    \_(ツ)_/

    • Marked as answer by Dhananjaya-DJ Thursday, December 7, 2017 11:17 AM
    Thursday, December 7, 2017 10:57 AM

All replies