Search code examples
arraysvariablespowershellcsvdeclare

Powershell variable declare with CSV object


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.


Solution

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

    $x = $connections[0].PSObject.Copy()