Microsoft MVP성태의 닷넷 이야기
닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기) [링크 복사], [링크+제목 복사],
조회: 2335
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 4개 있습니다.)
Windows: 146. PowerShell로 원격 프로세스(EXE, BAT) 실행하는 방법
; https://www.sysnet.pe.kr/2/0/11450

개발 환경 구성: 738. PowerShell - 원격 호출 시 "powershell.exe"가 아닌 "pwsh.exe" 환경으로 명령어를 실행하는 방법
; https://www.sysnet.pe.kr/2/0/13858

닷넷: 2325. C# - PowerShell과 연동하는 방법
; https://www.sysnet.pe.kr/2/0/13892

닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)
; https://www.sysnet.pe.kr/2/0/13897




C# - PowerShell과 연동하는 방법 (두 번째 이야기)

이번에는 Get-VM 명령어로 예를 들어 볼까요? ^^

Get-VM
; https://learn.microsoft.com/en-us/powershell/module/hyper-v/get-vm

문서의 서두에 "Module: Hyper-V"라고 나오는데요, 즉 모듈명이 "Hyper-V"라는 것입니다. PowerShell의 경우 모듈은 PSModulePath에 등록된 경로에 있으므로,

PS C:\Windows\System32> $env:PSModulePath
C:\Users\testusr\Documents\WindowsPowerShell\Modules;...[생략]...

  • %USERPROFILE%\Documents\WindowsPowerShell\Modules;
  • C:\Program Files\WindowsPowerShell\Modules;
  • C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\;
  • C:\Program Files (x86)\Microsoft SQL Server\130\Tools\PowerShell\Modules\;
  • C:\Program Files (x86)\Microsoft SQL Server\140\Tools\PowerShell\Modules\;
  • C:\Program Files\Microsoft Message Analyzer\PowerShell\

차례대로 저 경로에서 찾아보면 되는데, 제 시스템에서 Hyper-V 모듈은 다음 경로에 있었습니다.

C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Hyper-V\2.0.0.0

저 폴더에는 Hyper-V.psd1 파일이 있고, 해당 파일을 열어보면 실제 구현을 담고 있는 DLL에 대한 정보가 있습니다. (물론, 모든 PowerShell 모듈이 이런 식으로 구성돼 있는 것은 아닙니다. ^^)

// Hyper-V.psd1
...[생략]...

# Script module or binary module file associated with this manifest
NestedModules = 'Microsoft.HyperV.PowerShell.Cmdlets.dll'
...[생략]...

그럼, 다시 저 DLL 파일을 아래의 경로에서 찾을 수 있고,

C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.HyperV.PowerShell.Cmdlets\v4.0_10.0.0.0__31bf3856ad364e35

대부분은 닷넷 어셈블리로 구현돼 있을 것이므로 dnSpy 등의 역어셈블 도구를 이용해 실제 구현이 어떻게 됐는지 확인할 수 있습니다.




해당 DLL을 역어셈블해 Get-VM 명령어를 보면 구현 자체는 다음과 같이 간단한데요,

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation;
using Microsoft.HyperV.PowerShell.ExtensionMethods;
using Microsoft.Management.Infrastructure;
using Microsoft.Virtualization.Client.Management;

