Introducing VMware PowerCLI Core (Part 2)

If you would like to read the other parts in this article series please go to:

As I mentioned in my previous article here on VirtualizationAdmin.com, PowerCLI Core was recently developed by VMware Fling Labs as a way of enabling users of Linux, Mac and Docker to use the same PowerShell cmdlets that were previously only available on Windows so sysadmins could have a multi-platform scripting language to let them manage their VMware infrastructure from any operating system without any changes being necessary to their scripts. In this short two-part article we have some help from Luc Dekens, a long time VMware vExpert and Microsoft MVP, who briefly walks us through this exciting new technology. Picking up where we left off in the previous article here’s Luc again…

PowerCLI Core, first encounter

PowerCLI Core is currently published as a Fling. That is VMware’s way of doing Technical Previews of new products and features, that one day will make it into an official and supported product:

Image 

Editor

Before we are running scripts, we will need an editor to, duh, edit our scripts. And preferably one that has features like PowerShell Intellisense, debugging, Git integration, and some more. But more importantly, an editor we can use on this multitude of platforms.

Image
 
And with the Visual Studio Code and the PowerShell Extension, we have such a tool at our disposal. Both are other examples of Microsoft’s new, open nature.

Multi-platform Coding

While we all applaud the variety of platforms that become available to run our PowerShell scripts, this also brings some new challenges. As Alan already mentioned during the interview, we want to write “portable” PowerShell scripts, so we must come up with new ways of doing some of the standard techniques we used on Windows only platforms.

The following is just an initial list of some of these that I encountered while taking my first steps in PowerShell and PowerCLI Core.

Where am I?

When we want to provide scripts that run on multiple platforms, we must come up with a method to determine where our script is running. Is it on a Windows platform, a Linux box or a Mac?

The current PowerShell Core build unfortunately doesn’t provide an easy way yet to find this out. On the PowerShell repo, there are several Issues that refer to this problem. See for example issue #1997.

I have been using the following simple function, name Get-CorePlatform, which returns platform information. Based on the OSFamily property of the returned object, a script can deduce where it is running:


function Get-CorePlatform
{
    [cmdletbinding()]
    param()

 

    $osDetected = $false
    try{

        $os = Get-CimInstance -ClassName Win32_OperatingSystem
        Write-Verbose -Message 'Windows detected'
        $osDetected = $true
        $osFamily = 'Windows'
        $osName = $os.Caption
        $osVersion = $os.Version
        $nodeName = $os.CSName
        $architecture = $os.OSArchitecture

    }
    catch{
        Write-Verbose -Message 'Possibly Linux or Mac'
        $uname = "$(uname)"
        if($uname -match '^Darwin|^Linux'){
            $osDetected = $true
            $osFamily = $uname
            $osName = "$(uname -v)"
            $osVersion = "$(uname -r)"
            $nodeName = "$(uname -n)"
            $architecture = "$(uname -p)"
        }
        # Other
        else
        {
            Write-Warning -Message "Kernel $($uname) not covered"
        }
    }
    [ordered]@{
        OSDetected = $osDetected
        OSFamily = $osFamily
        OS = $osName
        Version = $osVersion
        Hostname = $nodeName
        Architecture = $architecture
    }
}

 

You can use this function in your script to determine where, in which OS, your script is running, and take necessary action.

Scheduling Scripts

One of the strengths of automation, is that you can schedule scripts to run at specific times. A classic example is running the famous vCheck script overnight, and find the resulting report in your mailbox when you come into work the next morning.

The New-ScheduledTask cmdlet is currently not yet available in PowerShell Core. Seen the different scheduling solutions available on all the platforms where you can run your scripts, we need some logic with which we can schedule a script through the local scheduling option.

I created a small function, named New-CoreScheduledTask, that will use crontab in Linux and Mac OS environments, and the schtasks command in a Windows environment. And it uses the Get-CorePlatform function to determine which platform specific solution to pick:

 


function New-CoreScheduledTask
{
    [cmdletbinding()]
    param(
        [datetime]$Start,
        [scriptblock]$Script
    )
    switch -RegEx ((Get-CorePlatform).OSFamily)
    {
        'Windows' {
            $text = @()
            $text += 'schtasks','/Create','/SC Once'
            $text += "/ST $($Start.ToShortTimeString()) /SD $($Start.ToString('dd-MM-yyyy'))"
            $text += "/TN CoreTools-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
            $text += "/TR ""powershell.exe -Command '&{$Script}'"""
                        Invoke-Expression -Command ($text -join ' ')    
    }
        "^Linux|^Darwin"{
           $text = @()
           $text += (crontab -l 2>&1 | where{$_ -notmatch "no crontab"})

 

           $cronLine = "$($Start.Minute) $($Start.Hour) $($Start.Day) $($Start.Month) $([int]$Start.DayOfWeek)"
           $cronline += " $(which powershell) -Command ""&{$($Script)}"""
           $text += $cronLine

           New-CoreCrontab -Command $text
        }
        'Default'{

            Write-Error -Message "Unknown OSFamiliy $($_)"
        }
    }
}

For completeness, the PowerShell Core comes with a crontab module in the demos folder. Targeted at Linux and Mac OS, and way more features than my simple function above.

Module

The functions from this article can be found in my GitHub repository named CoreTools. Feel free to fork and contribute.

What I used

Since we are using Alpha versions, there might be breaking changes in future releases. As a reference, I used the following versions for this article.

  • PowerShell Core: v6.0.0-alpha.13
  • VMware PowerCLI Core: 1.0 build 0
  • Visual Studio Code: 1.8.0
  • PowerShell Language Support for VSC: 0.8.0

Closing Thoughts

The “open” initiatives Microsoft and VMware are taking, signify, in my opinion, the dawn of a new era in IT.

Your “investment” in Windows PowerShell is paying off. The effort you put in learning and using PowerShell, is now paying off on multiple platforms. Reap the benefits!

The “Community” becomes an important and valued player, and as an individual, you can now contribute to all these new initiatives that are popping up. Github should be your new best friend!

If you weren’t convinced before that PowerShell was an indispensable tool for any serious IT Pro, you should be by now. Just think how you will be able to manage and automate all these platforms with just one language!

A brave new world indeed! Happy scripting!

About The Author

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top