New filters on the Home Feed, take a look!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

4
Object Scopes
Post Body

Hi r/powershell,

I am confused and I need a sanity check about scopes. Why is the output of this script changed?

Function ChangeIt {

    $Object.State = "Changed"

}

$Object = [PsCustomObject] @{

    State  = "Original"

}

ChangeIt

$Object.State

I always thought this would only work if I pass the object into the function as a parameter like this:

Function ChangeIt {

    Param(

        [PsCustomObject]$InputObject

    )

    $InputObject.State = "Changed"

}

$Object = [PsCustomObject] @{

    State  = "Original"

}

ChangeIt -InputObject $Object

$Object.State

But apparently, scopes don't seem to exist for [PsCustomObjects], or objects in general? Why do I even bother to pass objects as parameters into my functions then, if I have write access to them anyway?

Author
Account Strength
90%
Account Age
15 years
Verified Email
Yes
Verified Flair
No
Total Karma
4,540
Link Karma
3,347
Comment Karma
1,193
Profile updated: 4 days ago
Posts updated: 6 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
6 years ago