Splatting after passing a hash table by reference in Powershell

I ran into a problem when I passed a hash table, referring to a function for splatting purposes. How can i fix this?

Function AllMyChildren { param ( [ref]$ReferenceToHash } get-childitem @ReferenceToHash.Value # etc.etc. } $MyHash = @{ 'path' = '*' 'include' = '*.ps1' 'name' = $null } AllMyChildren ([ref]$MyHash) 

Result: error ("Spaced variables cannot be used as part of a property or array expression. Assign the result of the expression to a temporary variable, and then split the temporary variable.").

Tried to do this:

 $newVariable = $ReferenceToHash.Value get-childitem @NewVariable 

This worked and seemed correct for the error message. Is this the preferred syntax in this case?

+4
source share
1 answer

1) Passing hash tables (or any instance of classes, that is, reference types) using [ref] does not make sense, since they are always passed by reference themselves. [ref] used with type values ​​(scalars and instances of structures).

2) The splatting operator can be applied to a variable directly, and not to an expression.

Thus, to solve the problem, just pass the hash table in the function as it is:

 Function AllMyChildren { param ( [hashtable]$ReferenceToHash # it is a reference itself ) get-childitem @ReferenceToHash # etc.etc. } $MyHash = @{ 'path' = '*' 'include' = '*.ps1' 'name' = $null } AllMyChildren $MyHash 
+4
source

Source: https://habr.com/ru/post/1445314/


All Articles