Mark Wragg
Mark Wragg

Reputation: 23395

Adding an item to an existing object loaded via Import-Clixml with PowerShell

I can't get my head around how to add an existing item to an object that (in this instance) has been loaded via Import-CliXML.

My XML file is a simple object that contains a table of role and assignee pairs. When the file doesn't exist, it works correctly. If the file contains an existing role it updates it successfully. However if the role being set does not exist in the file (and therefore should be added to it), I get this error:

Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
At C:\Users\me\Set-TeamRole.ps1:33 char:9
$TeamRoles += $RoleObj

Here is my code:

function Set-TeamRole {
    Param(
        [string]$Role,
        [string]$Assignee,
        [string]$Path = 'TeamRoles.xml'
    )

    if (Test-Path $Path) {
        $TeamRoles = Import-Clixml $Path
        $ExistingRole = $TeamRoles | Where {$_.Role -eq $Role}
    } else {
        $TeamRoles = @()
    }

    if ($ExistingRole) {
        $ExistingRole.Assignee = $Assignee
    } else {
        $RoleObj = New-Object -TypeName PSCustomObject

        $NewRole = @{
            Role = $Role;
            Assignee = $Assignee;
        }

        Add-Member $NewRole -InputObject $RoleObj
        $TeamRoles += $RoleObj
    }

    $TeamRoles | Export-Clixml -Path $Path -Force
}

Upvotes: 0

Views: 1399

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200443

When the input XML file contains only one object, the statement

$TeamRoles = Import-Clixml $Path

will not produce an array, and consequentially the statement

$TeamRoles += $RoleObj

will try to invoke an addition operation on that object instead of appending to an array (and fail if that object doesn't support such an operation).

You can force the imported data into an array by running Import-Clixml in an array subexpression operator:

$TeamRoles = @(Import-Clixml $Path)

Upvotes: 1

Related Questions