Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass PSCredential object from C# code to Powershell Function

Tags:

c#

powershell

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 + "}");
like image 503
d.g Avatar asked Dec 07 '12 10:12

d.g


1 Answers

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

like image 178
d.g Avatar answered Sep 19 '22 14:09

d.g