Skip Parameter object (PSCredential) inside ScriptBlock programmatically in C #

I am trying to run the HPC cmdlet programmatically to change the HPC installation credentials on a remote computer. Running the cmdlet locally is pretty simple:

Runspace rs = GetPowerShellRunspace(); rs.Open(); Pipeline pipeline = rs.CreatePipeline(); PSCredential credential = new PSCredential(domainAccount, newPassword); Command cmd = new Command("Set-HpcClusterProperty"); cmd.Parameters.Add("InstallCredential", credential); pipeline.Commands.Add(cmd); Collection<PSObject> ret = pipeline.Invoke(); 

However, if I want to do the same with the remote PowerShell, I need to run Invoke-Command and pass the ScriptBlock credentials inside Command. How can i do this? It might look something like this, except that I need to pass the credentials as an object bound to the InstallCredential parameter inside the ScriptBlock instead of the line:

 Pipeline pipeline = rs.CreatePipeline(); PSCredential credential = new PSCredential(domainAccount, newPassword); pipeline.Commands.AddScript(string.Format( CultureInfo.InvariantCulture, "Invoke-Command -ComputerName {0} -ScriptBlock {{ Set-HpcClusterProperty -InstallCredential {1} }}", nodeName, credential)); Collection<PSObject> ret = pipeline.Invoke(); 
+2
source share
2 answers

I would continue to use AddCommand for Invoke-Command (instead of AddScript). Add parameters for Invoke-Command, and when you go to the Scriptblock parameter, make sure the script block defines the param () block, for example:

 {param($cred) Set-HpcClusterProperty -InstallCredential $cred} 

Then add the ArgumentList parameter to the Invoke-Command and set the value for the credentials you created.

+1
source
 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

I use this, maybe this can help you.

+7
source

All Articles