2014-12-31 37 views
2

所以,我發現了一個奇怪的現象:
我有這些頭銜導入CSV文件:PowerShell的變量,CSV對象申報

$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 

現在,如果我提出一個新的變量從一行

$x = $connections[0] 

然後改變一些東西在$ X

$x.Accessable = $true 

變化會在$ connections [0]中可見。

$connections[0].Accessable 
True 

這是正常行爲嗎?如果是這樣,我怎樣才能創建一個新的變量與該行的類似對象?

編輯: Powershell array assignment assigns variable, not value?是關於數組或多維數組,這個問題是關於對象傳輸(複製)的。這個頁面上的簡單答案在這種情況下不起作用。問題仍然存在。

+0

不完全重複IMO。部分問題「如何處理這個特定的對象」在那裏沒有回答。 – PetSerAl

+0

它是重複的,因爲它是關於複製的參考。重複有一個解決方案。雖然這個問題也包含一個替代方案。 – JasonMArcher

回答

2

是的,這是正常的行爲,它是如何參考類型的工作。您需要複製對象:

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

工作好,還有一個問題你。我應該如何實現這一點,如果我想在$ connections對象上使用Where-Object? 例如: $ x = $ connections | Where-Object {$ _。Application -eq「Test」} – Tumpi

+0

您的意思是說,您要更改Where-Object cmdlet中的對象,還是隻想在Where-Object中過濾它們並將其更改爲後者? – PetSerAl

+0

過濾,比稍後更改。 – Tumpi