Importing class module not working as expected

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of TyMac711 TyMac711 2 months ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #48203
    Profile photo of TyMac711
    TyMac711
    Participant

    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', [email protected]');
    
    $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?

    • This topic was modified 2 months ago by Profile photo of TyMac711 TyMac711. Reason: spelling
    #48208
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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
    Profile photo of TyMac711
    TyMac711
    Participant

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

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.