且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除powershell输出中的空行...一般

更新时间:2023-12-04 20:44:52

您可以定义一个自定义Out-Default 函数,从输出中删除所有空行/空白行(仅用于显示):

You can define a custom Out-Default function that removes all empty/blank lines from the output (for display only):

function Out-Default { 
  $Input | Out-String -Stream | Where { $_.Trim().Length -gt 0 } | Write-Host
}

您可以将它放在您的 $PROFILE 文件中,以便在以后的所有会话中都可用(使用 -NoProfile 调用 PowerShell 的会话除外).

You can place it in your $PROFILE file to be available in all future sessions (except those where PowerShell is invoked with -NoProfile).

所有命令隐式使用这个函数用于到主机(控制台)输出,因为Out-Default是 PowerShell 在幕后调用的特殊命令,用于处理到主机的输出(即,既不捕获也不通过管道传递也不重定向的输出).

All commands implicitly use this function for to-host (console) output, because Out-Default is a special command that PowerShell calls behind the scenes for handling to-host output (that is, for output that is neither captured nor piped nor redirected).

因此,一旦定义了函数,只需调用 Get-ChildItem(别名为 dir),例如,应该产生全为空/空白的输出已删除.

Therefore, once the function has been defined, simply calling Get-ChildItem (which is aliased to dir), for instance, should produce output with all empty/blanks removed.

请注意,捕获/管道/重定向输出受到影响,这是理想的.

Note that capturing / piping / redirecting output is not affected, as is desirable.

警告:如前所述,Out-Default 仅影响 to-host 输出,不影响其他格式化系统的行为-based Out-* cmdlet,如果需要,您必须单独重新定义.

Caveat: As stated, Out-Default only affects to-host output, not also the behavior of other formatting system-based Out-* cmdlets, which you'd have to redefine separately, if desired.

值得注意的是,重新定义的Out-Default不会影响Out-File 及其有效别名>/>> - 请参阅底部以了解执行相同剥离的自定义 Out-File 实现空行.

Notably, a redefined Out-Default does not affect Out-File and its effective aliases > / >> - see the bottom section for a custom Out-File implementation that performs the same stripping of blank lines.

顺便说一句:PowerShell 带有默认的 Out-Default 命令,作为 cmdlet 实现.虽然您可以直接调用Out-Default(无论是默认实现还是自定义实现),但没有理由这样做,应该避免这样做 - 请参阅这个答案.

As an aside: PowerShell comes with a default Out-Default command, implemented as a cmdlet. While you can call Out-Default directly (whether the default implementation or a custom one), there is no reason to, and doing so should be avoided - see this answer.

正如 Compo 指出的那样,您可以使用相同的技术特别,对于给定的命令;例如:

As Compo points out, you can use the same technique ad hoc, for a given command; e.g.:

Get-ChildItem | Out-String -Stream | Where { $_.Trim().Length -gt 0 }

但是,请注意 - 与 Out-Default 方法不同 - 这种技术适合仅用于显示,因为您输出字符串表示而不是原始对象(如果您要通过管道传输到Write-Host,您将完全绕过(成功)输出流).

Note, however, that - unlike the Out-Default approach - this technique is suitable for display only, because you're then outputting string representations rather than the original objects (and if you were to pipe to Write-Host, you would bypass the (success) output stream altogether).

自定义 Out-File 函数,也可以去除空行/空白行,也由 >/>> 调用>:

Custom Out-File function that also strips empty/blank lines and is also called by > / >>:

注意:

  • 这个函数比自定义的Out-Default函数更复杂,因为它需要支持与原始cmdlet相同的参数.

  • This function is more complex than the custom Out-Default function, because it needs to support the same parameters as the original cmdlet.

它会明显比原来的Out-File/>/>>,它不支持常见的 -Confirm-WhatIf 参数(它们很少与 Out-File 一起使用,但是).

It will be noticeably slower than the original Out-File / > / >>, and it doesn't support the common -Confirm and -WhatIf parameters (which are rarely used with Out-File, however).

如下所示,该函数专为在 PowerShell [Core] v6+ 中使用而设计 - 请参阅源代码中的注释,了解如何(轻松)使其适应 WindowsPowerShell.

As printed below, the function is designed for use in PowerShell [Core] v6+ - see the comments in the source code for how to (easily) adapt it to Windows PowerShell.

# Note: Supports neither -Confirm nor -WhatIf
function Out-File {
  [CmdletBinding(DefaultParameterSetName = 'ByPath', HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=2096621')]
  param(
    [Parameter(ParameterSetName = 'ByPath', Mandatory, Position = 0)]
    [Alias('Path')]
    [string] $FilePath,
  
    [Parameter(ParameterSetName = 'ByLiteralPath', Mandatory, ValueFromPipelineByPropertyName)]
    [Alias('PSPath', 'LP')]
    [string]
    $LiteralPath,
  
    [Parameter(Position = 1)]
    # Note: This validation set is for PowerShell *Core* (v6+).
    # For Windows PowerShell support, comment out the the next line and uncomment the one after.
    [ValidateSet('ascii','bigendianutf32','unicode','utf8','utf8NoBOM','bigendianunicode','oem','utf7','utf8BOM','utf32')]
    # [ValidateSet('default', 'ascii','bigendianutf32','unicode','utf8','bigendianunicode','oem','utf7','utf32')]
    [string] $Encoding,
  
    [switch] $Append,
  
    [switch] $Force,
  
    [Alias('NoOverwrite')]
    [switch] $NoClobber,
  
    [ValidateRange(2, 2147483647)]
    [int] $Width,
  
    [switch] $NoNewline,
  
    [Parameter(ValueFromPipeline = $true)]
    [psobject] $InputObject
  )
  
  $null = $PSBoundParameters.Remove('InputObject')

  $Input | Out-String -Stream | Where-Object { $_.Trim().Length -gt 0 } | 
    Microsoft.PowerShell.Utility\Out-File @PSBoundParameters

}