Búsqueda de sitios web

Enviar desde PowerShell ISE a Microsoft Word revisado


A muchos de ustedes pareció gustarles mi pequeño complemento PowerShell ISE para enviar texto desde el panel de secuencias de comandos a un documento de Word. Debería haber sabido que alguien preguntaría sobre una forma de colorearlo. Puede seleccionar líneas manualmente en un script y cuando las pega en Word, heredan automáticamente los tokens coloreados. Desafortunadamente, encontrar un equivalente de PowerShell es mucho más complicado.

Si busca, encontrará muchas herramientas y scripts para generar HTML y resultados coloreados desde ISE. Intenté incorporar algunos de ellos en mi guión, pero eran mucho más complicados de lo que quería abordar. Todo lo que realmente necesitaba era un simple comando Ctrl+C. Entonces hice trampa. Decidí usar el método SendKeys() de VBScript.

if ($Colorized) {
    #copy the selection to the clipboard and paste
    #This is a shortcut hack that may not always work the first time
    $wshell = New-Object -ComObject Wscript.shell
    #must be lower-case c otherwise you will end up sending
    #ctrl+shift+c
    $wshell.SendKeys("^c") 
    #timing is everything with SendKeys. This could be a lower value
    start-sleep -Milliseconds 500
    $global:selection.Paste()
}

Agregué un nuevo parámetro de cambio a la función llamada Colorizado. Esto significaba que también necesitaba un acceso directo al menú adicional.

$psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Send to Word Colorized",{Send-ToWord -Colorized},"") | Out-Null

Notarás que no hay ningún método abreviado de teclado. Al menos para mí, obtuve resultados inconsistentes usando un atajo de teclado y, a menudo, nada. Pero si seleccionaba el elemento del menú, siempre parecía funcionar.

Aquí está la función completa actualizada.

#requires -version 3.0

#this is an ISE only function
Function Send-ToWord {
[cmdletbinding()]
Param(
[ValidatePattern("\S+")]
[string[]]$Text = $psise.CurrentFile.Editor.SelectedText,
[switch]$Colorized
)

If (($global:word.Application -eq $Null) -OR -NOT (Get-Process WinWord)) {
    #remove any variables that might be left over just to be safe
    Remove-Variable -Name doc,selection -Force -ErrorAction SilentlyContinue

    #create a Word instance if the object doesn't already exist
    $global:word = New-Object -ComObject word.application

    #create a new document
    $global:doc = $global:word.Documents.add()

    #create a selection
    $global:selection = $global:word.Selection

    #set font and paragraph for fixed width content
    $global:selection.Font.Name = "Consolas"
    $global:selection.font.Size = 10
    $global:selection.paragraphFormat.SpaceBefore = 0
    $global:selection.paragraphFormat.SpaceAfter = 0

    #show the Word document
    $global:word.Visible = $True    
}

if ($Colorized) {
    #copy the selection to the clipboard and paste
    #This is a shortcut hack that may not always work the first time
    $wshell = New-Object -ComObject Wscript.shell
    #must be lower-case c otherwise you will end up sending
    #ctrl+shift+c
    $wshell.SendKeys("^c") 
    #timing is everything with SendKeys. This could be a lower value
    start-sleep -Milliseconds 500
    $global:selection.Paste()
}
else {
#insert the text
$global:selection.TypeText($text) 
}

#insert a new paragraph (ENTER)  
$global:selection.TypeParagraph()

} #end Function

#add to menu
$psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Send to Word",{Send-ToWord},"Ctrl+Alt+W") | Out-Null                

#keyboard shortcut doesn't always work
$psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Send to Word Colorized",{Send-ToWord -Colorized},"") | Out-Null

No puedo garantizar que copiar y pegar en color funcione el 100% del tiempo. De lo contrario, siempre puedes utilizar los atajos de teclado tradicionales: Ctrl+C, Alt+Tab (a Word), Ctrl+V.

Disfrutar.

Artículos relacionados