#weirs PS behavior? writing out variable type fixed issue?

5 messages · Page 1 of 1 (latest)

tidal meteor
#

Hi, I fixed the problem now but I'm just curious why it hapend. So, Tl;Dr, my code threw this error:

Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
At C:\Important\programming\powershell\JLang\varWork.ps1:13 char:5
+     $variables += [PSCustomObject]@{
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

in this function

function createVar {
    param(
        $name,
        $value,
        $variables
    )

    #$name
    #$value

    $variables.GetType().Name

    $variables += [PSCustomObject]@{
        Name  = $name
        Value = $value
        Type  = $value.GetType().Name
    }

    return $variables 
}

and didn't work as intended when I didn't parsed $variables, but when I added the line $variables.GetType().Name it fixed itself, it didn't threw this error and worked fine, how could just this fix it? It seems so weird because that line should just do side effect and side effects shouldn't change code behaviour? Am I missing something here? BTW: I'm pretty new to PowerShell but not programming

round wind
#

Demo: ```ps
function createVar {
param ( $variables )
$variables += [PSCustomObject]@{ a = 'b' }
}

This will throw because 1 is a scalar and there's no way to add a custom object to that:

createVar 1

This will also throw, it's still a scalar even if the type matches now

createVar ([PSCustomObject]@{ c = 'd' })

This will succeed because the incoming value is an array and you can create a new array based on that. Note that this does not mutate the original value

createVar ([PSCustomObject]@{ c = 'd' }, [PSCustomObject]@{ e = 'f' })

There's no output from the demo function above, it will simply not throw an error if you get the input right.

Should have better parameter validation, etc, etc.
native inlet
#

What is your original goal? To view properties that an object has -- or to modify it?

This isn't perfect, but a simple trick is reading PSObject.Properties which lets you loop all properties

$Target = Get-Item .\New-TerminalStackedChangelog.ps1
$Target.PSObject.Properties | Ft Name, Value, TypeNameOfValue -AutoSize

You can define a formatter that prevents long lines from messing up the table

#

It's a little counter intuitive a tfirst, but powershell implicitly outputs values to the output stream if you don't assign them or use them as parameters
this function is outputting 2 values every call

[a] is a string and [b] is your object

A note for the future: Because output is implicit, the return statement is not actually required there.

At least in powershell, think of return as control flow rather than returning a value.