我是新來的C#和Powershell在一起,但我希望創建一個網頁,在後端利用Powershell。我意識到我正在做的事情可以完全用C#完成,但是想知道其他應用程序。在C#中的Powershell返回命令輸出
本質上,我從Web窗體中獲取新的Web應用程序的名稱並獲取經過身份驗證的用戶的用戶名以用於物理路徑映射。
我的Powershell代碼正常工作(即使直接從Pipeline.Commands [0]中複製它),但它在運行時似乎沒有做任何事情。如果我強制使用一個結果變量(例如:make -physicalpath是一個不存在的路徑),但在所有參數都正確的情況下,結果變量中會出現參數錯誤,則變量結果只包含一個空白項。
我看到很多類似的問題,但沒有看到確切的答案。
這聽起來像是C#或IIS Powershell模塊問題嗎?任何想法如何從我的命令中獲得更多信息?
protected void Button1_Click(object sender, System.EventArgs e)
{
String username = getUser();
String physicalPath = "S:\\WebSites\\" + username + "\\public_html\\" + TextBox1.Text;
// Create Powershell Runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
// Create pipeline and add commands
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(
"Import-Module WebAdministration; set-psdebug -trace 1; " +
"New-WebApplication -Site MySite" +
" -Name " + TextBox1.Text +
" -PhysicalPath " + physicalPath +
" -ApplicationPool WebSites -Verbose -force");
pipeline.Commands.Add("Out-String");
// Execute Script
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
// Close runspace
runspace.Close();
//Script results to string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
}
謝謝!
謝謝Jaykul - 我會給你一個嘗試,當我有機會回來。 – user566175 2011-01-10 16:33:12