[英]C# Powershell AddScript not working
! 我在下面的示例中修改了代碼,以方便閱讀和闡明(因此請不要提及沒有異常處理等) !
目標:
我正在嘗試使用C#中的Powershell將GPO鏈接到ActiveDirectory OU(使用System.Management.Automation dll)
輸入字符串 (稍后將在.AddScript中使用)
import-module grouppolicy;New-GPLINK -name Workstations -target "OU=Workstations,OU=Computers,OU=TestBuilding,OU=Buildings,OU=Demo,DC=FABRICAM,DC=COM" -LinkEnabled YES -Server MYSERVER.FABRICAM.COM
應該發生魔術的代碼。
Integration.PowerShell.Classes.Singleton.Instance.AddScript(script); <== The input string
Integration.PowerShell.Classes.Singleton.Instance.Invoke();
對於那些想看單身人士的人
using System.Management.Automation.Runspaces;
using WindowsPowerShell = System.Management.Automation.PowerShell;
internal class Singleton
{
private static WindowsPowerShell windowsPowerShellRunspace;
public static WindowsPowerShell Instance
{
get
{
if (windowsPowerShellRunspace == null)
{
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
windowsPowerShellRunspace = WindowsPowerShell.Create();
windowsPowerShellRunspace.Runspace = runSpace;
}
return windowsPowerShellRunspace;
}
}
}
結果
代碼執行時沒有流或異常的任何錯誤...但是實際上什么也沒有發生。 PowerShell實例在Windows2008R2上運行
注意:我還在服務器上的Powershell控制台中執行了代碼,在這里工作正常...
更新
好像我的流中確實有一個錯誤..猜想我以某種方式錯過了它,但是,這是一個例外:
The 'New-GPLINK' command was found in the module 'GroupPolicy', but the module could not be loaded. For more information, run 'Import-Module GroupPolicy'.
找到了解決方案(感謝發布:“ jamone”的堆疊發布 ):
為了使用CLR 2.0混合模式程序集,您需要修改App.Config文件以包括:
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
關鍵是useLegacyV2RuntimeActivationPolicy標志。 這將導致CLR使用最新版本(4.0)來加載您的混合模式程序集。 沒有這個,它將無法工作。
請注意,這僅對混合模式(C ++ / CLI)程序集有效。 您可以加載所有托管的CLR 2程序集,而無需在app.config中指定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.