namespace Microsoft.HyperV.PowerShell.Commands
{
    [Cmdlet("Get", "VM", DefaultParameterSetName = "Name")]
    [OutputType(new Type[]
    {
        typeof(VirtualMachine)
    })]
    public sealed class GetVM : VirtualizationCmdlet<VirtualMachine>, IVmByNameCmdlet, IVirtualMachineCmdlet, IServerParameters, IParameterSet
    {
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "This is by spec.")]
        [ValidateNotNullOrEmpty]
        [Parameter(ParameterSetName = "Name", ValueFromPipeline = true, Position = 0)]
        [Alias(new string[]
        {
            "VMName"
        })]
        public string[] Name { get; set; }

        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "This is by spec.")]
        [Parameter(ParameterSetName = "Name")]
        [Parameter(ParameterSetName = "Id")]
        [ValidateNotNullOrEmpty]
        public override CimSession[] CimSession { get; set; }

        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "This is by spec.")]
        [Parameter(ParameterSetName = "Name")]
        [Parameter(ParameterSetName = "Id")]
        [ValidateNotNullOrEmpty]
        public override string[] ComputerName { get; set; }

        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "This is by spec.")]
        [Parameter(ParameterSetName = "Name")]
        [Parameter(ParameterSetName = "Id")]
        [ValidateNotNullOrEmpty]
        [CredentialArray]
        public override PSCredential[] Credential { get; set; }

        [ValidateNotNull]
        [Parameter(ParameterSetName = "Id", ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Position = 0)]
        public Guid? Id { get; set; }

        [Parameter(ParameterSetName = "ClusterObject", Mandatory = true, Position = 0, ValueFromPipeline = true)]
        [ValidateNotNullOrEmpty]
        [PSTypeName("Microsoft.FailoverClusters.PowerShell.ClusterObject")]
        public PSObject ClusterObject { get; set; }

        internal override IList<VirtualMachine> EnumerateOperands(IOperationWatcher operationWatcher)
        {
            IList<VirtualMachine> result;
            if (base.CurrentParameterSetIs("Name"))
            {
                result = ParameterResolvers.ResolveVirtualMachines(this, operationWatcher, ErrorDisplayMode.WriteWarning);
            }
            else
            {
                if (!base.CurrentParameterSetIs("Id"))
                {
                    return GetVM.GetVirtualMachinesFromClusterObject(this.ClusterObject, operationWatcher).ToList<VirtualMachine>();
                }
                Guid vmId = this.Id.Value;
                result = ParameterResolvers.GetServers(this, operationWatcher).SelectWithLogging((Server server) => VirtualizationObjectLocator.GetVirtualMachineById(server, vmId), operationWatcher).ToList<VirtualMachine>();
            }
            return result;
        }

        internal override void ProcessOneOperand(VirtualMachine operand, IOperationWatcher operationWatcher)
        {
            operationWatcher.WriteObject(operand);
        }

        private static IEnumerable<VirtualMachine> GetVirtualMachinesFromClusterObject(PSObject clusterObject, IOperationWatcher operationWatcher)
        private static IEnumerable<VirtualMachine> GetVirtualMachinesFromClusterObject(PSObject clusterObject, IOperationWatcher operationWatcher)
        {
            object[] array = clusterObject.BaseObject as object[];
            if (array != null)
            {
                return array.Cast<PSObject>().SelectManyWithLogging((PSObject innerElement) => ClusterUtilities.GetVirtualMachinesFromClusterObject(innerElement, operationWatcher), operationWatcher);
            }
            IEnumerable<VirtualMachine> result;
            try
            {
                result = ClusterUtilities.GetVirtualMachinesFromClusterObject(clusterObject, operationWatcher);
            }
            catch (Exception e)
            {
                ExceptionHelper.DisplayErrorOnException(e, operationWatcher);
                result = Enumerable.Empty<VirtualMachine>();
            }
            return result;
        }
    }
}

느낌이 오시겠지만, 저걸 C# 프로젝트에서 직접 참조해 호출하는 것은 쉽지 않습니다. 왜냐하면, PowerShell 자체의 런타임 구성을 위한 여러 가지 부수적인 요소(호출 측 Credential 처리와 원격 호출, 명령 수행의 파이프라인 처리) 등이 관여하기 때문입니다.

따라서, 그냥 마이크로소프트에서 제공하는 어셈블리를 이용해 PowerShell 명령어를 호출하는 것이 훨씬 간단하고 안전합니다. ^^

C# - PowerShell과 연동하는 방법
; https://www.sysnet.pe.kr/2/0/13892


using System.Management.Automation;

