簡體   English   中英

C#— Windows Server 2012使用Powershell安裝功能和角色

[英]C# — Windows Server 2012 installing Features and Roles using Powershell

我編寫了一個使用Powershell API安裝Windows角色和功能的應用程序。 它在Windows 2008 R2中可以正常工作,但在Windows 2012中什么也沒有發生。 該程序繼續運行,好像一切都很好,但未安裝任何程序。

我曾嘗試制作程序.NET v4.5(它是.NET v2.0),但這沒有幫助。 我到處都在Google上搜索,找不到適合的解決方案。 實際上,大多數人說使用Windows 2008 R2中可用的那種實現。 這是我的代碼:

        public bool runPowerShell(string command, string args)
    {
        mLogger myLogger = mLogger.instance;  //How I log stuff in my application.
        bool done = false; //default Return value.
        const string path = @"C:\\XMPLogs\\Roles and Features"; //Where Powershell output will go.

        //Make sure Powershell log directory is there.
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

        //Start a new Powershell instance.
        PowerShell powershell = PowerShell.Create();
        System.Collections.ObjectModel.Collection<PSObject> output = new System.Collections.ObjectModel.Collection<PSObject>();
        StringBuilder strBuilder = new StringBuilder(); //Used to examine results (for testing)
        powershell.AddScript(@"Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted");
        powershell.AddScript(@"Import-Module ServerManager");
        //powershell.Invoke();

        powershell.AddScript(command + " " + args);
        try
        {

            output = powershell.Invoke();

            // Construct a StringBuilder to examine the output of Invoke()
            foreach (PSObject obj in output)
                strBuilder.AppendLine(obj.ToString());

            // Show the StringBuilder to see results (always empty!)
            MessageBox.Show(strBuilder.ToString());
            done = true;
        }
        catch (Exception ex)
        {
            string test = ex.ToString();
            MessageBox.Show(test);
            myLogger.output("ERRO", "PowerShell command " + command
                + "failed to run with arguments \"" + args + "\".  Message:  " + ex.ToString());
            done = false;
        }

        powershell.Dispose();
        return done;
    }

我會這樣調用該方法:

runPowerShell("add-windowsfeature", "-name FS-FileServer -logpath \"c:\\XMPLogs\\Roles and Features\\File Services.log\"");

“輸出”對象中永遠沒有任何數據,日志文件也沒有。 所以,我不知道發生了什么。 我確實知道是否在方法調用中使用了兩個參數,然后將它們手動輸入到Powershell提示符中,安裝運行就完美無缺。

誰能看到我在Windows Server 2012上的這種實現方式做錯了什么?

謝謝。

沒有更多信息,很難知道這里的真正問題是什么。 也許您不是以管理員身份運行應用程序,因此不允許添加Windows功能?

但是,PowerShell在終止錯誤(將阻止執行並引發異常,應使您的代碼進入catch語句)和非終止錯誤(僅寫入錯誤流而不會輸入catch語句)之間有所不同。

如果運行Get-Help Write-ErrorGet-Help about_ThrowGet-Help about_Try_Catch_Finally ,則可以閱讀有關此內容的更多信息。

我猜想您的powershell命令會導致非終止錯誤。 若要確定是否發生了非終止錯誤,可以檢查powershell.HadErrors屬性,並獲取錯誤消息,可以閱讀powershell.Streams.Error屬性。

這可能會幫助您找出正在發生的錯誤,並有望幫助您解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM