title: Passing/updating hashtables and arrays by reference in PowerShell
body: <p>As I learn about how Perl and PowerShell differ, I'm trying to pin down differences between passing and updating lists by reference. I <em>think</em> I get the idea now, PowerShell-wise.</p>
  
  <p><strong>Pass a hash table by reference:</strong></p>
  
  <p>When the function is called: It isn't necessary to precede the table's name with <code>[ref]</code>. Within the function: The table's name in the <code>param</code> list can be preceded simply by <code>[hashtable]</code>, not <code>[ref]</code> &#151; (because "as received" it is already a reference; so it was explained to me). If the hash table is to be updated within the function, <code>.Value</code> is not needed when <code>[ref]</code> hasn't been used. IOW: call the function this way: <code>MyFunction $MyHashTable</code>. The function contains:</p>
  
  <pre><code>param([hashtable]$HashNameWithinFunction)
  
  $HashNameWithinFunction.Add('x', 'y')
  </code></pre>
  
  <p><strong>Pass an array by reference:</strong></p>
  
  <p>Both when the function is called and in the function's <code>param()</code> list: the array's name must be preceded by <code>[ref]</code>. When the array is to be updated by reference, <code>.Value</code> must be used. The function is called this way: <code>MyFunction ([ref]$MyArray)</code>. The function contains:</p>
  
  <pre><code>param([ref]$ArrayNameWithinFunction)
  
  $ArrayNameWithinFunction.Value += 'something new'
  </code></pre>
  
  <p>Is my understanding correct? I've tested the above and I know both work. But is there any potential for some subtle error in doing it those ways?</p>
  
  <p>Adding this following reply from Chrstian:</p>
  
  <pre><code>function UpdateArray {
      param([ref]$ArrayNameWithinFunction)
      $ArrayNameWithinFunction.Value += 'xyzzy'
  }
  $MyArray = @('a', 'b', 'c')
  UpdateArray ([ref]$MyArray)
  </code></pre>