development

PowerShell에서 줄 바꿈없이 텍스트를 어떻게 출력합니까?

big-blog 2020. 6. 27. 10:09
반응형

PowerShell에서 줄 바꿈없이 텍스트를 어떻게 출력합니까?


PowerShell 스크립트가 다음과 같이 인쇄되기를 원합니다.

Enabling feature XYZ......Done

스크립트는 다음과 같습니다.

Write-Output "Enabling feature XYZ......."
Enable-SPFeature...
Write-Output "Done"

그러나 Write-Output항상 끝에 새 줄을 인쇄하여 출력이 한 줄에 있지 않습니다. 이 방법이 있습니까?


Write-Host -NoNewline "기능 XYZ 사용 가능 .."


불행히도 여러 답변과 의견에서 언급했듯이 Write-Host위험 할 수 있으며 다른 프로세스로 파이프 할 수 없으며 플래그 Write-Output가 없습니다 -NoNewline.

그러나 이러한 방법은 진행률을 표시하는 "* nix"방법, "PowerShell"방법은 다음과 같습니다 Write-Progress. PowerShell 창의 맨 위에 표시 줄에 PowerShell 3.0부터 사용 가능한 진행률 정보가 표시 됩니다. 세부.

# Total time to sleep
$start_sleep = 120

# Time to sleep between each notification
$sleep_iteration = 30

Write-Output ( "Sleeping {0} seconds ... " -f ($start_sleep) )
for ($i=1 ; $i -le ([int]$start_sleep/$sleep_iteration) ; $i++) {
    Start-Sleep -Seconds $sleep_iteration
    Write-Progress -CurrentOperation ("Sleep {0}s" -f ($start_sleep)) ( " {0}s ..." -f ($i*$sleep_iteration) )
}
Write-Progress -CurrentOperation ("Sleep {0}s" -f ($start_sleep)) -Completed "Done waiting for X to finish"

그리고 OP의 예를 들어 보자.

# For the file log
Write-Output "Enabling feature XYZ"

# For the operator
Write-Progress -CurrentOperation "EnablingFeatureXYZ" ( "Enabling feature XYZ ... " )

Enable-SPFeature...

# For the operator
Write-Progress -CurrentOperation "EnablingFeatureXYZ" ( "Enabling feature XYZ ... Done" )

# For the log file
Write-Output "Feature XYZ enabled"

사용자에게 유익한 출력을 제공하기 때문에 귀하의 경우에는 작동하지 않을 수 있지만 출력을 추가하는 데 사용할 수있는 문자열을 만드십시오. 출력 할 때 문자열 만 출력하십시오.

물론이 예제가 어리석지 만 개념에는 유용하다는 것을 무시하십시오.

$output = "Enabling feature XYZ......."
Enable-SPFeature...
$output += "Done"
Write-Output $output

디스플레이 :

Enabling feature XYZ.......Done

예, 다른 답변에는 상태가 있으므로 Write-Output으로 수행 할 수 없습니다. PowerShell이 ​​실패하면 .NET으로 전환하십시오. 여기에 .NET 답변이 몇 개 있지만 필요보다 복잡합니다.

그냥 사용하십시오 :

[Console]::Write("Enabling feature XYZ.......")
Enable-SPFeature...
Write-Output "Done"

가장 순수한 PowerShell은 아니지만 작동합니다.


파일에 쓰려면 바이트 배열을 사용할 수 있습니다. 다음 예제는 파일을 추가 할 수있는 빈 ZIP 파일을 만듭니다.

[Byte[]] $zipHeader = 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
[System.IO.File]::WriteAllBytes("C:\My.zip", $zipHeader)

또는 사용하십시오 :

[Byte[]] $text = [System.Text.Encoding]::UTF8.getBytes("Enabling feature XYZ.......")
[System.IO.File]::WriteAllBytes("C:\My.zip", $text)

FrinkTheBrave의 답변 단순화 :

[System.IO.File]::WriteAllText("c:\temp\myFile.txt", $myContent)

The problem that I hit was that Write-Output actually linebreaks the output when using using PowerShell v2, at least to stdout. I was trying to write an XML text to stdout without success, because it would be hard wrapped at character 80.

The workaround was to use

[Console]::Out.Write($myVeryLongXMLTextBlobLine)

This was not an issue in PowerShell v3. Write-Output seems to be working properly there.

Depending on how the PowerShell script is invoked, you may need to use

[Console]::BufferWidth =< length of string, e.g. 10000)

before you write to stdout.


