我想使用" Active Directory管理与Windows PowerShell" 提供的特定命令。所以我在我的服务器上安装了这个模块。
现在,我想在我的代码中使用这些命令。我的项目在c# - ASP.NET。
这是我用来调用传统" cmdlet"的代码。命令(New-Mailbox,Set-User,...):
string runasUsername = @"Mario";
string runasPassword = "MarioKart";
SecureString ssRunasPassword = new SecureString();
foreach (char x in runasPassword)
ssRunasPassword.AppendChar(x);
PSCredential credentials =
new PSCredential(runasUsername, ssRunasPassword);
// Prepare the connection
var connInfo = new WSManConnectionInfo(new Uri("MarioServer"),
"http://schemas.microsoft.com/powershell/Microsoft.Exchange",credentials);
connInfo.AuthenticationMechanism =
AuthenticationMechanism.Basic;
connInfo.SkipCACheck = true;
connInfo.SkipCNCheck = true;
// Create the runspace where the command will be executed
var runspace = RunspaceFactory.CreateRunspace(connInfo);
//Params
....
// create the PowerShell command
var command = new Command("New-Mailbox");
command.Parameters.Add("Name", name);
....
// Add the command to the runspace's pipeline
runspace.Open();
var pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(command);
// Execute the command
var results = pipeline.Invoke();
if (results.Count > 0)
System.Diagnostics.Debug.WriteLine("SUCCESS");
else
System.Diagnostics.Debug.WriteLine("FAIL");
runspace.Dispose();
这段代码完美无缺!好极了!但是,我想使用" Set-ADUser" ,此命令来自 ActiveDirectory模块(RSAT工具)。
鉴于所有设置都在服务器上(模块已安装),我试图简单地改变" New-Mailbox" for" Set-ADUser" :
var command = new Command("Set-ADUser");
当我运行代码时,我有这个错误:
术语' Set-ADUser'不被识别为cmdlet,函数,脚本文件或可操作程序的名称。
那么,这就是我的问题:
我们如何从c#中的ActiveDirectory模块(RSAT工具)运行命令? (我正在使用VS 2010)。
答案 0 :(得分:1)
正如@JPBlanc在评论部分中指出的那样,您需要确保加载ActiveDirectory
PowerShell模块。 PowerShell 3.0及更高版本默认启用模块自动加载(可以禁用),但如果您仍然定位PowerShell 2.0,则必须先调用:
Import-Module -Name ActiveDirectory;
..然后才能使用模块内的命令。
出于验证目的,您可以使用Get-Module
命令确保已导入ActiveDirectory
模块。
Get-Module -Name ActiveDirectory;
如果上述命令返回$null
,则不导入模块。要验证PowerShell是否可以“查看”ActiveDirectory
模块,而不实际导入它,请运行以下命令:
Get-Module -Name ActiveDirectory -ListAvailable;