2

So I found a strange behavior:
I have an imported CSV file with these titles:

$connections | Get-Member
Name                MemberType   Definition
----                ----------   ----------
Equals              Method       bool Equals(System.Object obj)
GetHashCode         Method       int GetHashCode()
GetType             Method       type GetType()
ToString            Method       string ToString()
Access Method       NoteProperty System.String Access Method=SSH
Accessable          NoteProperty System.String Accessable=N/A
Application         NoteProperty System.String Application=Test
Authentication type NoteProperty System.String Authentication type=rsa
Node                NoteProperty System.String Node=ComputerName
Port                NoteProperty System.String Port=22
User                NoteProperty System.String User=User

Now, if I make a new variable from one line

$x = $connections[0]

Then change something in $x

$x.Accessable = $true

The change will be visible in $connections[0].

$connections[0].Accessable
True

Is this a normal behavior? If so how can I make a new variable with a similar object as that line?

Edit: Powershell array assignment assigns variable, not value? is about arrays, or multidimensional arrays, this question is about object transfer (copy). The simple answers on that page does not work in this case. Issue still happens.

2
  • Not completely duplicate IMO. Part of question "how to deal with this particular object" not answered there. Commented Jan 1, 2015 at 15:40
  • It is a duplicate because it is about copy by reference. The duplicate has a solution for that. Although this question also contains an alternative. Commented Jan 1, 2015 at 23:58

1 Answer 1

2

Yes, it is normal behavior, it is how reference types work. You need to make copy of object:

$x = $connections[0].PSObject.Copy()
Sign up to request clarification or add additional context in comments.

6 Comments

Works OK, one more question thou. How should I implement this, if I would like to use a Where-Object on the $connections object? Example: $x = $connections | Where-Object {$_.Application -eq "Test"}
Do you mean, that you want to change objects inside Where-Object cmdlet, or you want to just filter them in Where-Object and change them latter?
Filter, than change later.
$connections|Where-Object {...}|ForEach-Object {$_.PSObject.Copy()}
@Tumpi So, all you actually need is to make a copy just before you change them.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.