powershell

type-safe powershell: Unable to find type `[Application]`


I am trying to slowly move towards more type-safe powershell scripts and therefore experimenting with explicitly setting types for all my variables. In the following, I attempt to instantiate a Word.Application object and then quit out of it:

using namespace Microsoft.Office.Interop.Word
using namespace System.Management.Automation

$ErrorActionPreference = [ActionPreference]::"Stop"
[Application]$wordApp = new-object -comobject Word.Application
$wordApp.Quit()

Could anyone explain to me why, upon running this script I get the following error:

InvalidOperation: test.ps1:5 Line | 5 | [Application]$wordApp = new-object -comobject Word.Application | ~~~~~~~~~~~~~ | Unable to find type [Application].

What is the correct way to remediate this?


Solution

  • Could anyone explain to me why, upon running this script I get the following error: [Unable to find type]?

    Therefore:

    # NOTE:
    #  Windows PowerShell only - doesn't work in PowerShell (Core) 7, as of v7.4.x
    using assembly Microsoft.Office.Interop.Word
    using namespace Microsoft.Office.Interop.Word
    using namespace System.Management.Automation
    
    $ErrorActionPreference = [ActionPreference]::Stop
    [Application]$wordApp = New-Object -ComObject Word.Application
    $wordApp.Name # Get and output the .Name property value, for demonstration purposes.
    $wordApp.Quit()
    

    Note: