Need help figuring out why Powershell is throwing error 16 - powershell

I posted this script the other day in an effort to discover a good way to change file extensions when "saving as." I had the problem licked, but as of this morning, the script will not run without errors. Here's the error message I'm getting:
Processing : C:\users\xxx\Desktop\ht\Automatic_Post-Call_Survey.htm
Exception calling "SaveAs" with "16" argument(s): "This is not a valid file name.
Try one or more of the following:
* Check the path to make sure it was typed correctly.
* Select a file from the list of files and folders."
At C:\users\xxx\Desktop\hd.ps1:11 char:20
+ $opendoc.saveas <<<< ([ref]"$docpath\$doc.FullName.doc", [ref]$saveFormat);
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
if "16" is the error code, that represents an inability to delete the directory...but it doesn't appear as if I'm asking for that at all--unless there's some default parameter in place somewhere. I'm pretty much baffled.anyone have any other ideas I can try out?
$docpath = "c:\users\xxx\desktop\do"
$htmPath = "c:\users\xxx\desktop\ht"
$srcfiles = Get-ChildItem $htmPath -filter "*.htm*"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument");
$word = new-object -comobject word.application
$word.Visible = $False
$filename = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
function saveas-document {
$opendoc = $word.documents.open($doc.FullName);
$opendoc.saveas([ref]"$docpath\$filename", [ref]$saveFormat);
$opendoc.close();
}
ForEach ($doc in $srcfiles) {
Write-Host "Processing :" $doc.FullName
saveas-document
$doc = $null
}
$word.quit();

this should do what do you need, but is not the best design :)
$docpath = "c:\users\xxx\desktop\do"
$htmPath = "c:\users\xxx\desktop\ht"
$srcfiles = Get-ChildItem $htmPath -filter "*.htm*"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument");
$global:word = new-object -comobject word.application
$word.Visible = $False
#$filename = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
function saveas-document ($docs) {
$opendoc = $word.documents.open($docs);
$savepath = $docs -replace [regex]::escape($htmPath),"$docpath"
$savepath = $savepath -replace '\.html*', '.doc'
$opendoc.saveas([ref]"$savepath", [ref]$saveFormat);
$opendoc.close();
}
ForEach ($doc in $srcfiles) {
Write-Host "Processing :" $doc.FullName
saveas-document -doc $doc.FullName
$doc = $null
}
$word.quit();

Related

This command is not available. By writing to Word with Powershell

My powershell script yesterday stopped working. I have changed nothing in the code or in the path to files. It just stopped working. I can't explain it.
I've tested all path and all variables and its look fine.
function Gen-Doc($Replace, $dataToRaplace, $user_name, $austauch) {
$objWord = New-Object -comobject Word.Application
$objWord.Visible = $false
if ($austauch -eq $true) {
$objDoc = $objWord.Documents.Open("C:\Path\To\Docu\Vorlage\Doc1.docx")
} else {
$objDoc = $objWord.Documents.Open("C:\Path\To\\Docu\Vorlage\Doc2.docx")
}
$objSelection = $objWord.Selection
$n = 0
while ($n -ne $dataToRaplace.Length) {
$FindText = $Replace[$n]
$ReplaceWith = $dataToRaplace[$n]
$MatchCase = $False
$MatchWholeWord = $true
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $wdFindContinue
$Format = $False
$wdFindContinue = 1
$wdReplaceAll = 2
$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith,$wdReplaceAll)
$n++
}
$filename = $user_name
$objDoc.SaveAs("C:\Path\To\Docu\$filename.docx")
$objWord.Quit()
if ($checkbox2.Checked -eq $true) {
Start-Process -FilePath "C:\Path\To\Docu\$filename.docx" -Verb print
}
}
And here is error message
This command is not available.
At C:\Scripts\Done\Ausgabe.ps1:103 char:9
+ $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWh ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
Make sure you don't have your document opened before doing $objDoc.SaveAs.
Check process manager for orphan WINWORD.EXE processes running.

Opening Large Set of Word Documents With Powershell - Automation

