Saturday, July 22, 2017

How to Access ESXCLI with PowerCLI


If you have worked with vSphere, chances are you have had to perform some tasks on an ESXi host using ESXCLI. This command line interface created by VMware enables you to perform such tasks as installing software, configuring NIC adapters or seting firewall rules on ESXi. Since ESXi runs only Linux, using ESXCLI can be a bit daunting for Windows admins who don’t have much experience with Linux. Luckily, if you know PowerShell, you can use PowerCLI as a door into ESXCLI.

Connecting to an ESXi host


First, we need to connect to either a vCenter server or ESXi host. We can do this with the Connect-VIServer cmdlet. Keep in mind you can also connect to your vCenter server as well.

Connect-VIServer -Server devhost -Credential (Get-Credential)

Exposing ESX CLI


Now that we are connecting to our ESXi host "Devhost" we can use the Get-EsxCli cmdlet in PowerCLI to expose the ESXCLI functionality by placing it into a variable.

$DevHost = Get-EsxCli -VMHost devhost -V2
Notice I used the –V2 parameter. This means we are using version 2 of this cmdlet as version 1 is deprecated and compatibility is not guaranteed.
Now if we just run the output of $DevHost we see the "elements" we have to work with for this ESXi host.
Read more on Toms's IT Pro

Tuesday, June 20, 2017

Windows 10 in-place upgrade with PowerShell and MDT



In this article, I will demonstrate how to use Microsoft Deployment Toolkit (MDT) and PowerShell to create a reusable in-place upgrade process for domain-joined computers. This is a completely automated process. Thus, no end-user interaction is necessary, and it can take place on any remote computer. Although I have not tested it specifically, theoretically this function should be able to upgrade hundreds of workstations simultaneously with the proper computing in place.

While adoption of Windows 10 for businesses has been growing, many workstations still run Windows 7 or Windows 8. For mass in-place upgrades, System Center Configuration Manager (SCCM) is the most widely used option as it allows administrators to push out the upgrade easily. For organizations that do not use SCCM, such as small to medium-sized businesses, there are other viable options, notably using MDT along with PowerShell.

Please note this solution will not be a fit for every organization. It requires the use of the Remote Desktop Protocol (RDP) on each machine to launch the upgrade process, and it is widely known that RDP is not entirely secure. The need for using RDP is due to the MDT upgrade process requiring a user logged on to the computer to launch the litetouch.vbs file. With that said, there are ways to reduce the security hole by using public key infrastructure (PKI) and enabling RDP only during the upgrade process. I also recommend changing the password on the account connecting via RDP immediately after the upgrade is complete.

Read more at 4Sysops.com

Wednesday, June 7, 2017

A safer way to patch ESXi using PowerCLI and VUM

Patching vSphere is fairly straightforward using vSphere Update Manager. You can let vCenter/VUM automate the patching of an entire datacenter or cluster if you want. Many VMware professionals prefer to have more control over how their clusters get patched, and with good reason. Yes, vCenter is capable of figuring out how many hosts can run your cluster via DRS so you can patch multiple hosts at once, but that is a bit scary if you ask me and unless you have a massive cluster, it is not worth the time savings in my opinion. I prefer to patch each host one by one and do some testing of vMotioning VM's for each host post installation to ensure the host is functioning correctly.

So I created a little function to do just that, Install-VUMPatch. You can grab it from my Github repo below. I included a good amount of error checking so that hopefully if anything goes wrong with a patch installation, the function stops and asks the user to halt or continue.


#Requires -Modules VMware.VimAutomation.Core
#Requires -Modules VMware.VumAutomation

