Skip to content

MS word – create and format headers and font style with powershell

2012/06/17

just a short script , how to use some very, very basic functions of word in powershell:

 

$word = new-object -ComObject “Word.Application”
$script:oldFontName = “”

function close-WordApp {
$word.quit()
$word = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()

}

function new-document {
return $word.documents.Add()
}

function change-font {
param( $fontName)

if( $fontname -eq $null) {
$newfont = $script:oldFontName
} else {
$newFont = $fontname
}

$script:oldFontName = $word.selection.Font.Name
$word.selection.Font.Name = $newFont
}

function write-word {
param ($text)

$word.selection.typetext($text)
}

function write-wordHeader {
param ($Headerlevel= “1” , $text)

$selection = $word.selection
$saveStyle = $selection.Style

$selection.style = “Heading $HeaderLevel”
$word.selection.typetext($text)
writecrlf-word
$selection.Style = $saveStyle
}
function writeCRLF-word {
$word.selection.TypeParagraph()
}

function saveandclose-worddoc {
param ( $doc,
[string] $filename)

$doc.SaveAs([ref]$filename)
$doc.close()
}
$word.visible = $true
$doc = new-document
write-word (get-date)
writecrlf-word

$os = Get-WmiObject -Class win32_OperatingSystem

write-wordheader -text “Operating system information for $($os.CSNAME)”
$os.properties | select Name | foreach -begin {$props=@()} -proc {$props+=”$($_.name)”}

change-font “Courier New”
write-word ($os | Select -Property $props | Out-String)
writecrlf-word
change-font
write-word ($os | Select -Property $props | Out-String)
writecrlf-word
saveAndClose-WordDoc -doc $doc -filename “c:\temp\osreport.docx”
close-WordApp

Advertisements
Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: