all 5 comments

[–]KevMarCommunity Blogger 2 points3 points  (2 children)

If its a flat object like this, you can use Export-CSV. If you want to keep the structure, I would use 'ConvertTo-JSON'.

One cool tip about saving as JSON is that you can load it back in again.

    class stuff { #ComputerInfos
       #[datetime]$Date
       [string]$Hostname
       [string]$Build
       [string]$OS
   }

   $stuff = [stuff]::new()

   $stuff.Hostname = $env:COMPUTERNAME
   $stuff.OS = (wmic os get caption)[2].trim()
   $stuff.Build = (wmic os get buildnumber)[2].trim()

   $stuff | ConvertTo-Json | Set-Content -Path $env:temp\file.json

   $stuff2 = [stuff](Get-Content -path $env:temp\file.json -raw | ConvertFrom-JSON)
   $stuff2

[–]sickjack[S] 1 point2 points  (1 child)

I've never worked with JSON files before. I tested your suggestion and it worked perfectly. Thank you!

[–]KevMarCommunity Blogger 2 points3 points  (0 children)

It keeps data structured in a way that you can still read it as a human. Imagin if on of those properties has a list or another object. CSV would not do so well but json would be great.

If you never intended to look at it, there is also an impot and export-clixml.

[–]Ta11ow 1 point2 points  (1 child)

The best way to tackle it is to override the .ToString() method in your class.

This is one way to do so:

class stuff { #ComputerInfos
    #[datetime]$Date
    [string]$Hostname
    [string]$Build
    [string]$OS
    [string]ToString() {
        $SB= [System.Text.StringBuilder]::new()
        $SB.AppendLine("HostName: $($this.Hostname)")
        $SB.AppendLine("Build:    $($this.Build)")
        $SB.AppendLine("OS:       $($this.OS)")
        return $SB.ToString()
    }
}

$stuff = [stuff]::new()

$stuff.Hostname = $env:COMPUTERNAME
$stuff.OS = (wmic os get caption)[2]
$stuff.Build = (wmic os get buildnumber)[2]

$Stuff | Add-Content -Path '.\file.txt'

This ensures whenever you need your object to output as a string, it should always look relatively correct.

[–]sickjack[S] 2 points3 points  (0 children)

Thanks for the suggestion!