I can't seem to be able to pass in a reference parameter to PowerShell from C#. I keep getting the following error:
"System.Management.Automation.ParentContainsErrorRecordException: Cannot process argument transformation on parameter 'Test'. Reference type is expected in argument."
Example:
For the simple script:
Param (
[ref]
$Test
)
$Test.Value = "Hello"
Write-Output $Test
And here's the C# code:
string script = {script code from above};
PowerShell ps = PowerShell.Create();
ps = ps.AddScript($"New-Variable -Name \"Test\" -Value \"Foo\""); // creates variable first
ps = ps.AddScript(script)
.AddParameter("Test", "([ref]$Test)"); // trying to pass reference variable to script code
ps.Invoke(); // when invoked, generates error "Reference type is expected in argument
I've tried AddParameter as well as AddArgument.
What I have gotten to work is to create my script first as a script block:
ps.AddScript("$sb = { ... script code ...}"); // creates script block in PowerShell
ps.AddScript("& $sb -Test ([ref]$Test)"); // executes script block and passes reference parameter
ps.AddScript("$Test"); // creates output that shows reference variable has been changed
Any help?