PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

Geek Sync Live

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.

Latest Scripts

09-19-2015 - Bryan's Games Galore!
09-18-2015 - Bryan's Process Help
09-06-2015 - Bryan's Wifi Pinger

As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Cloning Objects

In our previous tips we illustrated that PowerShell stores objects by reference. If you want to create a copy, you would have to manually copy the object with all of its properties.

Here is a simple way of cloning objects:

$object1 = @{Name='Weltner'; ID=12 }
$object2 = @{Name='Frank'; ID=99 }

$a = $object1, $object2

# clone entire object by serializing it back and forth:
$b = $a | ConvertTo-Json -Depth 99 | ConvertFrom-Json

$b[0].Name = 'changed'

Note that serialization may change the object types in the copied object, though:

PS C:\> $a[0].GetType().FullName

PS C:\> $b[0].GetType().FullName

PS C:\>

Twitter This Tip! ReTweet this Tip!

Copyright 2012 PowerShell.com. All rights reserved.