Как добавить ссылку на сборку в PowerShell при использовании вместе с кодом C#? - PullRequest
2 голосов
/ 13 июля 2020

При добавлении ...

using System.DirectoryServices.AccountManagement;

Я получаю сообщение об ошибке:

Имя типа или пространство имен «DirectoryServices» не находится в пространстве имен «Система» (отсутствует ссылка на сборку?) Add-Type: не удалось добавить тип. Обнаружены ошибки компиляции.

Код в целом:

Add-Type -Language CSharp @"

using Microsoft.Win32;
using System.DirectoryServices.AccountManagement;

namespace MyApp
{
    public static class Program 
    {
        public static string GetCurrentUser()
        {
            _ = new PrincipalContext(ContextType.Domain);
            UserPrincipal user = UserPrincipal.Current;
            return user.ToString();
        }
        public static void SetRegKey(string userName)
        {
            string regString = userName;
            string subKey = @"SYSTEM\ControlSet001\Services\LanmanServer\Parameters";
            RegistryKey key = Registry.LocalMachine.CreateSubKey(subKey);
            key.SetValue("srvcomment", regString);
            key.Close();
        }
    }
}

"@;

$userName = [MyApp.Program]::GetCurrentUser()
[MyApp.Program]::SetRegKey($userName)

1 Ответ

2 голосов
/ 13 июля 2020
Add-Type -ReferencedAssemblies "System.DirectoryServices.AccountManagement" -Language CSharp @"

using Microsoft.Win32;
using System.DirectoryServices.AccountManagement;

namespace MyApp
{
    public static class Program 
    {
        public static string GetCurrentUser()
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            UserPrincipal user = UserPrincipal.Current;
            return user.ToString();
        }
        public static void SetRegKey(string userName)
        {
            string regString = userName;
            string subKey = @"SYSTEM\ControlSet001\Services\LanmanServer\Parameters";
            RegistryKey key = Registry.LocalMachine.CreateSubKey(subKey);
            key.SetValue("srvcomment", regString);
            key.Close();
        }
    }
}

"@;

$userName = [MyApp.Program]::GetCurrentUser()
[MyApp.Program]::SetRegKey($userName)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...