How to pass a PSCredential object from C # code to a Powershell function

I have a PSCredential object in C # and want to pass it as a parameter to this PowerShell Script

This is a PSCredential object.

PSCredential Credential = new PSCredential ( "bla" , blasecurestring) 

This is Script I want to run in C #

 powershell.AddScript("$s = New-PSSession -ComputerName '" + serverName + "' -Credential " + Credential); 

I could not understand the solution proposed here Programmatically pass a Parameter object (PSCredential) inside a ScriptBlock in C #

EDIT: This job works

 powershell.AddCommand("New-PSSession").AddParameter("ComputerName", serverName).AddParameter("Credential", Credential); 

But how can I save session information in a variable? I need them for the following commands:

 powershell.AddScript(@"Invoke-Command -Session $s -ScriptBlock {" + cmdlet + "}"); 
+6
source share
1 answer

I have found a solution now. It's so easy when you know what you are doing ...

 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 a C # PSCredential Object

+8
source

All Articles