i'm trying to write a Powershell-script that edits Text Form Fields in Microsoft Office Word 2007. It should find a Form Field via the Bookmark I configured before and write a Text into it. The default text I wrote into it for test purposes is "Something".
That's what I have so far:
$document = 'D:\Powershell\Test.docx'
$Word = New-Object -Com Word.Application
$Word.Visible = $True
$doc = $word.Documents.Open($document)
$text = "Hello"
$bookmark = "server1"
$doc.Bookmarks.Item($bookmark).Range.Text.Replace("Something", $text)
While it works in the console since the output is:
FORMTEXT Hello
Word still displays the String I inserted manually before.
When I type in:
$doc.Bookmarks.Item($bookmark).Range.Text
The output is:
FORMTEXT Something
I already tried:
$Word.ActiveDocument.Reload()
$Word.ActiveDocument.Fields.Update()
$doc.PrintPreview()
$doc.ClosePrintPreview()
$doc.Bookmarks.Item($bookmark).Range.Fields.Update()
But nothing seems to work.
Has somebody an idea how to write something in that Text Form Field permanently?
Alternatively if that's easier I could use a (rich) Text Content Control (which seem to be newer). Those don't use a bookmark but a tag and title.
Thanks for you help in advance .
PS:It doesn't work with MS Word 2016 either.
When you have a legacy text form field, the bookmark is really there to identify the field. If you try to write replace the text of the bookmark in VBA (say) you'll probably get Error 6028 - "The range cannot be deleted".
I don't know Powershell well enough to do this without checking, but the equivalent VBA would be
doc.FormFields($bookmark).Result = "Something"
so I would guess the powershell is something like
$doc.FormFields.Item($bookmark).Result = "Something"
Related
Question about running a custom function in Powershell.
I'm on Windows 10 and I'd like to somehow print my monorepository's directory tree structure excluding node_modules. This is not supported out of the box but requires a custom function to be defined. I found one solution on StackOverflow (https://stackoverflow.com/a/43810460/9654273), which would enable using a command like:
tree -Exclude node_modules -Ascii > tree.txt
The problem is I don't know what to do with the provided source code :D The answer says "add to your $PROFILE, for instance", so I ran notepad $PROFILE in PowerShell, pasted the code snippet there, saved it and tried running the command. It didn't work because I did something wrong. According to the StackOverflow post's comments from anand_v.singh and mklement0 I was still running some other tree command, not the one I just attempted to define.
So how do I use a custom function in PowerShell? Starting point is that source code is on StackOverflow and I don't know where to paste it. Or do you know some other, easier way to print a directory tree on Windows 10 excluding node_modules?
I had the same problem with that function. The issue is the special characters in the hashtable at line 106:
$chars = #{
interior = ('├', '+')[$ndx]
last = ('└', '\')[$ndx] #'
hline = ('─', '-')[$ndx]
vline = ('│', '|')[$ndx]
space = ' '
}
I changed the special characters to ascii as follows:
$chars = #{
interior = ('+', '+')[$ndx]
last = ('\', '\')[$ndx] #'
hline = ('-', '-')[$ndx]
vline = ('|', '|')[$ndx]
space = ' '
}
The only downside is that you do not now have the option of using special graphics characters (the Ascii switch is still there, but does nothing). Maybe someone could tell us how to embed them properly.
I have a requirement to have a small script on a Windows Server using PowerShell to convert files to PDF (from RTF). I've got a prototype using Word that works on my desktop machine, but the servers involved don't have Office/Word installed. Is there a similar way I can call Wordpad to achieve the same thing?
$documents_path = 'c:\projects\pbl\hi.rtf'
$word_app = New-Object -ComObject Word.Application
$document = $word_app.Documents.Open($documents_path)
$pdf_filename = 'c:\projects\pbl\hi.pdf'
$document.SaveAs([ref] $pdf_filename, [ref] 17)
$document.Close()
$word_app.Quit()
You would not be able to accomplish this goal using only WordPad because it has no automation interface like Microsoft Word has. You would need to investigate an alternative solution to achieve this.
This is old thread so no point in addressing OP question as such
However for the benefit of others landing here, this is a "Yes" Answer, I have not run it on a server, but understand there may be issues calling MS Print to PDF -- headless, for several reasons, including it uses the Graphics Device Interface. It works perfectly on a workstation.
It is done as a one line command along these lines, Input could be %1 with %2 for Output.
There are 2 WordPad.exe's to try :-)
This is the default American English one:-
%comspec% "C:\Windows\System32\wordpad.exe" /pt "%Input%" "Microsoft Print to PDF" "Microsoft Print to PDF" "%Output%"
OR my Locale British English one, which I target !
"%ProgramFiles%\Windows NT\Accessories\WORDPAD.EXE" /pt %1 "Microsoft Print to PDF" "Microsoft Print to PDF" %2
For a drag and drop wrapper see:-
Doc2PDF.cmd - Convert .Doc(x), .ODT, .RTF or .Txt to PDF & open them in SumatraPDF
P.S
A better replacement to WordPad is Jarte Pro and if you have a Portable WinWord.exe you could look at https://stackoverflow.com/a/2749172/10802527
Looking here:
Is it possible to change an .rtf file to .txt file using some sort of batch script on Windows?
I have saw which possible use POWERSHELL for to do it. Was present a full example for to do it but link don't work.
Who can tell me as i can to solve it? Thanks.
You can use .NET to do this in powershell very easily by implementing the System.Windows.Forms.RichTextBox control, loading the richtextfile into it, then pulling the text version out. This is by far the easiest and quickest way I have found to do this.
My function for doing exactly this is here: https://github.com/Asnivor/PowerShell-Misc-Functions/blob/master/translate-rtf-to-txt.ps1
To explain this a little more basically:
$rtfFile = [System.Io.FileInfo]"path/to/some/rtf/file"
$txtFile = "path/to/the/destination/txt/file"
# Load *.rtf file into a hidden .NET RichTextBox
$rtBox = New-Object System.Windows.Forms.RichTextBox
$rtfText = [System.IO.File]::ReadAllText($rtfFile);
$rtBox.Rtf = $rtfText
# Get plain text version
$plainText = $rtBox.Text;
# Write the plain text out to the destination file
[System.IO.File]::WriteAllText($txtFile, $plainText)
So I need to highlight text from an element (textarea), copy that highlighted and then paste it into another element.
Storing the value from the first element and then populate the other element using SendKeys is not an option for me. Because then I will run into other issues with a javascript.
This is an example on how far I've got so far:
# Creating FirefoxDriver
$driver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver
# Go to made up URL
$driver.url = "https://www.madeupdomain.com/"
# Find element and store in $MyElement
$MyElement = $driver.FindElementByXPath("//*[#id='MadeUpTextAreaElementId']")
# Attempt to highlight all
$MyElement.SendKeys($driver.keys.CONTROL + 'A')
# Attempt to copy text from text
$MyElement.SendKeys($driver.keys.CONTROL + 'C')
# Find another element to paste text to
$MyOtherElement = $driver.FindElementByXPath("//*[#id='AnotherMadeUpTextAreaElementId']"
# Attempt to paste copied text to another element
$MyOtherElement.SendKeys($driver.keys.CONTROL + 'V')
But this will simply type in "A" and "C" into the first element, and then "V" into the the last element.
Guessing the issue is with the "$driver.keys.CONTROL" parts. How do I get Selenium to understand it's a keycombo I want to perform?
Turns out I started out wrong regarding "$driver.keys.CONTROL" being the issue.
"$driver.keys.CONTROL" is nowhere near the solution!
In order to simulate ctrl + a, ctrl + c, and ctrl + v in Powershell you need to use System.Windows.Forms.SendKeys. A list of all available keystrokes using this may be found here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send(v=vs.110).aspx
Secondly in order to use these keystrokes with a Selenium webdriver I used the SendKeys methods from OpenQA.Selenium.Interactions.Actions. Which I discovered after looking into a couple of java related threads. Took me some time to convert into Powershell friendly code:
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/interactions/Actions.html#sendKeys(java.lang.CharSequence...)
So anyway here is my code updating, doing the ctrl + a, ctrl + c, and ctrl + v actions I needed:
# Creating FirefoxDriver
$driver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver
# Create instans of Actions
$actions = New-Object OpenQA.Selenium.Interactions.Actions($driver)
# Go to made up URL
$driver.url = "https://www.madeupdomain.com/"
# Find element and store in $MyElement
$MyElement = $driver.FindElementByXPath("//*[#id='MadeUpTextAreaElementId']")
# Attempt to highlight all
$actions.SendKeys($MyElement,[System.Windows.Forms.SendKeys]::SendWait("^a")) | out-null
# Attempt to copy text from text
$actions.SendKeys($MyElement,[System.Windows.Forms.SendKeys]::SendWait("^c")) | out-null
# Find another element to paste text to
$MyOtherElement = $driver.FindElementByXPath("//*[#id='AnotherMadeUpTextAreaElementId']"
# Attempt to paste copied text to another element
$actions.SendKeys($MyElement,[System.Windows.Forms.SendKeys]::SendWait("^v")) | out-null
Just make sure you have your browser window on focus when using System.Windows.Forms.SendKeys! I did the mistake to have my powershell prompt selected during some runs, which caused unnecessarily troubleshooting.
Given that Find.Execute does not allow for RegEx, is there any COM way to do this besides streaming the paragraphs out and stepping through them one by one?
I need to find a RegEx pattern in a Word document, and preferably return the match. Failing that, find a RegEx in a Word document and at least return $True so I can capture it.
N.B.: I realize that the reason Find.Execute is limited is due to it being a call to the "find text" dialog, but I'm hoping there's some similarly efficient way to search for patterns. Find.Execute is fairly quick, streaming out the text from the document as a range and then searching through that is not.
When exactly did Find.Execute stop allowing for regular expressions?
$wd = New-Object -COM "Word.Application"
...
$fnd = $wd.Selection.Find
$fnd.Text = "..." # replace with your pattern
$fnd.MatchWildcards = True
...
$fnd.Execute
The syntax is just a little different from standard regular expressions.