// Install-Package System.Management.Automation
// Install-Package Microsoft.PowerShell.SDK

internal class Program
{
    static void Main(string[] args)
    {
        PowerShell _ps = PowerShell.Create();

        _ps.AddCommand("Get-VM", false);
        _ps.AddParameter("Name", new string[] { "win11en" });

        System.Collections.ObjectModel.Collection<PSObject> output = _ps.Invoke();

        foreach (var item in output)
        {
            dynamic vmObj = item;
            Console.WriteLine($"{vmObj.Name}: {vmObj.CPUUsage}%");
        }
    }
}

(지난 글에서도 언급했지만) "dynamic vmObj = item;"의 dynamic 대신 형식 안정성을 위해 Microsoft.HyperV.PowerShell.VirtualMachine 타입을 직접 쓰는 것도 가능합니다. 이를 위해서는 직접 참조/실행해 보면서 의존성 목록을 파악할 수 있는데, 제가 해 본 결과 Get-VM의 경우에는 어셈블리를 2개 참조해야 합니다.

// Microsoft.HyperV.PowerShell.Objects.dll
// C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.HyperV.PowerShell.Objects\v4.0_10.0.0.0__31bf3856ad364e35\Microsoft.HyperV.PowerShell.Objects.dll

// Microsoft.Virtualization.Client.Management.dll
// C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.Virtualization.Client.Management\v4.0_10.0.0.0__31bf3856ad364e35\Microsoft.Virtualization.Client.Management.dll

그럼, 다음과 같이 코드를 변경할 수 있습니다.

foreach (var item in output)
{
    if (item.BaseObject is Microsoft.HyperV.PowerShell.VirtualMachine vm)
    {
        Console.WriteLine($"{vm.Name}: {vm.CPUUsage}%");
    }                    
}

그런데, 이런 식으로 Microsoft.HyperV.PowerShell.VirtualMachine 타입을 사용하기 위해 "Microsoft.HyperV.PowerShell.Objects.dll"을 참조하는 것은 약간의 위험이 따릅니다. 가령, Windows 11 23H2에서 저 DLL의 버전은 10.0.22621.1인데요, 이것을 참조해 빌드한 후 산출된 어셈블리 디렉터리를 Windows 11 24H2에 복사해 실행하면 Invoke 코드에서 오류가 발생할 수 있습니다.

System.Collections.ObjectModel.Collection<PSObject> output = _ps.Invoke();
/* 예외 발생
System.Management.Automation.CommandNotFoundException: 'The 'Get-VM' command was found in the module 'Hyper-V', but the module could not be loaded due to the following error: [Could not load type 'Microsoft.HyperV.PowerShell.MemoryBackingType' from assembly 'Microsoft.HyperV.PowerShell.Objects, Version=10.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.]
For more information, run 'Import-Module Hyper-V'.'
*/

왜냐하면, Invoke 호출로 인해 Microsoft.PowerShell.SDK / System.Management.Automation은 GAC에 등록된 (24H2 윈도우 11에 설치된 10.0.26100.2033 버전의) Microsoft.HyperV.PowerShell.Cmdlets.dll을 로드하게 되고, 이 DLL은 동일하게 24H2에 설치된 10.0.26100.2033 버전의 Microsoft.HyperV.PowerShell.Objects.dll을 참조해 거기에만 있는 Microsoft.HyperV.PowerShell.MemoryBackingType에 의존하고 있기 때문입니다.

여기서 문제는, 23H2 환경에서 빌드했을 때 output 디렉터리에 위치하는 Microsoft.HyperV.PowerShell.Objects.dll은 10.0.22621.1 버전의 것이므로 Invoke 호출은 그 DLL을 선제적으로 로딩하게 되고, 결국 MemoryBackingType을 찾을 수 없어 예외가 발생하는 것입니다.

