脚本可以在PowerShell中,但在PowerShell ISE中运行时,不C#
这个脚本作品(它设置给用户的远程桌面服务简介在Active Directory设置):脚本可以在PowerShell中,但在PowerShell ISE中运行时,不C#
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
一个错误,我称之为:
Exception calling "InvokeSet" with "2" argument(s):
"Unknown name. (Exception from 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 = [email protected]"
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#
脚本的顶部,但没有效果。我也在正常运行的脚本和C#
脚本中都调用了$PSVersionTable.PSVersion
,并且都返回了正在使用版本3的情况。
Exception calling "setinfo" with "0" argument(s): "The attribute syntax specified to the directory service is invalid.
而且在PowerShell中没有查询这些属性(没有错误,也没有输出):
更新属性名称
msTSProfilePath
msTSHomeDrive
msTSHomeDirectory
msTSAllowLogon
我得到这个错误在C#中后
有没有人碰巧知道可能会导致这种情况?
非常感谢
更新答案:看来,这些属性不存在2008+。请尝试以下的人,而不是:
- msTSAllowLogon
- msTSHomeDirectory
- msTSHomeDrive
- msTSProfilePath
一看便知在this thread为全面解释。
原来的答案:
从阿济斯pk的的评论可能是答案。您需要运行Import-Module ActiveDirectory
,就像您需要在命令行PowerShell中执行的操作一样。
如果您曾在PowerShell命令行中运行过Import-Module ActiveDirectory
,那么您将知道需要一段时间才能加载。在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();
尝试添加导入模块用于广告的脚本,你在C#中运行。 –
@Abhijithpk刚刚尝试在脚本中添加'Import-Module ActiveDirectory',但仍然看到相同的错误 – Bassie