Importing class module not working as expected

I have created the following class that when imported connects to a vCenter server and you can run PowerCLI commands against vSphere:

class vCenterServer {
     
        [string] $vcenter_server
        [string] $vcenter_user

        vCenterServer([String] $NewvCenter, [String] $NewUser) {
        
        $this.vcenter_server = $NewvCenter;
        $this.vcenter_user = $NewUser;
        }

        [void] connect() {

                try {
                    
                    $pwdSec = Get-Content C:\vmware_password.txt | ConvertTo-SecureString
                    $bPswd  = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwdSec)
                    $pswd   = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bPswd)
                    
                    connect-viserver $this.vcenter_server -protocol https -user $this.vcenter_user -password $pswd

                }
                catch {
                    
                    Write-Warning -Message "Could not connect to vc"
                
                }

        }

        [void] disconnect() {

        disconnect-viserver $this.vcenter_server -confirm:$false

        }


}

Saved as a .psm1 module I can call this class with the “using” command from the command line and use is just fine - for example:

using module vi-connect

$vcenter = [vCenterServer]::new('192.168.0.1', 'administrator@vsphere.local');

$vcenter.connect()

…however putting these same commands in to a script does not seem to work:

C:\Users\me\Desktop> .\class_test.ps1
WARNING: Could not connect to vc

Any ideas why this is not working in a script but does from the commandline?

You’re throwing out all information about the error that took place, so it’s hard to say. Try adding a “throw” statement to the end of your catch block, so you can examine what happened.

Interesting… I added:

catch {
                    $ErrorMessage = $_.Exception.Message
                    Write-Warning -Message $ErrorMessage
}

And now I have no errors and the test script seems to work as expected… ¯_(ツ)_/¯