function Install-VUMPatch
{
    [CmdletBinding()]
    param
    (
    [Parameter(Mandatory=$true)]
    [string]$VCenter,

    [Parameter(Mandatory=$true)]
    [pscredential]$Credential,

    [Parameter(Mandatory=$true)]
    [string]$ClusterName,

    [Parameter(Mandatory=$false)]
    [string]$BaselineName = 'Critical Host Patches (Predefined)',

    [Parameter(Mandatory=$true)]
    [string]$VM
    )
    begin 
    {
        ##Try connecting to vcenter
        try
        {
            Connect-VIServer $VCenter -Credential $Credential -ErrorAction Stop
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            Write-Error $ErrorMessage 
            break
        }
    }
    process 
    {
        Try 
        {
            # Put baseline into variable and validate existence for later use
            $Baseline = Get-Baseline -Name $BaselineName -ErrorAction stop
            # Attach baseline to all hosts in cluster
            Attach-Baseline -Entity $ClusterName -Baseline $Baseline -ErrorAction stop
            # Test compliance against all hosts in cluster
            Test-Compliance -Entity $ClusterName -UpdateType HostPatch -Verbose -ErrorAction stop
            # Build array of noncompliant hosts
            $VMHosts = (Get-Compliance -Entity $ClusterName -Baseline $Baseline -ComplianceStatus NotCompliant -ErrorAction Stop).Entity.Name
            #Copy patches to noncompliant hosts
            Copy-Patch -Entity $VMhosts -Confirm:$false -ErrorAction stop
        }
        Catch 
        {
            $ErrorMessage = $_.Exception.Message
            Write-Error $ErrorMessage 
            Write-Output 'Error getting $Vmhosts variable'
            break
        }
        # For each noncompliant host install patches
        foreach ($VMhost in $VMHosts)
        {
            Write-Output "Patching $VMHost"
            try 
            {   
                # Put VMHost in maintenance mode
                Set-VMHost $VMhost -State Maintenance -Confirm:$false -ErrorAction Inquire | Select-Object Name,State | Format-Table -AutoSize
                # Remediate VMHost
                $UpdateTask = Update-Entity -Baseline $baseline -Entity $vmhost -RunAsync -Confirm:$false -ErrorAction Stop
                Start-Sleep -Seconds 05
                # Wait for patch task to complete
                while ($UpdateTask.PercentComplete -ne 100)
                {   
                    Write-Progress -Activity "Waiting for $VMhost to finish patch installation" -PercentComplete $UpdateTask.PercentComplete 
                    Start-Sleep -seconds 10
                    $UpdateTask = Get-Task -id $UpdateTask.id
                }
                # Check to see if remediation was sucessful
                if ($UpdateTask.State -ne 'Success')
                {
                    Write-Warning "Patch for $VMHost was not successful"
                    Read-Host 'Press enter to continue to next host or CTL+C to exit script'
                    Continue
                }
                # Check to see if host is now in compliance
                $CurrentCompliance = Get-Compliance -Entity $VMHost -Baseline $Baseline -ErrorAction Stop
                if  ($CurrentCompliance.Status -ne 'Compliant')
                {
                    Write-Warning "$VMHost is not compliant"
                    Read-Host 'Press enter to continue to next host or CTL+C to exit script'
                    Continue
                }
                # Set VMHost out of maintenance mode 
                Set-VMHost $vmhost -State Connected -Confirm:$false -ErrorAction Inquire | Select-Object Name,State | Format-Table -AutoSize
                # VMotion VM to VMHost and sleep for 3 seconds
                Move-VM -VM $VM -Destination $VMhost -Confirm:$false -ErrorAction Stop | Out-Null
                Start-Sleep -seconds 3
                # Test network connectivity to VM to ensure VMHost is operating correctly
                Test-Connection $VM -Count 4 -Quiet -ErrorAction Stop | Out-Null
                Write-Output "$VMHost patch successful."
            }
            catch 
            {
                $ErrorMessage = $_.Exception.Message
                Write-Warning $ErrorMessage 
                # Comment out the Read-Host if you do not want the script to prompt after an error. 
                Read-Host -Prompt 'Press enter to continue to next VMHost or CTRL + C to exit' 
                Continue
            }
        }
    }
    end 
    {
        Disconnect-ViServer -Confirm:$False -Force
        Write-Output  'Script completed'
    }
}

Monday, June 5, 2017

Capture network traces with the PowerShell module NetEventPacketCapture



Every network admin will at some point need to capture and view network events to help troubleshoot network issues. The PowerShell module NetEventPacketCapture is an interesting option to capture network traces

IT professionals have many tools that can enable the capturing and viewing of network traffic. Tools such as Wireshark and Netmon have been staples for performing network traces. Starting with Windows 7/2008 the netsh trace command became available to allow capturing traces via the command line.

The NetEventPacketCapture module


One tool I have recently started using is the PowerShell NetEventPacketCapture module to capture and show trace events. Microsoft released the module with Windows 8.1/2012 R2, so although it is a few years old, it is not a widely used tool. One of the main reasons why using this module is appealing to me is that you can do many of the tasks within PowerShell without having to use other tools.

In order to create a trace log (.etl file), you must use four cmdlets from the NetEventPacketCapture module. In addition, you need a tool to view the trace file. This would be the bare minimum process for capturing a network event trace:

  • Use New-NetEventSession to create a trace session. For remote traces you can use the ‑CimSession
  • Add-NetEventProvider to add an event-tracing provider to the session you created. For instance the provider "Microsoft-Windows-TCPIP" would trace TCP/IP events.
  • Start-NetEventSession will begin logging live events to the .etl file.
  • Stop-NetEventSession will end the trace session.
  • Finally, to view the .etl file, you can use a number of tools. In this article, I will use the Get-WinEvent cmdlet in PowerShell.

Read more on 4Sysops.com

Sunday, May 21, 2017

Using the Windows Defender PowerShell cmdlets

