1

I am writing a powershell function which executes a foreach loop. The loops goes through each server name in a text file list of hosts and then for each one, pulls the free space on C and then assigns it to a variable.

Then another loop goes through the list again and gets the name of the hosts and then adds it to a variable.

Then I have a variable which takes the two variables containing the data pulled from the loops and export it to CSV. It puts the correct data in the CSV but I would like to format it in a certain way. The current csv output is (for 4 entries for example) 'server 1' 'server2' 'server 3' 'server 4' 'diskspacevalue1' '2' '3' '4' etc.

So Im at the point where I have all the data I need but I need to arrange it so that one cell has the server name and then the cell next to it has it's respective value.

I have a feeling I should be creating objects or using an array but wondered if there was anything I could add to implement the formatting I want based on the script I have written so far?

function diskcheck {
    $freespace = Get-Content C:\temp2\DiskspaceProj\hosts.txt | Foreach-Object {
        Get-WmiObject win32_logicaldisk -Computername $_ -Filter "DeviceID='C:'" | select -ExpandProperty "FreeSpace"
    }
    $hostName = Get-Content C:\temp2\DiskspaceProj\hosts.txt | Foreach-Object {
        Get-WmiObject Win32_ComputerSystem -ComputerName $_ | Select -ExpandProperty "Name"
    }
    $output = "$hostname, $freespace" | echo > C:\temp2\DiskspaceProj\diskspace.csv
}
diskcheck

1 Answer 1

3

Don't maintain two separate array - create one array of objects that contain both properties:

function diskcheck 
{
    param(
        [string]$Path = 'C:\temp2\DiskspaceProj\hosts.txt'
    )

    Get-Content $Path |ForEach-Object {
        New-Object psobject -Property @{
            Hostname = Get-WmiObject Win32_ComputerSystem -ComputerName $_ |Select -ExpandProperty Name
            FreeSpace = Get-WmiObject win32_logicaldisk -Computername $_ -Filter "DeviceID='C:'" | select -ExpandProperty FreeSpace
        }
    }
}

Then use Export-CSV to export the list to a file:

diskcheck |Select Hostname,FreeSpace |Export-Csv C:\diskspace_output.csv -NoTypeInformation
Sign up to request clarification or add additional context in comments.

1 Comment

That runs great. However I am getting a strange output in the CSV. The values show as 'System.Object[]' in each cell. Any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.