Microsoft MVP성태의 닷넷 이야기
Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리 [링크 복사], [링크+제목 복사]
조회: 4361
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(WMI 쿼리를 위한) PowerShell 문자열 escape 처리

지난 글에,

C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법
; https://www.sysnet.pe.kr/2/0/13228

설명한 내용을 dsscrolls 님이 다시 쿼리를 구성한 답글을 남기셨는데요, 그래서 가벼운 마음으로 PowerShell로 해당 쿼리를 그대로 구현해 다시 덧글을 달려고 했더니... 이게 쉽지가 않습니다. ^^;

우선, 첫 번째 쿼리부터 문제입니다.

Select Antecedent from Win32_LogicalDiskToPartition where Dependent="Win32_LogicalDisk.DeviceID="C:"" 

위의 쿼리를 PowerShell에 전달하면 문자열 내에 사용한 인용 부호 때문에,

PS> Get-WmiObject -Query "SELECT Antecedent FROM Win32_LogicalDiskToPartition WHERE Dependent="Win32_LogicalDisk.DeviceID="C:"""
Get-WmiObject : A positional parameter cannot be found that accepts argument 'Win32_LogicalDisk.DeviceID=C:"'.
At line:1 char:1
+ Get-WmiObject -Query "SELECT Antecedent FROM Win32_LogicalDiskToParti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetWmiObjectCommand

오류가 발생합니다. 당연히, 저 인용 부호(")를 escape 처리해야 하는데요,

Escaping in PowerShell
; https://www.rlmueller.net/PowerShellEscape.htm

PowerShell에서 문자열 내부의 인용 부호는 2개로 escape 처리하거나, backtick을 이용할 수 있습니다. 하지만, 그건 단순히 escape 시킨 것에 불과하고, WMI 쿼리 등의 문법과는 맞지 않아 이런 오류가 발생하게 됩니다.

// 겹따옴표를 2개 연속으로 escape 처리

PS> Get-WmiObject -Query "SELECT Antecedent FROM Win32_LogicalDiskToPartition WHERE Dependent=""Win32_LogicalDisk.DeviceID=""C:"""""
Get-WmiObject : Invalid query "SELECT Antecedent FROM Win32_LogicalDiskToPartition WHERE Dependent="Win32_LogicalDisk.DeviceID="C:"""
At line:1 char:1
+ Get-WmiObject -Query "SELECT Antecedent FROM Win32_LogicalDiskToParti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand"

// 겹따옴표를 backtick으로 escape 처리

PS> Get-WmiObject -Query "SELECT Antecedent FROM Win32_LogicalDiskToPartition WHERE Dependent=`"Win32_LogicalDisk.DeviceID=`"C:`"`""
Get-WmiObject : Invalid query "SELECT Antecedent FROM Win32_LogicalDiskToPartition WHERE Dependent="Win32_LogicalDisk.DeviceID="C:"""
At line:1 char:1
+ Get-WmiObject -Query "SELECT Antecedent FROM Win32_LogicalDiskToParti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

2가지 처리 방식 모두 저렇게 오류가 발생합니다. 왜냐하면, Dependent 조건 절의 내용이 다음과 같이 평가되기 때문입니다.

Dependent="Win32_LogicalDisk.DeviceID="C:""

따라서 이런 경우에는 홑따옴표를 곁들여서 다음과 같이 해결할 수 있습니다.

Get-WmiObject -Query "SELECT Antecedent FROM Win32_LogicalDiskToPartition WHERE Dependent=`"Win32_LogicalDisk.DeviceID='C:'`""

일단, 저렇게 해결할 수 있었지만, 한 단계 더 중첩된 경우가 나오면 그때는 어떻게 escape 처리를 해야 할지 모르겠습니다. ^^; (아마도 WMI 쿼리에서 그런 경우는 없을 거라 생각되지만.)




어쨌든, 문자열 내부에 인용 부호가 2중첩 되는 것까지는 해결할 수 있었습니다. 이를 바탕으로 "C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법" 글에서 나온 쿼리를 마저 포팅해 보겠습니다.

우선 위의 쿼리에서 나온 Antecedent 값은,

PS> $result = Get-WmiObject -Query "SELECT Antecedent FROM Win32_LogicalDiskToPartition WHERE Dependent=`"Win32_LogicalDisk.DeviceID='C:'`""

PS> $result.Antecedent
\\TESTPC\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #1"

이후의 "SELECT * FROM Win32_DiskDriveToDiskPartition ..." 쿼리에 바로 사용할 수 없습니다. 아쉽게도 cimv2 경로가 들어가서는 안 되고, 그 이후의 값을 Dependent 절에 다음과 같이 설정해야 합니다.

Get-WmiObject -Query "Select * from Win32_DiskDriveToDiskPartition where Dependent=Win32_DiskPartition.DeviceID="Disk #1, Partition #1""

==> escape 처리

Get-WmiObject -Query "Select * from Win32_DiskDriveToDiskPartition where Dependent=`"Win32_DiskPartition.DeviceID='Disk #1, Partition #1'`""

저 결과로 물리 드라이브 경로를 얻을 수 있는데요,

PS> $result = Get-WmiObject -Query "Select * from Win32_DiskDriveToDiskPartition where Dependent=`"Win32_DiskPartition.DeviceID='Disk #1, Partition #1'`""

PS> $result.Antecedent
\\TESTPC\root\cimv2:Win32_DiskDrive.DeviceID="\\\\.\\PHYSICALDRIVE1"

이 값 역시 cim 경로가 나오는데 그것을 제외한 부분을 Win32_DiskDrive 쿼리에 전달하면,

PS> Get-WmiObject -Query "Select SerialNumber from Win32_DiskDrive where DeviceID='\\\\.\\PHYSICALDRIVE1'" 

__GENUS          : 2
__CLASS          : Win32_DiskDrive
__SUPERCLASS     :
__DYNASTY        :
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
SerialNumber     : 0025_38A1_0100_2C3D.
PSComputerName   :

모든 과정이 완료됩니다. ^^ 이것을 약간 더 자동화하면 다음과 같이 정리할 수 있습니다.

$result = Get-WmiObject -Query "SELECT Antecedent FROM Win32_LogicalDiskToPartition WHERE Dependent=`"Win32_LogicalDisk.DeviceID='C:'`""

$result = $result.Antecedent.SubString($result.Antecedent.IndexOf(':') + 1)

$result = Get-WmiObject -Query "Select * from Win32_DiskDriveToDiskPartition where Dependent='$result'"

$result = $result.Antecedent.SubString($result.Antecedent.IndexOf('=') + 1)

Get-WmiObject -Query "Select SerialNumber from Win32_DiskDrive where DeviceID=$result"




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







[최초 등록일: ]
[최종 수정일: 2/10/2023]

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)
13606정성태4/24/202444닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024314닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024322오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024505닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024791닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024837닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024846닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024862닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024884닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024859닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241049닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241050닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241068닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241079닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241217C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241193닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241150닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241262닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241168오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241326Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241111Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241060개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241194Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241453Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...