DevOps | Scripts | Automation

Powershell

How to: Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named ‘op_Addition’ – PowerShell

This error generally occurs while adding output to the PSCustomObject. When you don’t declare the output as an array and you directly append the output to the PSCustomObject then this error occurs. For example,

foreach($service in (Get-Service)){
  $output += [PSCustomObject]@{
                ServiceName = $service.Name
                Status = $service.Status
                StartType = $service.StartType
             }
}

$output

In the above example, $output is not declared earlier as an Array. So the error will be generated

It says that the PSCustomObject can’t perform Op_Addition (Operation Addition). To resolve this issue, we can declare $output as an array and it will solve the problem.

$output = @()
foreach($service in (Get-Service)){
  $output += [PSCustomObject]@{
                ServiceName = $service.Name
                Status = $service.Status
                StartType = $service.StartType
             }
}

$output

We can’t declare $output as a String because it will produce the output in a string manner. For example,

$output = ""
foreach($service in (Get-Service)){
  $output += [PSCustomObject]@{
                ServiceName = $service.Name
                Status = $service.Status
                StartType = $service.StartType
             }
}

$output

Output:

Loading