Site icon Dotnet Helpers

Add text to Word Using PowerShell

For most of the automation and report we will prefer and use Excel , instead of excel her we look at how you can use Word with PowerShell to create a document.One of the first things that you need to do is ensure that you have Word installed on your computer. Once you have that verified, we can begin by creating a COM object connection to Word.Application, which will help us to begin the interacting with Word.

Running the below script that was just looking to create the document without showing anything, and making Visible property on the object to True. So after creating this object ($word) which will help to interacting with Word and its ready for our operations.

$word=new-object -ComObject “Word.Application”
$Word.Visible = $True

Before using edit on the word document before that, we need to add a document to our Word object and then select it so we can being adding text to it.

$doc = $word.documents.Add()
$myDoc = $word.Selection

Now we are ready to begin to edit and start writing in our Word document.Here i am going to generate the comments document from the PowerShell script, so you can achieve this using the TypeText() method, which is available on $myDoc object.

If we use of the TypeText method, the we need to understand the text will appear on the same line as the rest of the text. So we need to use the TypeParagraph method which use to start on a new line like break tag in HTML and then you use TypeText to begin writing on a brand-new line.

$myDoc.Style=”Strong”
$myDoc.TypeParagraph()
$myDoc.TypeText(“Hi All, “)
$myDoc.TypeParagraph()
$myDoc.TypeText(“This is Message from dotnet-helpers.com “)

Final Code:

OUTPUT

 

Exit mobile version