There are several ways to manage and configure Windows Defender, such as via the System Center Configuration Manager (SCCM), Desired State Configuration (DSC), Intune, and Group Policy. The Defender PowerShell module is another tool you can use. In this article, I will provide an introduction to the Defender module and examples of using its commands.

With the release of the Windows 10 Anniversary Update, Microsoft has improved their antivirus (AV) solution by adding features, including the ability to perform offline scans, cloud integration, and enhanced notifications as noted here. One advantage of Windows Defender over third-party AV products is Defender's built-in PowerShell support.

Running Get-Command -Module Defender shows the cmdlets you can use to work with Defender. Essentially, you can manage preferences, threats, definitions, scans, and get the current status of Windows Defender.



Read more on 4Sysops.com

Thursday, May 18, 2017

What version of SMB are my clients connecting to my Windows server with?

In light of the recent WannaCry attack, this simple PowerShell one liner will give you some insight into what SMB version your clients are connect to your Windows servers with. This works with any server that is running 2012 and up. This gives the current SMB connections for all 2012 servers in your Active Directory domain.




Wednesday, May 17, 2017

The best training experience I ever had

First off, before I tell my story I will admit that I am very lucky and in more than one way. The story I will tell is not the norm, it is an exception.

I am fortunate enough to work at a phenomenal organization. It is an organization that treats their employees VERY well. The pay is great, the benefits are excellent, and the atmosphere is beautiful. Each year we are given an opportunity to take training in a particular area, online or in-person and with all expenses paid. As an IT professional I have attended many classroom trainings. Some past trainings have been in VMware, Red Hat, Netapp, PHP, Sharepoint among others. Some have been good, others have been not so good.

For those who have attended training, you know how it goes. They are usually geared towards certifications, which means they try to cram as much material down your throat as they can and at breakneck pace. By the third day, your brain is wiped out and you start to spend a lot of time checking work emails and not engaging in the classroom.

Last Fall I decided I wanted to take a class in PowerShell DSC, in particular the class DevOps Management Fundamentals using Desired State Configuration (DSC), with the instructor Jason Helmick. There were a few reasons for this choice. First, I have wanted to start using DSC for a while, but just haven't had to the time to sit down and learn it. I use PowerShell a lot, so I knew I would be able to pick it up fairly easily. Second, the training is not geared towards a certification. I hoped this meant there would be time to dive a little deeper into DSC and PowerShell (I was right). Third, I have used Puppet and Ansible, but I work primarily in Windows. They both support Windows but I would rather use a Windows-based config management solution. Fourth, the instructor was Jason Helmick, who I consider a "higher-up" in the PowerShell community. I knew I would be getting expert training. I had actually seen him teach a session at Ignite in Chicago a few years back.

As I arrived in Phoenix on day one of the training, I walked in and met Jason. For anyone who has met Jason before you would know he is extremely down to earth, smart, easy to talk to, and fun. Having seen him at Ignite I felt really lucky to have a chance to learn for him for a week. As I sat down I asked him how many other students would be attending. He said "just one". Now for an IT training to have only two attendees is not only rare, it's unheard of. Most trainings would get cancelled with only two attendees, but since it was a fairly new course they decided to run it. 

As we started getting into learning DSC, I soon learned this was not just another training, it was a once in a lifetime experience to learn from someone who knows a lot more than I am. Being there were only two students, it was easy to ask questions and get help on the labs. Not only that, but Jason was so open to sharing his knowledge that discussions about DSC turned into discussions about using PowerShell as well, which is just about my favorite topic in the world. I learned more in depth PowerShell that week than I have in the last year, because I had a great instructor that I could easily ask questions to without feeling like I was wasting the time of other students. It was awesome.

As the week ended, I felt comfortable using DSC and I was excited to go back home and start implementing it. Before I left though, I wanted to pick Jason's brain about one more topic, technical writing. I had long been interested in starting a blog and trying to establish myself as a technical author and here was a guy who is already a respected author at Pluralsight which is the best IT training site in my opinion. Jason was really supportive of my ambition to become an author, and gave me a few great nuggets of advice to help me get started in the field.

As I returned home I immediately starting working on this blog and reached out to a few sites to propose some ideas for articles. I was fortunate enough to be given the chance to write for 4sysops and Tom's IT Pro recently, which has been an awesome experience and I owe it all to Jason. I would not have tried writing without some inspiration from a great instructor who I was fortunate enough to have direct access to for a week.

In closing, I know I am fortunate for this training experience, but I guess the moral of the story is that if you have access to learn from someone who knows more than you do, do not waste that opportunity. Ask questions, learn, most professionals will be more than willing to share, especially in the PowerShell community. This is why PSHSummit is such a popular conference.

How to Access ESXCLI with PowerCLI

If you have worked with vSphere, chances are you have had to perform some tasks on an ESXi host using ESXCLI. This command line interface...