There seems to be no way to do this in PowerShell. All of the previous answers are not correct, because they do not behave the way Write-Output behaves but more like Write-Host which doesn't have this problem anyway.

The closes solution seems to use Write-Host with the -NoNewLine parameter. You can not pipe this which is a problem generally, but there is a way to override this function as described in Write-Host => Export to a file, so you can easily make it accept the parameter for an output file. This is still far from a good solution. With Start-Transcript this is more usable, but that cmdlet has problems with native applications.

Write-Outputsimply can't do what you need in a general context.


Write-Host is terrible, a destroyer of worlds, yet you can use it just to display progress to a user whilst using Write-Output to log (not that the OP asked for logging).

Write-Output "Enabling feature XYZ" | Out-File "log.txt" # Pipe to log file Write-Host -NoNewLine "Enabling feature XYZ......." $result = Enable-SPFeature $result | Out-File "log.txt" # You could try{}catch{} an exception on Enable-SPFeature depending on what it's doing if ($result -ne $null) { Write-Host "complete" } else { Write-Host "failed" }


You simply cannot get PowerShell to omit those pesky newlines... There is no script or cmdlet that does. Of course, Write-Host is absolute nonsense, because you can't redirect/pipe from it!

Nevertheless, you can write your own EXE file to do it which is what I explained how to do in Stack Overflow question How to output something in PowerShell.


The answer by shufler is correct. Stated another way: Instead of passing the values to Write-Output using the ARRAY FORM,

Write-Output "Parameters are:" $Year $Month $Day

or the equivalent by multiple calls to Write-Output,

Write-Output "Parameters are:"
Write-Output $Year
Write-Output $Month
Write-Output $Day
Write-Output "Done."

concatenate your components into a STRING VARIABLE first:

$msg="Parameters are: $Year $Month $Day"
Write-Output $msg

This will prevent the intermediate CRLFs caused by calling Write-Output multiple times (or ARRAY FORM), but of course will not suppress the final CRLF of the Write-Output commandlet. For that, you will have to write your own commandlet, use one of the other convoluted workarounds listed here, or wait until Microsoft decides to support the -NoNewline option for Write-Output.

Your desire to provide a textual progress meter to the console (i.e. "....") as opposed to writing to a log file, should also be satisfied by using Write-Host. You can accomplish both by collecting the msg text into a variable for writing to the log AND using Write-Host to provide progress to the console. This functionality can be combined into your own commandlet for greatest code reuse.


The following will place the cursor back at beginning of the previous row. It's up to you to place it in the right horizontal position (using $pos.X to move it sideways):

$pos = $host.ui.RawUI.get_cursorPosition()
$pos.Y -= 1
$host.UI.RawUI.set_cursorPosition($Pos)

Your current output is 27 spaces over, so $pos.X = 27 might work.


It may not be terribly elegant, but it does exactly what OP requested. Note that the ISE messes with StdOut, so there will be no output. In order to see this script work it can't be run within the ISE.

$stdout=[System.Console]::OpenStandardOutput()
$strOutput="Enabling feature XYZ... "
$stdout.Write(([System.Text.Encoding]::ASCII.GetBytes($strOutput)),0,$strOutput.Length)
Enable-SPFeature...
$strOutput="Done"
$stdout.Write(([System.Text.Encoding]::ASCII.GetBytes($strOutput)),0,$strOutput.Length)
$stdout.Close()

I cheated, but I believe this is the only answer that addresses every requirement. Namely, this avoids the trailing CRLF, provides a place for the other operation to complete in the meantime, and properly redirects to stdout as necessary.

$c_sharp_source = @"
using System;
namespace StackOverflow
{
   public class ConsoleOut
   {
      public static void Main(string[] args)
      {
         Console.Write(args[0]);
      }
   }
}
"@
$compiler_parameters = New-Object System.CodeDom.Compiler.CompilerParameters
$compiler_parameters.GenerateExecutable = $true
$compiler_parameters.OutputAssembly = "consoleout.exe"
Add-Type -TypeDefinition $c_sharp_source -Language CSharp -CompilerParameters $compiler_parameters

.\consoleout.exe "Enabling feature XYZ......."
Write-Output 'Done.'

당신은 절대적으로 이것을 할 수 있습니다. Write-Output에는 본질적으로 동일한 " NoEnumerate " 라는 플래그 가 있습니다.

참고 URL : https://stackoverflow.com/questions/3896258/how-do-i-output-text-without-a-newline-in-powershell

반응형