2012-04-06 14 views
1

私はC#から実行したいPowerShellスクリプトを持っています。スクリプトの内容は、C#から変数を含む複数のPowershellコマンドを実行

$w = Get-SPWebApplication "http://mysite/" 
$w.UseClaimsAuthentication = 1 
$w.Update() 
$w.ProvisionGlobally() 
$w.MigrateUsers($True) 

であり、サイトをクレームベース認証に設定するために使用されます。私はC#から複数のコマンドを実行する方法を知っていますが、変数$ wを考慮してスクリプト全体をどのように実行するかはわかりません。

PowerShell OPowerShell = null; 
Runspace OSPRunSpace = null; 
RunspaceConfiguration OSPRSConfiguration = RunspaceConfiguration.Create(); 
PSSnapInException OExSnapIn = null; 
//Add a snap in for SharePoint. This will include all the power shell commands for SharePoint 
PSSnapInInfo OSnapInInfo = OSPRSConfiguration.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out OExSnapIn); 
OSPRunSpace = RunspaceFactory.CreateRunspace(OSPRSConfiguration); 
OPowerShell = PowerShell.Create(); 
OPowerShell.Runspace = OSPRunSpace; 
Command Cmd1 = new Command("Get-SPWebApplication"); 
Cmd1.Parameters.Add("http://mysite/"); 
OPowerShell.Commands.AddCommand(Cmd1); 
// Another command 
// Another command 
OSPRunSpace.Open(); 
OPowerShell.Invoke(); 
OSPRunSpace.Close(); 

コマンドを別々のコマンドとして追加するか、スクリプトをファイルに保存して実行するにはどうすればよいですか?ベストプラクティスは何ですか?

答えて

3

は、スクリプトを含む文字列を追加するAddScriptメソッドを使用することができます。

OPowerShell.Commands.AddScript("@ 
$w = Get-SPWebApplication ""http://mysite/"" 
$w.UseClaimsAuthentication = 1 
$w.Update() 
$w.ProvisionGlobally() 
$w.MigrateUsers($True) 
"); 

あなたはそれを呼び出す前に、パイプラインに複数のスクリプトの抜粋を追加することができます。

OPowerShell.Commands.AddScript("@ 
$w = Get-SPWebApplication $args[0] 
... 
"); 
OPowerShell.Commands.AddParameter(null, "http://mysite/"); 

ます。またRunspace Samples on MSDNを見てすることができます:あなたはまた、同様に、スクリプトにパラメータを渡すことができます。

---フェルダー

関連する問題