How to define a named parameter as [ref] in PowerShell

I am trying to use the [ref] named parameters. However, I get an error message:

 workflow Test { Param([Parameter(Mandatory=$true)][String][ref]$someString) write-verbose $someString -Verbose $someString = "this is the new string" } cls $someString = "hi" Test -someString [ref]$someString write-host $someString #Error: Cannot process argument transformation on parameter 'someString'. Reference type is expected in argument. 

How can I fix this problem?

+19
powershell powershell-workflow
source share
2 answers

I noticed that you are using a "workflow" in your example parameter [ref]. For simplicity, let's call it a “function” and return to the “workflow” later.

Three things need to be changed in the code:

  1. When passing the [ref] parameter to a function, enclose the parameter in parentheses () .
  2. When using the [ref] parameter inside a function, refer to $ variable.value
  3. Remove the type [string] from the definition of your parameter. It can be [string] or [link], but not both at the same time.

Here is the code that works:

 function Test { Param([Parameter(Mandatory=$true)][ref]$someString) write-verbose $someString.value -Verbose $someString.value = "this is the new string" } cls $someString = "hi" Test -someString ([ref]$someString) write-host $someString 

As for the "workflows." They are very limited, read PowerShell Workflows: Limitations . In particular, you cannot call a method on an object in a workflow. This will break the line:

 $someString.value = "this is the new string" 

I don’t think that using the [ref] parameters in the workflow is appropriate due to the limitations of the workflow.

+30
source share

I felt that I needed to write this additional very simplified answer, since this was the first Google hit when looking for information about using reference parameters in Powershell functions. Although your question was not about functions, but about workflows:

An example of using reference parameters in functions (does not work with a workflow):

 Function myFunction ([ref]$aString) { $aString.Value = "newValue"; } $localVariable = "oldValue" Write-Host $localVariable # Outputs: oldValue myFunction ([ref]$localVariable); Write-Host $localVariable # Outputs: newValue 

Using functions, you can define a parameter as a reference and another type, for example like this (but not with workflows):

 Function myFunction ([ref][string]$aString) { $aString.Value = "newValue"; } $localVariable = "oldValue" Write-Host $localVariable # Outputs: oldValue myFunction ([ref]$localVariable); Write-Host $localVariable # Outputs: newValue 

I agree with Jan, you should not try to use reference parameters in workflows due to workflow restrictions (method call for objects): https://blogs.technet.microsoft.com/heyscriptingguy/2013/01/02/powershell- workflows-restrictions /

+3
source share

All Articles