따라서 해당 DLL들은 실행 모듈과 같은 디렉터리에 복사하는 식으로 빌드해서는 안 되고 PowerShell.Invoke 호출의 내부 구현에 따라 자연스럽게 GAC로부터 로드되도록 맡겨야 합니다. 즉, Microsoft.HyperV.PowerShell.VirtualMachine 타입을 직접 사용하는 것은 지양해야 합니다. (아마도 이런 이유 때문에 해당 타입에 대한 문서를 제공하는 것이 어렵지 않은가... 싶습니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/5/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13917정성태4/30/202525VS.NET IDE: 199. Directory.Build.props에 정의한 속성에 대해 Condition 제약으로 값을 변경하는 방법
13916정성태4/23/2025422디버깅 기술: 221. WinDbg 분석 사례 - ASP.NET HttpCookieCollection을 다중 스레드에서 사용할 경우 무한 루프 현상 - 두 번째 이야기
13915정성태4/13/20251635닷넷: 2331. C# - 실행 시에 메서드 가로채기 (.NET 9)파일 다운로드1
13914정성태4/11/20251963디버깅 기술: 220. windbg 분석 사례 - x86 ASP.NET 웹 응용 프로그램의 CPU 100% 현상 (4)
13913정성태4/10/20251186오류 유형: 950. Process Explorer - 64비트 윈도우에서 32비트 프로세스의 덤프를 뜰 때 "Error writing dump file: Access is denied." 오류
13912정성태4/9/2025847닷넷: 2330. C# - 실행 시에 메서드 가로채기 (.NET 5 ~ .NET 8)파일 다운로드1
13911정성태4/8/20251074오류 유형: 949. WinDbg - .NET Core/5+ 응용 프로그램 디버깅 시 sos 확장을 자동으로 로드하지 못하는 문제
13910정성태4/8/20251239디버깅 기술: 219. WinDbg - 명령어 내에서 환경 변수 사용법
13909정성태4/7/20251708닷넷: 2329. C# - 실행 시에 메서드 가로채기 (.NET Framework 4.8)파일 다운로드1
13908정성태4/2/20252104닷넷: 2328. C# - MailKit: SMTP, POP3, IMAP 지원 라이브러리
13907정성태3/29/20251888VS.NET IDE: 198. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C# 프로젝트의 출력 경로 변경하기
13906정성태3/27/20252130닷넷: 2327. C# - 초기화되지 않은 메모리에 접근하는 버그?파일 다운로드1
13905정성태3/26/20252163Windows: 281. C++ - Windows / Critical Section의 안정화를 위해 도입된 "Keyed Event"파일 다운로드1
13904정성태3/25/20251866디버깅 기술: 218. Windbg로 살펴보는 Win32 Critical Section파일 다운로드1
13903정성태3/24/20251506VS.NET IDE: 197. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C++ 프로젝트의 출력 경로 변경하기
13902정성태3/24/20251714개발 환경 구성: 742. Oracle - 테스트용 hr 계정 및 데이터 생성파일 다운로드1
13901정성태3/9/20252093Windows: 280. Hyper-V의 3가지 Thread Scheduler (Classic, Core, Root)
13900정성태3/8/20252329스크립트: 72. 파이썬 - SQLAlchemy + oracledb 연동
13899정성태3/7/20251789스크립트: 71. 파이썬 - asyncio의 ContextVar 전달
13898정성태3/5/20252108오류 유형: 948. Visual Studio - Proxy Authentication Required: dotnetfeed.blob.core.windows.net
13897정성태3/5/20252335닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)파일 다운로드1
13896정성태3/5/20252160Windows: 279. Hyper-V Manager - VM 목록의 CPU Usage 항목이 항상 0%로 나오는 문제
13895정성태3/4/20252203Linux: 117. eBPF / bpf2go - Map에 추가된 요소의 개수를 확인하는 방법
13894정성태2/28/20252229Linux: 116. eBPF / bpf2go - BTF Style Maps 정의 구문과 데이터 정렬 문제
13893정성태2/27/20252178Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...