我有几个不寻常的,相对复杂/大型的PowerShell脚本,通过写主机输出彩色文本。 我想复制整个文本输出到Windows剪贴板,而不会丢失制表符(与Windows Control-C,剪贴板副本)或替代。 如果在脚本在PowerShell.exe控制台窗口中运行后突出显示所有文本,请按Control-C(将其复制到Windows剪贴板),将制表符转换为空格。
如果我尝试使用下面的Set-Clipboard cmdlet来pipe理我的脚本的整个输出,则脚本中有太多的组件(主要是Write-Host行),这些组件与进一步的PSpipe道处理不兼容; 所以,下面的设置剪贴板被完全忽略(只显示输出到本地主机控制台)。
PS:我也试过开始 – 脚本\停止 – 抄本。但是,那也不捕获标签。 它将制表符转换为空格。
我希望有人有一个聪明,快捷的方式来剪贴板捕获我从cmdlet得到的文本,需要写主机,这也抓住了制表符字符。
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) } }
我认为你会发现的答案是,使用写主机将永远带你走你不想要的路。 Jeffrey Snover在他的博客中对此进行了讨论。 改变你的脚本来改变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's 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个空格的字符串(如果这是你的标签变成的),那么把你的输出,所有出现的4个空格,替换成一个制表符,然后添加到剪贴板。 Hacky,但是根据我之前关于使用写主机和进一步自动化的路径,这可能适用于您。
在这种情况下,我认为你可以使用像这样的东西:
$objectsToProcess += $inputObject -replace " ", "`t"
反对专家的建议..我仍然觉得我的解决方案是对我的情况最简单(和理想)。 我不会轻易做出这个决定。 特别是当人们花费大量时间来帮助我时。 对不起马特! 如果我的巨大脚本中没有一百万个写主机,我会使用你的解决方案。
重构一个简单的搜索\替换是最简单的解决方案(就我而言)。 我可以将自定义写主机命名为“Write-Host2”。 然后,只需将Write-Host2函数添加到我的脚本中。 它将与大多数写主机参数向后兼容; 加上复制粘贴和制表符兼容颜色输出到本地控制台。