I have a PSCredential Object in C# and want to pass it as parameter for this PowerShell Script
This is the PSCredential Object
PSCredential Credential = new PSCredential ( "bla" , blasecurestring)
This is the Script I want to run in C#
powershell.AddScript("$s = New-PSSession -ComputerName '" + serverName + "' -Credential " + Credential);
I couldn't understand the solution which is offered here Pass a Parameter object (PSCredential) inside a ScriptBlock programmatically in C#
EDIT: This thing is working
powershell.AddCommand("New-PSSession").AddParameter("ComputerName", serverName).AddParameter("Credential", Credential);
But how can I save the Session Info in a variable? I need them for the following commands:
powershell.AddScript(@"Invoke-Command -Session $s -ScriptBlock {" + cmdlet + "}");
I found the solution now. It's so easy when you know what you do...
powershell.AddCommand("Set-Variable");
powershell.AddParameter("Name", "cred");
powershell.AddParameter("Value", Credential);
powershell.AddScript(@"$s = New-PSSession -ComputerName '" + serverName + "' -Credential $cred");
powershell.AddScript(@"$a = Invoke-Command -Session $s -ScriptBlock {" + cmdlet + "}");
powershell.AddScript(@"Remove-PSSession -Session $s");
powershell.AddScript(@"echo $a");
Where Credential is the C# PSCredential object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With