powershell add item to psobject

Welcome Forums General PowerShell Q&A powershell add item to psobject

This topic contains 3 replies, has 3 voices, and was last updated by

1 year, 8 months ago.

  • Author
  • #62991


    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")
    $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


    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


    If you replace below line

    $CSV = Import-Csv $PATH


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

    it should work.

  • #63006


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

The topic ‘powershell add item to psobject’ is closed to new replies.