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

14,288

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

Share:
14,288

Related videos on Youtube

d.g
Author by

d.g

Updated on September 14, 2022

Comments

  • d.g
    d.g over 1 year

    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 + "}");
    
  • Rookian
    Rookian almost 10 years
    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.
  • Bassie
    Bassie about 8 years
    Hi d.g, can you please let me know what powershell is? Is that a RunSpace object?
  • user3752281
    user3752281 about 7 years
    What is the difference between ps.AddParameter and ps.AddArgument?