I'm running C# PowerShell code on a remote system and need to get the value of a local variable. PowerShell has a cmdlet named Get-Variable
which I'm trying to use. This is my code for trying to fetch the relevant collection of PSVariables (which obviously should contain just one):
psShell.AddScript($"$text = 'someValue'");
psShell.Invoke();
psShell.Commands.Clear();
psShell.AddCommand("Get-Variable")
.AddParameter("Name", "text");
var v = psShell.Invoke<PSVariable>();
Problem is on the last line, I get the following exception:
Cannot convert the "System.Management.Automation.PSVariable" value of type "Deserialized.System.Management.Automation.PSVariable" to type "System.Management.Automation.PSVariable".
Anyone know how to solve this ?
Also, I know of the SessionStateProxy method mentioned on StackOverflow, but as this post of mine shows, it doesn't work for my scenario for some reason.