[英]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 示例時,它按預期工作,但是當我創建自己的項目時卻沒有。 我真的很難弄清楚為什么我在我的項目中出現錯誤而不是在示例中。 到目前為止我所做的是
我對如何深入了解這個問題的想法不多了。 代碼如下
// 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.