Importing class module not working as expected

This topic contains 2 replies, has 2 voices, and was last updated by  TyMac711 1 year, 9 months ago.

  • Author
  • #48203


    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('', 'administrator@vsphere.local');

    ...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?

    • This topic was modified 1 year, 9 months ago by  TyMac711. Reason: spelling
  • #48208

    Dave Wyatt

    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.

    • #48327


      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... ¯\_(ツ)_/¯

You must be logged in to reply to this topic.