簡體   English   中英

從 C# 調用 Powershell cmdlet 時,無法調試 ImportPSModule 失敗的原因

[英]Unable to debug why ImportPSModule fails when calling Powershell cmdlets from C#

我正在嘗試從 C# 調用“Connect-MsolService”cmdlet,但出現“...'Connect-MsolService' 未被識別為 cmdlet 的名稱...”錯誤。 任何有關如何調試此問題的指針將不勝感激。

我的項目基於 Office 開發中心示例Office 365:通過從 C# 調用 Windows PowerShell cmdlet 來管理用戶,C#首先執行“MSOnline”模塊的 ImportPSModule。

當我在 VS 2015 中打開 Office Dev Center 示例時,它按預期工作,但是當我創建自己的項目時卻沒有。 我真的很難弄清楚為什么我在我的項目中出現錯誤而不是在示例中。 到目前為止我所做的是

  • 在同一個解決方案中擁有兩個項目(樣本和我的)
  • 將兩個項目縮減為控制台應用程序,刪除所有不必要的依賴項和引用
  • 該示例有一個對 System.Management.Automation 的硬引用,當我在項目中嘗試每個時,我將其更改為塊引用(兩者都有效)仍然出現錯誤
  • 在我的項目中嘗試了基本的 powershell 命令(例如 Get-Process),一切正常
  • 試圖在 ImportPSModule 中使用 ImportPSModulesFromPath 和模塊的完整路徑,但都不起作用
  • 試圖檢查 Get-Item Env:\\PSModulePath 在每個項目中是否顯示相同的路徑,這似乎是這種情況
  • 檢查 VS 中每個項目的項目屬性,並確保所有設置都相同

我對如何深入了解這個問題的想法不多了。 代碼如下

            // Create Initial Session State for runspace.
            InitialSessionState initialSession = InitialSessionState.CreateDefault();
            initialSession.ImportPSModule(new[] { "MSOnline" });

            // Create credential object.
            PSCredential credential = new PSCredential("james@myestatehub.com", securePass);
            // Create command to connect office 365.
            Command connectCommand = new Command("Connect-MsolService");
            connectCommand.Parameters.Add((new CommandParameter("Credential", credential)));

            // Create command to get office 365 Contacts.
            Command getUserCommand = new Command("Get-MsolContact");

            using (Runspace psRunSpace = RunspaceFactory.CreateRunspace(initialSession))
            {
                // Open runspace.
                psRunSpace.Open();

                //Iterate through each command and executes it.
                foreach (var com in new Command[] { connectCommand, getUserCommand })
                    {
                    var pipe = psRunSpace.CreatePipeline();
                    pipe.Commands.Add(com);
                    // Execute command and generate results and errors (if any).
                    Collection<PSObject> results = pipe.Invoke(); //ERROR GET RAISED HERE

好的,我找到了我遇到這個問題的原因,但這並不意味着我完全理解為什么我需要將特定元素添加到項目文件中。

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>

在上面的條目中,我必須將<Prefer32Bit>false</Prefer32Bit>元素添加到 PropertyGroup。 一旦我添加了這個元素,代碼就會按預期工作。

可悲的是,雖然我讓代碼運行,但我仍在弄清楚為什么我需要這樣做。

暫無
暫無

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

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