PowerCLI

 View Only
Expand all | Collapse all

Managing screen output from PowerCLI cmdlets?

  • 1.  Managing screen output from PowerCLI cmdlets?

    Posted Jan 29, 2013 11:04 PM

    The output I get shown from running cmdlets in my script varies, sometimes there's quite a lot of info written to screen other times there's none, but I can't figure out why. What do I do to manage the output?


    For example, my script does

    Start-VM -VM $cbrvm -Confirm:$false

    Which currently results in >30 lines of data being displayed:

    PowerState              : PoweredOn
    Version                 : v7
    Description             : Provides services
    Notes                   : Provides services
    Guest                   : MY-ESX-VPX:
    NumCpu                  : 2
    MemoryMB                : 1024
    HardDisks               : {Hard disk 1}

    <etc.>

    Yesterday this same script was NOT putting the data on the screen. I've made some changes since then but none to the Start-VM command and don't know what makes the difference.

    Thanks

    Alan



  • 2.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Jan 30, 2013 08:45 AM

    Would you mind attaching you're script ?

    That might help finding a possible cause.



  • 3.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Jan 30, 2013 04:15 PM

    I'd rather not use Out-Null, because it might hide something useful. Here's the full script, maybe it shows the the reason for all the output?  I've attached the output as file "screenoutput.txt".

    May I add a second question, now I'm revealing my poor scripting (all advice for improvement gratefully accepted!) ?  The script tries to do Disconnect-VIServer at the end, but somehow I can't get the -Server parameter right; that is, Disconnect-VIServer doesn't accept the $Server object returned by $Server = Connect-VIserver -Server 10.1.1.27 <etc>

    I hope it's OK to put the script inline - if attachments are preferred please let me know (obviously if it was bigger, then attachment would be better).

    Thanks

    Alan

    #  $Id: //depot/branch/alansi/build/bin/MakeVpx.ps1#5 $
    #  $DateTime: 2013/01/29 17:07:38 $
    #  $Change: 317348 $


    param (
        [string]$version = "7.0.0.1", # the real versioning is set by kickstart script, this is just for filename
        [string]$tgtdir = $env:USERPROFILE + "\Desktop\"
    )

    [string]$Scriptrev ='$Revision: #5 $'


    [string]$Vmname = "CBR-ESX-VPX"
    [string]$Outputdir = $tgtdir   # TODO 'env' probably NOT suitable destination using ssh

    # connection params for ESXi host
    [string]$ESXHOST   = "10.1.1.27"
    [string]$username = "root"
    [string]$password = ""

    ###########################################################################

    # show what's running
    $fullPathIncFileName = $MyInvocation.MyCommand.Definition
    #$currentScriptName = $MyInvocation.MyCommand.Name
    #$currentExecutingPath = $fullPathIncFileName.Replace($currentScriptName, "")
    $msg = "{0}({1}) creating {2} version {3} in {4} on host {5}" -f $fullPathIncFileName, $Scriptrev, $Vmname, $VERSION, $Outputdir, $ESXHOST
    write-host $msg
    Get-Date


    # load the VMware module
    [string]$VimAutoCore = "VMware.VimAutomation.Core"
    if ( (Get-PSSnapin -Name $VimAutoCore -ErrorAction SilentlyContinue) -eq $null )
    {
        Write-Host "loading $VimAutoCore powershell module"
        Add-PsSnapin $VimAutoCore
    }


    ###########################################################################
    #
    # connect to ESX host

    $protocol = "https"
    $port=443
    $Server=''
    $myserver=''

    Try {
        $myserver = get-vmhost -Server $ESXHOST -State connected -erroraction "Stop"
        #if (get-vmhost -Server $ESXHOST -State connected -erroraction "Stop") {
        if ($myserver) {
            Write-host "already connected to $myserver"
            $Server = $myserver
            $connected=$True
        }
    }
    Catch {
        Try {
            Write-Host "Connecting to ESX host server $ESXHOST"
            $Server = Connect-VIserver -Server $ESXHOST -user $username -password $password -errorAction "Stop"
            $connected=$True
            Write-Host "Connected OK to server $Server"
        }
        Catch {
            $msg="Failed to connect to server {0} on {1} as user {2}" -f $ESXHOST,$protocol,$username
            #Write-Warning $msg
            #Write-Warning $error[0].Exception.Message
            Write-Error $msg
            Write-Error $error[0].Exception.Message
            Exit 1
        }
    }
    if ($connected) {
        #Write-Host "Connected to VM host $ESXHOST"
        Write-Host "Connected to VM host $Server"
    }


    ###########################################################################
    #
    # create the CBR VM

    # remove any pre-existing CBR VM
    if(Get-VM $Vmname -ErrorAction SilentlyContinue){
        Write-Host "Found pre-existing VM '$Vmname' on $Server, will delete it"
        if((Get-VM $Vmname).powerstate -eq "PoweredOn"){
            Write-Host "$Vmname is powered on, powering it off"
            Shutdown-VMGuest -VM (Get-VM $Vmname) -Confirm:$false
        }
        Remove-VM $Vmname -DeletePermanently  -Confirm:$false
        if( ( Get-VM $Vmname -ErrorAction SilentlyContinue) -eq $null) {
            Write-Host "Removed $Vmname"
        }
    } else {
        Write-Host "No pre-existing VM '$Vmname' found"
    }

    # make the new VM
    # no simple way to define 1 CPU with 2 cores-per-socket, so give 2 CPUs for now
    Try {
        $cbrvm = New-VM -Name $Vmname -Version v7 `
            -NumCpu 2 -MemoryMB 1024 -DiskMb 61440 `
            -DiskStorageFormat Thick `
            -GuestId rhel5_64Guest `
            -Notes "Provides services" `
            -Confirm:$false `
            -ErrorAction Stop
    }   
    Catch {
        $msg="Failed to create New-VM named {0}" -f $Vmname
    #    Write-Warning $msg
    #    Write-Warning $error[0].Exception.Message
        Write-Error $msg
        Write-Error $error[0].Exception.Message
        Exit 1
    }       
           
    Write-Host "New vm $Vmname created, ready for install"


    # use modified CentOS ISO for boot from CD ======================================
    #
    # There's no way to enter a kickstart command
    # so the CentOS boot disk is modified to include the command to load our kickstart script
    # The ISO defines
    #   name and location of kickstart script
    #   temporary IP address and network info for the new VM
    # The kickstart script is updated with version number etc before use


    "WARNING: Using modified CentOS boot cd ISO with *HARDCODED* IP addresses and Kickstart script name"
    $cbrcd = New-CDDrive -VM $cbrvm -ISOPath "[datastore1] ISO/CentosForESX.iso" -StartConnected


    #" " # pause here for me to open the console in client
    #$a = read-host "    press any key to START $Vmname"


    # boot the VM, CBR installs automagically, configured by kickstart script ======================================
    Write-Host "Installing Branch Repeater in the new VM"
    Start-VM -VM $cbrvm -Confirm:$false

    <#
    # show what we've got
    $nic = Get-NetworkAdapter -VM $cbrvm
    "vm is $cbrvm"
    "cd is $cbrcd"
    "nic is $nic"
    #>

    # TODO wait for semaphore then shutdown  ... for now sleeping instead of semaphore
    Write-Host "Please wait"
    $SleepSecs = 300 # five mins probably NOT long enough
    #$SleepSecs = 600 # longer wait
    Start-Sleep  $SleepSecs
    # following code assumes the CBR VM was installed OK and is ready to export


    # shutdown the VM ======================================
    #" "
    #$a = read-host "    press any key to STOP $Vmname"
    Stop-VM -VM $cbrvm -Confirm:$false

    #Configure the CBR VPX - set NICs, CPUs, CD ======================================

    Remove-CDDrive  -CD $cbrcd  -Confirm:$false # VM must be in state PoweredOff

    $nic = Get-NetworkAdapter -VM $cbrvm
    Remove-NetworkAdapter -NetworkAdapter $nic -Confirm:$false # VM must be in state PoweredOff
    Get-VM $cbrvm | New-NetworkAdapter  -NetworkName "APA-1" -StartConnected  -Type Vmxnet3
    Get-VM $cbrvm | New-NetworkAdapter  -NetworkName "APA-2" -StartConnected  -Type Vmxnet3

    # for two cores per socket cannot use -NumCPU but *might* be able to use
    #     $spec=New-Object –Type VMware.Vim.VirtualMAchineConfigSpec –Property @{“NumCoresPerSocket” = 1}  (Get-VM –Name Test_VM).ExtensionData.ReconfigVM_Task($spec)


    #export the CBR VPX ======================================
    #

    $ovafilename = $Outputdir + "\" + $Vmname + "-" + $VERSION + ".ova"

    # makes export dir if rqd
    # overwrites (deletes & replaces) an existing file
    #
    $ovftool = "C:\Program Files\VMware\VMware OVF Tool\ovftool.exe"
    if (!(test-path $ovftool))
    {
        write-host -ForegroundColor red "ERROR: Cannot find OVFtool $ovftool"
        # download ovftool here: http://www.vmware.com/support/developer/ovf/
        exit 1
    }

    # TODO modify these to use same naming throughout
    if(!( test-path "$Outputdir" ))
    {
        Try {
           New-Item -itemtype "Directory" "$Outputdir" -force -Confirm:$False
        }
        Catch {
            $msg="Failed to creat output directory {0}" -f $Outputdir
            Write-Warning $msg
            Write-Warning $error[0].Exception.Message
            Exit 1
        }
    }

    if( test-path "$ovafilename" )
    {
        write-host "deleting previous $ovafilename"
        Try {
            Remove-Item "$ovafilename" -force -Confirm:$False -ErrorAction Stop
        }
        Catch {
            $msg = "Failed to delete pre-existing file {0}\{1}" -f $Outputdir,$ovafilename
            Write-Warning $msg
            Write-Warning $error[0].Exception.Message
            Exit 1
        }
    }


    function Export-VM 
    {
        # from http://geekafterfive.com/category/vmware/page/3/
        param
        (
            [parameter(Mandatory=$true,ValueFromPipeline=$true)] $vm,
            [parameter(Mandatory=$true)][String] $destination
        )

        $ovftool = "C:\Program Files\VMware\VMware OVF Tool\ovftool.exe"

            if( test-path "$($destination)$($vm.name).ova" )
            {
                write-host "deleting previous $($destination)$($vm.name).ova"
                Remove-Item "$($destination)$($vm.name).ova" -force -Confirm:$False
            } else {
                write-host "did not see $($destination)\$($vm.name).ova"
            }

            $moref = $vm.ExtensionData.MoRef.Value
            $session=get-view -Id $global:DefaultVIServer.ExtensionData.Client.ServiceContent.SessionManager
            $ticket = $session.AcquireCloneTicket()
            & $ovftool --skipManifestCheck  "--I:sourceSessionTicket=$($ticket)" `
               "vi://$($defaultviserver.name)?moref=vim.VirtualMachine:$($moref)" `
               "$($destination)$($vm.name).ova"
    }

    Export-VM $cbrvm  $Outputdir
    ####################################################

    "  VM export complete"

    " "

    # destroy the VM and delete it from disk ======================================
    #$a = read-host "    press any key to delete $Vmname and disconnect from $ESXHOST"
    Remove-VM $Vmname -DeletePermanently  -Confirm:$false
    "VM $Vmname deleted from ESX host $Server"

    if ( (Disconnect-VIServer -Server $Server -Force -Confirm:$false -ErrorAction SilentlyContinue) -eq $null ) {
        Write-Host "did not disconnect"
    } else {
        Write-Host "Disconnected from $ESXHOST"
    }

    Disconnect-viserver * -force -confirm:$false

    Write-Host "Finished."
    # all done



  • 4.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Jan 30, 2013 05:48 PM

    The Start-VM and Stop-VM cmdlets both return the VirtualMachine object, provided they were successful.

    Not a lot you can do about that I'm afraid.

    But you can control what and where the output goes to.

    The Out-Null cmdlet suppresses the output, it's gone.

    You could also use an Out-File and store the result in a file, instead of displaying it on the screen.

    An alternative is to use the Start-Transcript and Stop-Transcript cmdlets. Instead of directing the output per statemenet, the complete out will be redirected to a file.

    I do find it strange that the output formatter displays all the properties of your objects.

    That looks as if it can't find the .ps1xml files, who define what properties of an object should be displayed.

    Or that the formatter doesn't think the output is directed to the console (hence the Format-List format instead of the Format-Table format)



  • 5.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Nov 13, 2018 01:05 PM

    running powerCLI 5.5

    Do others have this behavior?

    When we do a "Start-VM -VM VNAME -Confirm:$false" ....  we get that long object listing ( in fact some deprecation warnings also )

    However when I do "Start-VM -VM VNAME -Confirm:$false | Out-File filename"  or even redirect like this "Start-VM -VM VNAME -Confirm:$false" > filename

    I get very little output.

    It is ODD that redirected output content is different from powershell screen output.

    I did try all other types of redirect like 6>   5> 4> 3> 2>    but ONLY  "1"  i.e. ">"   makes a difference and it becomes a different output.

    Do others see the same behavior?



  • 6.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Nov 13, 2018 01:09 PM

    On screen/console you "see" all the streams, when writing to a file, you only get the success stream.

    See About Redirection



  • 7.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Nov 14, 2018 01:16 PM

    I appreciative your attempt to explain - but actually all that was stated was the behavior - not the WHY

    As I mentioned I tried "all stream type re-directions" 6> 5> 4> 3> 2> 1> even *>  and NONE redirected to the file

    To further explain that I "think" I know what is going on - and what you are trying to say - is that the "Start-VM" cmdlet  acts a lot like - the Linux login "Password:" prompt

    https://superuser.com/questions/569432/why-can-i-see-password-prompts-through-redirecting-output   where the "Password:" is sent directly by opening the /dev/tty - not stdout

    So it appears that the "Start-VM" cmdlet directly opens the PSHELL "window / console" (like a device) for the output - but if the output is redirected then that "device" no longer exists.

    I am not trying to belabor - was just hoping for absolute understanding

    I have moved on - with [ try (Out-Null) / catch (Write-Host)  ] construct - which this forum was very helpful to suggest.

    But if there are anyone who truly knows the WHY / HOW  the "Start-VM" cmdlet behaves like this - it is much appreciated



  • 8.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Nov 14, 2018 01:33 PM

    Not sure how you are redirecting, but for me this seems to redirect all streams to the file.

    Admittedly I'm using PSv5.1 and PowerCLI 11.0.0, and I don't have an older PowerCLI version laying around.

    $code = {

        $VerbosePreference =  'Continue'

        $DebugPreference = 'Continue'

        Write-Host "Test 1"

        Write-Error "Stream 2"

        Write-Warning "Stream 3"

        Write-Verbose "Stream 4"

        Write-Debug "Stream 5"

        Write-Information "Stream 6"

    }

    & $code *>&1 | Out-File -FilePath .\out.txt



  • 9.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Nov 14, 2018 02:52 PM

    With all respect:

    This thread is not about understanding the various streamed outputs of Powershell.

    It is about the SPECIFIC behavior of "Start-VM"

    Start-VM -VM vmname.held.private.com -Confirm:$false

          yields the humanly view-able output as mentioned at the beginning of this thread - verbose

    Start-VM -VM vmname.held.private.com -Confirm:$false | Out-File filename

           yields a much shorter output into the file

    Start-VM -VM vmname.held.private.com -Confirm:$false > filename

           yields the same much shorter output into the file

    Start-VM -VM vmname.held.private.com -Confirm:$false 6> filename6  5> filename6 4> filename4 3> filename3 2> filename2 > filename

           yields the same much shorter output into the file "filename"  - and all the others are 0 bytes

    I was trying to get a few of the nice things seen in the interactive view - 1) its PowerState and 2) which VMHost it runs in

    Start-VM -VM vmname.held.private.com -Confirm:$false |  findstr "PowerState VMHost" | findstr /v VMHostId

            but because of the shorter output -> PowerState and VMHost is not available

    If anyone knows the internals of "Start-VM"  - that is what I am asking

    Thank you



  • 10.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Nov 14, 2018 04:01 PM

    Perhaps if you could give an example of the differences in output?
    Because I'm seeing exactly the same output in both cases (on screen and to a file), and it doesn't include VMHost..
    In each case I get 4 properties, which is exactly what the .ps1xml file defines.



  • 11.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Nov 14, 2018 08:54 PM

    NO Redirect source code

    No Redirect output

    = = = = = = = =

    With Redirect source code

    With Redirect then listing the “Out-File”

    I have not created a specific .ps1xml file -



  • 12.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Nov 14, 2018 11:32 PM

    The issue is definitely with the output from the snippet with no redirection.
    The normal display options, as defined in the .ps1xml extended data type file for the module, should be applied.

    The .ps1xml file on the other hand seems to be ok, because with the redirection snippet, the expected 4 properties are displayed.


    I would like to see the output from $VM | Get-Member

    And include the 1st line with the TypeName.

    Btw, which PowerCLI version are you using?

    There seem to be some properties in the output that in the current version are not present anymore.



  • 13.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Nov 15, 2018 01:38 PM

    We are running PowerCLI 5.5 in to a ESXi / vCenter 6.5

    Yes we ARE now working to figure out the BEST WAY to upgrade PowerCLI to 10.2 ( or maybe 11.0 but we saw some issues on Google search regarding 11 )

    That will likely change the behavior of Start-VM   Yes our current Start-VM has deprecation warnings (old screen shot)    (which I suppressed- with "...displayDeprecationWarnings $false )

    I dont think the suppression of displaying the deprecation warnings is the issue - its could be the version of PowerCLI 5.5 / vCenter-ESXi 6.5 combination - that has our weird behavior

    Will let you know the behavior after the PowerCLI upgrade..   but now that effects - Production roll out so it takes some internal discussion here - ( I am in a lab right now )

    I cannot thank you enough for your feedback and patience



  • 14.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Nov 15, 2018 01:44 PM

    No problem.
    Let us know what happens after the upgrade.



  • 15.  RE: Managing screen output from PowerCLI cmdlets?

    Posted Jan 30, 2013 09:15 AM

    As Luc says the script would help. There are easy ways to suppres the output by adding "| Out-Null" to the whole command, keep in mind that this is a dirty fix :smileywink:.