sourcetip

PowerShell에서 새 줄로 배열 결합

fileupload 2023. 7. 27. 22:13
반응형

PowerShell에서 새 줄로 배열 결합

새 줄 문자를 사용하여 가입하려는 이름 배열이 있습니다.다음 코드를 가지고 있습니다.

$body = $invalid_hosts -join "`r`n"
$body = "The following files in $Path were found to be invalid and renamed `n`n" + $body

마지막으로 메일로 내용을 보냅니다.

$From = "myaddress@domain.com"
$To = "myaddress@domain.com
$subject = "Invalid language files"

Send-MailMessage -SmtpServer "smtp.domain.com" -From $From -To $To -Subject $subject -Body $body

내가 메시지를 받으면, 그 라인은The following files in <filepath> were found to be invalid and renamed에는 예상되는 이중 공간이 있지만 $invalid_hosts의 내용은 모두 한 줄에 있습니다.저도 해봤어요.

$body = $invalid_hosts -join "`n"

그리고.

$body = [string]::join("`n", $invalid_hosts)

두 가지 방법 모두 효과가 없습니다.이 작업을 수행하려면 어떻게 해야 합니까?

배열을 파이프로 연결합니다.Out-Stringcmdlet을 사용하여 문자열 개체 모음에서 단일 문자열로 변환합니다.

PS> $body = $invalid_hosts -join "`r`n" | Out-String

Out-String에 파이프만 연결하면 충분합니다(https://stackoverflow.com/a/21322311/52277) 참조).

 $result = 'This', 'Is', 'a', 'cat'
 $strResult = $result  | Out-String
 Write-Host $strResult
This
Is
a
cat

다른 모든 것에 대답하는 방법은 잘 모르겠지만, Powershell에서 보장된 새 줄에 대해서는 [환경]::'n' 대신 새 라인

오늘 이 문제를 해결해야 했습니다. 질문과 다른 답변들이 해결책을 찾는 데 도움이 되었기 때문에 제 대답을 공유하려고 생각했습니다.대신에

$body = $invalid_hosts -join "`r`n"
$body = "The following files in $Path were found to be invalid and renamed `n`n" + $body

사용하다

$MessageStr = "The following files in " + $Path + " were found to be invalid and renamed"
$BodyArray = $MessageStr + $Invalid_hosts
$Body = $BodyArray -join "`r`n"

저는 다르게 진행했고 새로운 라인을 교체했습니다.

$result -replace("`r`n"," ")

저는 PowerShell 전문가는 아니지만, 훨씬 더 쉬운 방법을 찾았습니다.간단하게 파이프 연결Write-Host다음과 같이:

$array = 'This', 'Is', 'a', 'cat'
$array | Write-Host

Output:
This
Is
a
cat

이것은 OP 질문과 약간 다른 사용 사례입니다.새 줄로 배열을 결합하지 않지만 출력을 쓸 때 새 줄을 제공합니다.

언급URL : https://stackoverflow.com/questions/20081824/join-an-array-with-newline-in-powershell

반응형