I am in the process of assigning a footer to hundreds of word documents with their current filepath. Here is my code, which does the job:
I plan to have $Word.Visible set to false, but it isn't for now for debugging purposes.
This gets all the word docs in a directory, adds footer with their file path, then saves and closes.
I am trying to handle a case like this:
I just want to skip this, or possibly force open and continue. Not sure the best way to go about this, however, and am seeking some help.
Thanks,
Elijah
Set-ExecutionPolicy bypass;
$path = 'somepath';
$documents = Get-ChildItem -Path $path *.docx -Recurse -Force
$filepaths = foreach ($document in $documents) {$document.fullname}
$Word = New-Object -ComObject Word.application;
$Word.Visible = $true;
foreach ($filepath in $filepaths){
$Doc = $Word.Documents.OpenNoRepairDialog($filepath);
$Doc.Unprotect();
$Selection = $Word.Selection;
$Doc.ActiveWindow.ActivePane.View.SeekView = 4;
$Selection.ParagraphFormat.Alignment = 1;
$Selection.TypeText($filepath);
$Doc.Save();
$Doc.Close();
}
$Word.Quit();
Edit1:
I've made an edit where it adds the dynamic field object for the file path, rather than just typing in the file path, that way if you happen to move the file, the file path can be updated to the new path. You will have to press F9 while selecting the footer in word, but this is the best you can do without making a macro and saving the file as a .docm.
Here is the amended code:
$documents = Get-ChildItem -path *docx -recurse -force
$filepaths = foreach($document in $documents){$document.FullName}
Set-Variable -Name wdFieldFileName -Value 29 -Option constant -Force -ErrorAction SilentlyContinue
$word = New-Object -ComObject Word.Application
#$word.Visible = $true
foreach($filepath in $filepaths){
$doc = $word.Documents.Open($filepath)
$sections = $doc.Sections
$item1 = $sections.Item(1)
$footer = $item1.Footers.Item(1)
$range = $footer.Range
$doc.Fields.Add($range, $wdFieldFileName, '\p')
$doc.Save()
$doc.Close()
}
$word.Quit()
I am still running into the error window when trying to open corrupted or document "in need of repair" as diagnosed by word.
Passing in multiple arguments to the Open() method does not yield results as expected. Here is an example:
Exception calling "Open" with "16" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At line:1 char:1
+ $doc = $word.Documents.Open($filepath, $False, $False, $False, $null, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation

Powershell Unable to find type [Microsoft.Office.Interop.Word.WdSaveFormat]

I'm using this script to convert DOC to HTML
param([string]$docpath,[string]$htmlpath = $docpath)
$srcfiles = Get-ChildItem $docPath -filter "*.doc"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatFilteredHTML");
$word = new-object -comobject word.application
$word.Visible = $False
function saveas-filteredhtml
{
$opendoc = $word.documents.open($doc.FullName);
$opendoc.saveas([ref]"$htmlpath\$doc.fullname.html", [ref]$saveFormat);
$opendoc.close();
}
ForEach ($doc in $srcfiles)
{
Write-Host "Processing :" $doc.FullName
saveas-filteredhtml
$doc = $null
}
$word.quit();
Unfortunately when I run it for the first time in the ISE console I get this error
Unable to find type [Microsoft.Office.Interop.Word.WdSaveFormat].
In F:\PS\NEW\main.ps1:108 car:29
+ ... = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFor ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Offic...rd.WdSaveFormat:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
While if I run it from the same console again the second time it works fine.
How can I solve the problem? Thanks
In this forum they solve the problem:https://gallery.technet.microsoft.com/office/6f7eee4b-1f42-499e-ae59-1aceb26100de/view/Discussions
you add this lines at the beginning of your code:
$wdTypes = Add-Type -AssemblyName 'Microsoft.Office.Interop.Word' -Passthru
$wdSaveFormat = $wdTypes | Where {$_.Name -eq "wdSaveFormat"}

Install windows update

I have following powershell script which should update my windows OS everytime I run it. Therefore I use the given windows API in order to search, download and install the updates. But somehow only searching for them actually works.
This is my script:
$global:scriptpath = $MyInvocation.MyCommand.Path
$global:dir = Split-Path $scriptpath
$global:logfile = "$dir\updatelog.txt"
write-host " Searching for updates..."
$session = New-Object -ComObject Microsoft.Update.Session
$searcher = $session.CreateUpdateSearcher()
$result = $searcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
if ($result.Updates.Count -eq 0) {
Write-Host "No updates to install"
} else {
$result.Updates | Select Title
}
$downloads = New-Object -ComObject Microsoft.Update.UpdateColl
foreach ($update in $result){
try {
$update.AcceptEula()
$Null = $downloads.Add($update)
} catch {}
}
$count = $result.Updates.Count
write-host ""
write-host "There are $($count) updates available."
write-host ""
read-host "Press Enter to download\install updates"
$downloader = $session.CreateUpdateDownLoader()
$downloader.Updates = $downloads
$downloader.Download()
$installs = New-Object -ComObject Microsoft.Update.UpdateColl
foreach ($update in $result.Updates){
if ($update.IsDownloaded){
$installs.Add($update)
}
}
$installer = $session.CreateUpdateInstaller()
$installer.Updates = $installs
$installresult = $installer.Install()
$installresult
But I get following error:
Exception calling "Download" with "0" argument(s): "Exception from HRESULT: 0x80240024"
+ $downloader.Download()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Somehow this line: $downloader.Updates = $downloads is not executed, but I don't know why. I also already tried running the script as an admin, didn't work either.
That error code is the WU_E_NO_UPDATE, described here. Basically it says that the Updates collection is not set or empty.

IE History Permissions for other users

I have a script which I think is most of the way to being able to grab IE history for all of the users on a machine. My problem is it doesn't work for users other than myself because I get a permissions error when attempting open the folder. Does anyone have any ideas how I can fix the permissions problem?
I'm running this script on a Windows 2012r2 machine and I am an administrator on the box.
Thanks!
function Get-History
{
param
(
[string]$userName
)
$shell = New-Object -ComObject Shell.Application
if($username)
{
$users = $username
}
else
{
$users = Get-ChildItem C:\Users
}
if((([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")))
{
Foreach($user in $users)
{
$user = Split-Path $user -leaf
try
{
$ErrorActionPreference = 'Stop'
$hist = $shell.NameSpace("C:\Users\$user\AppData\Local\Microsoft\Windows\History")
}
catch
{
continue
}
$folder = $hist.Self
#$folder.Path
if($hist){
$hist.Items() | foreach {
#""; ""; $_.Name
if ($_.IsFolder) {
$siteFolder = $_.GetFolder
$siteFolder.Items() | foreach {
$site = $_
#""; $site.Name
if ($site.IsFolder) {
$pageFolder = $site.GetFolder
$pageFolder.Items() | foreach {
$url = $pageFolder.GetDetailsOf($_,0)
$date = $pageFolder.GetDetailsOf($_,2)
#"$user`: $date visited $url"
#Write-Output ("$user,$date,`"$url`"" | ConvertFrom-Csv)
New-Object -TypeName PSObject -Property #{
user=$user;
date = $date;
url = $url
}
}
}
}
}
}
}
}
}
else
{
Write-Host "Not Admin"
}
}
If I run just the small snippet:
$shell = New-Object -ComObject Shell.Application
$hist = $shell.NameSpace("C:\Users\MyOwnUsername\AppData\Local\Microsoft\Windows\History")
Then I successfully assign the $hist variable as a System.__ComObject
But if I run:
$shell = New-Object -ComObject Shell.Application
$hist = $shell.NameSpace("C:\Users\SomeOtherUser\AppData\Local\Microsoft\Windows\History")
I get:
Exception calling "NameSpace" with "1" argument(s): "Unspecified error (Exception from HRESULT: 0x80004005 (E_FAIL))"
At line:3 char:1
+ $hist = $shell.NameSpace("C:\Users\SomeOtherUser\AppData\Local\Microsoft\Windows\History ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Full Disclosure: it's a slight modification of the script at this blog post
I never solved the permissions problem. I changed strategy to use BrowsingHistoryViewer by Nirsoft.
$execPath = "C:\BrowsingHistoryView.exe"
$computers = 'computer1','computer2','computer3','computer4'
$outPath = "c:\"
$computers |
ForEach-Object{ `
Start-Process $execPath `
-argumentList "/HistorySource 3",
"/HistorySourceFolder ""\\$_\c$\Users""",
"/scomma ""$outpath\history_$_.txt"""
}