powershell add item to psobject

This topic contains 3 replies, has 3 voices, and was last updated by  Hans Westelaken 7 months, 3 weeks ago.

  • Author
    Posts
  • #62991

    Hans Westelaken
    Participant

    When executing the script, I get an error in the command "$CSV += $NieuwePC"
    Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
    I do not understand what this message meant and how to solve it.

    $PATH = 'N:\ApplicatieGebruik\applicatie gebruik.csv'
    $CSV = Import-Csv $PATH
    $Datum = get-date -format g

    $Computer = $CSV | where {$_.Werkplek -eq "$env:computername"}
    if($Computer) # computer bestaat
    {
    foreach($row in $CSV)
    {
    if ($row.Werkplek -eq "$env:computername")
    {
    "gevonden"
    $row.Datum = $Datum
    $row.Gebruiker = $env:username
    }
    }
    }
    else # computer bestaat niet
    {
    $NieuwePC = [pscustomobject] @{Werkplek = "$env:computername"; datum = "$Datum"; Gebruiker = "$env:username"}
    $CSV += $NieuwePC
    "werkplek toevoegen"
    }

    $CSV | Sort-Object { $_.Datum -as [datetime]} -Descending | Export-Csv $PATH -NoTypeInformation

  • #62992

    Paul Frankovich
    Participant

    From what I can tell, you are trying to add a new PC to a CSV if it doesn't exist or update an existing record if it does. The error is because the PSCustomObject doesn't have an add method. I would write this as a function and let the pipeline take care of adding it the the CSV.

  • #62997

    Daniel Krebs
    Moderator

    If you replace below line

    $CSV = Import-Csv $PATH

    with

    $CSV = [System.Collections.Generic.List[PSCustomObject]](Import-Csv $PATH)

    it should work.

  • #63006

    Hans Westelaken
    Participant

    Thank you very much Daniel
    works like a charm.
    I'm happy.

You must be logged in to reply to this topic.