2010-10-18 21 views
2

Je tente d'exécuter une applet de commande HPC par programmation pour modifier les informations d'identification d'installation HPC sur un ordinateur distant. Si exécuter l'applet de commande localement, il est assez simple:Passage d'un objet Parameter (PSCredential) à l'intérieur d'un ScriptBlock par programmation en C#

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(); 

Cependant, si je veux faire la même chose avec PowerShell à distance, je dois exécuter Invoke-Command et passer les informations d'identification à l'ScriptBlock à l'intérieur du commandement. Comment puis je faire ça? Il pourrait ressembler à quelque chose comme ça, sauf que je dois passer dans les informations d'identification comme un objet binded au paramètre InstallCredential à l'intérieur du ScriptBlock au lieu d'une chaîne:

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(); 

Répondre

1

je continuerais à utiliser addCommand pour Invoke-Command (au lieu de addScript). Ajouter les paramètres pour Invoke-Command et quand vous obtenez au paramètre Scriptblock, assurez-vous que le scriptblock définit un param() bloc par exemple:

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

ajouter le paramètre ArgumentList à la commande Invoke-Command et définissez la valeur sur les informations d'identification tu as créé.

7
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"); 

Où Credential est le C# PSCredential objet

J'utilise ce, peut-être il peut vous aider.