9

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 + "}");
1
  • Maybe it is possible to go without pipelines Commented Dec 7, 2012 at 10:15

1 Answer 1

12

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

Sign up to request clarification or add additional context in comments.

3 Comments

Why don't you use C# instead of adding all the scripts? You don't need to create the session by yourself. Take a look at RunspaceFactory.CreateRunspace and PowerShell.Runspace.
Hi d.g, can you please let me know what powershell is? Is that a RunSpace object?
What is the difference between ps.AddParameter and ps.AddArgument?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.