How to save `n`n tab characters when using a copy of the Windows Control-C clipboard?

I have some unusual, relatively complex / large PowerShell scripts where it outputs colored text through Write-Host. I want to copy all text output to the Windows clipboard without losing tab characters (with Control-C windows, clipboard copy) or an alternative. If I selected all the text after the script runs in the PowerShell.exe console window, then press control-C (to copy it to the Windows clipboard), the tab characters are converted to spaces.

If I try to use the Set-Clipboard cmdlet below to transfer all the output of my script, there are too many components in my script (mainly in Write-Host channels) that are incompatible with further processing of the PS pipeline; therefore, the Set-Clipboard below is completely ignored (only output to the local host console).

PS: I also tried Start-Transcript \ Stop-Transcript .. However, this does not capture the tabs. It converts tabs to spaces.

I was hoping that someone has a smart, quick way to capture the text that I get from the cmdlets that need the write address to the clipboard, ALSO REPLACE the tab characters.

invoke-myscript -Devicename "WindowsPC" | Set-Clipboard
function Set-Clipboard {

param(
    ## The input to send to the clipboard
    [Parameter(ValueFromPipeline = $true)]
    [object[]] $InputObject
)

begin
{
    Set-StrictMode -Version Latest
    $objectsToProcess = @()
}

process
{
    ## Collect everything sent to the script either through
    ## pipeline input, or direct input.
    $objectsToProcess += $inputObject
}

end
{
    ## Launch a new instance of PowerShell in STA mode.
    ## This lets us interact with the Windows clipboard.
    $objectsToProcess | PowerShell -NoProfile -STA -Command {
        Add-Type -Assembly PresentationCore

        ## Convert the input objects to a string representation
        $clipText = ($input | Out-String -Stream) -join "`r`n"

        ## And finally set the clipboard text
        [Windows.Clipboard]::SetText($clipText)
    }
}
+4
source share
2 answers

. , ( ) . ; , . ! script, .

\replace - ( ). - "Write-Host2". Write-Host2 script (s). Write-Host; , - , , .

0

, , , , Write-Host , . . , , Write-Host Write-Output , , , , Write-Verbose / Write-Warning.

, , , -OutVariable ().

, , .

function print-with-tab {
  [cmdletbinding()]
  Param()

  Write-Host "HostFoo`t`t`tHostBar"
  Write-Output "OutFoo`t`t`tOutBar"
  Write-Warning "You have been warned."
}

print-with-tab -OutVariable outvar -WarningVariable warnvar

Write-Output "Out -->"
$outvar
# proof there tabs in here
$outvar -replace "`t", "-"
Write-Output "Warn -->"
$warnvar

HostFoo         HostBar
OutFoo          OutBar
WARNING: You have been warned.
Out -->
OutFoo          OutBar
OutFoo---OutBar
Warn -->
You have been warned.

, , ( , ), , 4 , , . , , Write-Host ... .

, , - :

$objectsToProcess += $inputObject -replace "    ", "`t"
+3

Source: https://habr.com/ru/post/1621326/


All Articles