在PowerShell ISE中运行时,此脚本有效(它在Active Directory中设置给定用户的“远程桌面服务配置文件”设置):
Get-ADUser FirstName.LastName | ForEach-Object {
$User = [ADSI]"LDAP://$($_.DistinguishedName)"
$User.psbase.invokeset("TerminalServicesProfilePath","\\Server\Share\HomeDir\Profile")
$User.psbase.invokeset("TerminalServicesHomeDrive","H:")
$User.psbase.invokeset("TerminalServicesHomeDirectory","\\Server\Share\HomeDir")
$User.setinfo()
}
但是,当我尝试从C#应用程序运行它时invokeset
,我调用的每个程序都出现错误:
使用“ 2”个参数调用“ InvokeSet”的异常:
“未知名称。(HRESULT的异常:0x80020006(DISP_E_UNKNOWNNAME))
这是代码,它在我的PowerShell
课程里面:
public static List<PSObject> Execute(string args)
{
var returnList = new List<PSObject>();
using (var powerShellInstance = PowerShell.Create())
{
powerShellInstance.AddScript(args);
var psOutput = powerShellInstance.Invoke();
if (powerShellInstance.Streams.Error.Count > 0)
{
foreach (var error in powerShellInstance.Streams.Error)
{
Console.WriteLine(error);
}
}
foreach (var outputItem in psOutput)
{
if (outputItem != null)
{
returnList.Add(outputItem);
}
}
}
return returnList;
}
我这样称呼它:
var script = $@"
Get-ADUser {newStarter.DotName} | ForEach-Object {{
$User = [ADSI]""LDAP://$($_.DistinguishedName)""
$User.psbase.invokeset(""TerminalServicesProfilePath"",""\\file\tsprofiles$\{newStarter.DotName}"")
$User.psbase.invokeset(""TerminalServicesHomeDrive"",""H:"")
$User.psbase.invokeset(""TerminalServicesHomeDirectory"",""\\file\home$\{newStarter.DotName}"")
$User.setinfo()
}}";
PowerShell.Execute(script);
其中newStarter.DotName
包含(已经存在的)AD用户的帐户名。
我尝试Import-Module ActveDirectory
在C#
脚本顶部包含,但没有任何效果。我还调用$PSVersionTable.PSVersion
了正常运行的C#
脚本和脚本,并且都返回了正在使用的版本3。
将属性名称更新为
msTSProfilePath
msTSHomeDrive
msTSHomeDirectory
msTSAllowLogon
我在C#中收到此错误:
使用参数“ 0”调用“ setinfo”的异常:“为目录服务指定的属性语法无效。
并在PowerShell中查询这些属性时不执行任何操作(没有错误,但也没有输出)
有谁碰巧知道是什么原因造成的?
非常感谢
更新的答案:这些属性似乎在2008年以后不存在。尝试以下方法:
有关完整说明,请参见此线程中的答案。
原始答案:
来自Abhijith pk的评论可能是答案。您需要运行Import-Module ActiveDirectory
,就像需要在命令行PowerShell中进行操作一样。
如果您曾经Import-Module ActiveDirectory
在PowerShell命令行中运行过,您将知道需要一段时间才能加载。在C#中运行时将是相同的。因此,如果要在应用程序中运行多个AD命令,最好将Runspace对象作为静态对象保持活动状态并重用它,这意味着您只需加载ActiveDirectory模块一次。
这里有有关如何在C#中执行此操作的详细信息:https : //blogs.msdn.microsoft.com/syamp/2011/02/24/how-to-run-an-active-directory-ad-cmdlet-from- net-c /
特别是,这是代码:
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[] { "activedirectory" });
Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss);
myRunSpace.Open();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句