
나는 사용하고 싶다select-string
다른 명령의 출력에 대해( grep
Unix OS에서 사용하는 방법과 유사)
다음은 없이 명령의 출력입니다 select-string
.
> (dir resources).Name
wmd-Linux-22022.json
wmd-Linux-22023.json
wmd-Linux-22024.json
wmd-Windows-22022.json
wmd-Windows-22023.json
wmd-Windows-22024.json
을 사용하면 select-string
어떤 이유로 빈 줄이 나타납니다.
> (dir resources).Name | select-string Windows
wmd-Windows-22022.json
wmd-Windows-22023.json
wmd-Windows-22024.json
(A) 일치하지 않는 빈 줄을 먹으라고 select-string에 지시하거나 (B) 빈 줄을 먹을 수 있는 다른 powershell 유틸리티로 출력을 파이프할 수 있는 방법은 무엇입니까?
답변1
Select-String은 다음과 같이 MatchInfo 배열을 반환합니다.((dir resources).Name | select-string Windows)[0].GetType()
원하는 결과를 얻으려면 전체 표현식을 [string[]]에 캐스팅하면 됩니다.
[string[]]((dir resources).Name | select-string Windows)
답변2
한 가지 해결책을 찾았습니다.
((dir resources).Name | 선택 문자열 Windows | out-string).Trim()
out-string
다른 명령의 입력을 문자열로 변환하고 Trim()
문자열에서만 작동하는 함수입니다(즉, Trim()
문자열이 아닌 일부 유형을 반환하는 명령의 출력에서는 작동하지 않습니다).
답변3
다음은 목록을 쉽게 작성하고(출력 결과로) 빈 줄을 제거하고 파이프로 연결할 수 있는 올인원 기능입니다. 아래에 표시된 2가지 사용 예가 도움이 되기를 바랍니다.
function Write-List {
Param(
[Parameter(Mandatory, ValueFromPipeline)][array] $Array,
[string]$Prefixe,
[bool]$Numbering = $False
)
if ($Numbering) {
$NumberOfDigit = $($Array.Count).ToString().Length
$Array | Format-List | Out-String -Stream | ForEach-Object -Process {
if (-not [string]::IsNullOrWhiteSpace($_)) {
"$Prefixe# {0,$NumberOfDigit} : {1}" -f (++$Index), $_
}
}
} else {
$Array | Format-List | Out-String -Stream | ForEach-Object -Process {
if (-not [string]::IsNullOrWhiteSpace($_)) {
"$Prefixe{0}" -f $_
}
}
}
}
예시 #1 :
Write-List @("titi", "toto", "tata", "titi", "toto", "tata", "titi", "toto", "tata", "titi", "toto", "tata") -Numbering $True
# 1 : titi
# 2 : toto
# 3 : tata
# 4 : titi
# 5 : toto
# 6 : tata
# 7 : titi
# 8 : toto
# 9 : tata
# 10 : titi
# 11 : toto
# 12 : tata
예시 #2 :
Get-Service -Name "*openvpn*" | Select-Object DisplayName,Name,Status,StartType | Write-List -Prefixe " - "
- DisplayName : OpenVPN Interactive Service
- Name : OpenVPNServiceInteractive
- Status : Running
- StartType : Automatic