Word as COM object has no attributes/ability to set attributes - powershell

I'm sorry that this is quite alien to me, but I had a previously working script that functioned like the following:
$wd = new-object -comobject word.application
but when I print the COM object it has empty/blank values for all attributes.
PS C:\Users\XXX> $wd
Application :
Creator :
Parent :
Name :
Documents :
Windows :
ActiveDocument :
ActiveWindow :
Selection :
And it cannot set any or perform any functions
PS C:\Users\XXX> $wd.Visible = $true
Exception setting "Visible": "Unable to cast COM object of type 'Microsoft.Office.Interop.Word.ApplicationClass' to interface type 'Microsoft.Office.Interop.Word._Application'. This
operation failed because the QueryInterface call on the COM component for the interface with IID '{00020970-0000-0000-C000-000000000046}' failed due to the following error: Error loading
type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))."
At line:1 char:1
+ $wd.Visible = $true
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
I tried browsing related questions but was unable to see if the mistakes are exactly identical. I've run all Windows updates and did a repair installation of Office. (Running Windows 10 and Office 2013)

Sometimes Word/Excel/PPT COM Objects are acting wildly. Thus using these is not recommended for automation purposes by Microsoft itself (sorry but couldn't find the source). But whatever personally I use those all the time :).
System Restore or closing and repoening the Powershell Session actually fixes those problems for me.
Unfortunately I couldn't figured out a programmatic way to handle this yet. So looking forward for further answers. (+1)

Related

Converting Doc(x) files to PDF in PowerShell

I am trying to convert Word file(s) to PDF. I have found a code that is using ComObject Word.Application.
However, running the command:
$word = New-Object -ComObject word.application returns the following error:
`New-Object : Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception
from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
At line:1 char:9
$word = New-Object -ComObject word.application
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : ResourceUnavailable: (:) [New-Object], COMException
FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand`
I have MS Word installed and running fine.
I have found that my PowerShell is running 64-bit version but my Office installed as 32-bit. This may be an issue but I cannot control it as the script will be powered by 3rd party application that I have no control over and Office is installed on many computers that I really do not control also.
Can I somehow register that Class? Can I do the conversion without any 3rd party software (like Word or LibreOffice) installed? Any other suggestions?
Thanks
Need to create a PDF file
I was not running as Admin.
However, I noticed that the same script was running fine on my other computer and everything seems the same on both of them. So, I have done the "repair" of the Office installation and that has fixed the issue.

InvalidCastException when trying to obtain UserPrincipal.Current

I have a PowerShell script which checks the currently signed in user as part of its start-up process. I'm using .Net to do this by adding the assembly:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$cUser = [System.DirectoryServices.AccountManagement.UserPrincipal]::Current
For almost everyone this works fine and I get a UserPrincipal object that I can use elsewhere, however there are a couple of users who get the following error when running it:
Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'. At line:2 char:1
+ [System.DirectoryServices.AccountManagement.UserPrincipal]::Current
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidCastException
+ FullyQualifiedErrorId : System.InvalidCastException
This is on a standard Windows 10 20H2 install and doesn't matter if PowerShell is running elevated or not. I've never seen this call return anything other than a UserPrincipal before, so I would be grateful for any advice: is this something I can deal with in code, or is there some underlying issue with the machines that are returning this exception?
I don't know if this is what you're looking for:
$cUser = Get-ADUser $Env:Username -Properties *
This has the most important attributes that you can use for whatever you want later on. It provides as much attribute as the code you posted that didn't work for some of the user.

Error downloading files with DownloadFile in powershell 2

I have the need to download files under powershell 2.
Since Invoke-WebRequest is not supported in version 2, I try to use DownloadFile but I always get the same error and I don't know how to fix it.
PS C:\Users\user> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
:: : Exception setting "SecurityProtocol": "Cannot convert null to type "System.Net.SecurityProtocolType" due to invali
d enumeration values. Specify one of the following enumeration values and try again. The possible enumeration values ar
e "Ssl3, Tls"."
At line:1 char:28
+ [Net.ServicePointManager]:: <<<< SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
PS C:\Users\user> $client = new-object System.Net.WebClient
PS C:\Users\user> $client.DownloadFile("https://web.com/test.txt", "C:\Users\user\Desktop\test.txt")
DownloadFile : Exception calling "DownloadFile" with "2" argument(s): "The underlying connection was closed: An unexpec
ted error occurred on a send."
At line:1 char:21
+ $client.DownloadFile <<<< ("https://web.com/test.txt", "C:\Users\user\Desktop\test.txt")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
What I can do?
If you are getting an error setting the TLS version, you may want to check which protocols are available:
[Net.SecurityProtocolType]::GetValues( 'Net.SecurityProtocolType' )
However, I don't know how the protocol availability will be affected by using such an old version. Moreover, I don't know how specific protocol settings on a given system affect the availability of protocols either at large or as returned by the above command.
In fact, I would point out the error itself only reflects SSL3 & Tls. On my system when I enter an invalid enumerator the error reports Ssl3,Tls,Tls11,Tls12,Tls13 as choices. While my system is configured to disable everything below Tls12 and has no settings defined for Tls13.
The best assumption I can make is .Net 2.0 which is used with PowerShell 2.0 cannot use Tls12 as it's not present in the enumerators and based on comparison with my system the enums aren't affected by explicit enabling/disabling of protocols.
In any case, I think you have to clear up the first error before you worry about the second. The second error may well be due to the TLS incompatibility. The easiest way to do this would be to upgrade PowerShell (along with the required .Net version). PowerShell 2.0 can coexist with Windows PowerShell 5.1 though you may have to launch with the -Version 2.0 parameter. Also, make sure the engine is installed as a Windows feature. DISCLAIMER: verify all that on your own.
I know the Windows PowerShell 2.0 Engine (PowerShell-V2) was available as a feature at least as late as Windows 2012 R2.
I would also point out that PowerShell 7.x (aka PowerShell Core) can be installed side by side with Windows PowerShell. Potentially this could sidestep the aforementioned complications, allowing you to do run the task at hand...

How to connect Powershell script to an already opened document?

I have a Powershell script that performs some modifications with a MSWord document. In the beginning of the script PS opens the document:
$word = New-Object -ComObject Word.Application
$desktop_path = [Environment]::GetFolderPath("Desktop")
$doc = $word.Documents.Open("$desktop_path" + "blabla.docx")
But as the requirements changed, I now need to run this PS script within an already opened document. Is there any options to force PowerShell find an opened document (by the name for example) and "connect" to it?
FYI: The sequense I want to obtain is: I open the file, launch some macros, call from VBA my PSScript (and here I need PS to be able to "fetch" an opened doc), launch other macros.
Thank you a lot in advance!
This should the same as for Excel:
$word = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Application')
Note the same-user limitation. I would recommend doing the whole thing programmatically via PowerShell though, as suggested by Guenther.
If word is not running, is running under a different user, or is running as admin (and PowerShell is not running as admin) you will get an error:
Exception calling "GetActiveObject" with "1" argument(s): "Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))"
At line:1 char:1
+ $word = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Appl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : COMException
As advised, check that PowerShell and Word are running under the same user. You can so this by going to Task Manager > Details, and checking the user name column for WINWORD.EXE and powershell.exe
To get a specific document based on name:
$doc = $word.Documents | Where-Object {$_.Name -eq "Document2"}
You can check how many documents are open by looking at the count:
$word.Documents.Count

Windows RT Powershell (PermissionDenied) on New-Object

I am trying to instantiate an object in Powershell for Windows RT, but keep getting the following error.
PS > $foo = New-Object System.Security.Cryptography.SHA1Managed
New-Object : Cannot create type. Only core types are supported in this language mode.
At line:1 char:8
+ $foo = New-Object System.Security.Cryptography.SHA1Managed
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [New-Object], PSNotSupportedException
+ FullyQualifiedErrorId : CannotCreateTypeConstrainedLanguage,Microsoft.PowerShell.Commands.NewObjectCommand
I just spent the last thirty minutes engaged in some pretty heavy Google-fu and was unable to find anything even close to a similar problem, let alone an answer. My hope is that I just need to configure something; my fear is that Windows RT ships with a crippled version of Powershell.
Does anyone know which case it is?
Yup, Windows RT ships with a locked down version of PowerShell - it operates in ConstrainedLanguageMode which prevents most interaction (prop setters/method calls) with .NET. It also has a limited command set IIRC.