Question:
I have a PSCredential Object in C# and want to pass it as parameter for this PowerShell Script
This is the PSCredential Object
1 2 |
PSCredential Credential = new PSCredential ( "bla" , blasecurestring) |
This is the Script I want to run in C#
1 2 |
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
1 2 |
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:
1 2 |
powershell.AddScript(@"Invoke-Command -Session $s -ScriptBlock {" + cmdlet + "}"); |
Answer:
I found the solution now. It’s so easy when you know what you do…
1 2 3 4 5 6 7 8 9 |
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