Saturday, April 15, 2017

PowerShell Function to Determine the Hyper-V Host for a VM

PowerShell Function to Determine the Hyper-V Host for a VM

http://ift.tt/2nPrKev

This week, I thought I would share a PowerShell function that I wrote to determine what Hyper-V host server a VM (virtual machine) resides on. In this scenario, you have no idea which Hyper-V host a VM resides on. First off, let me say that this function is written a bit unorthodox. Typically you’ll see functions written where each item in the ComputerName array is iterated through one at a time. Since this function uses the PowerShell remoting Invoke-Command cmdlet, it’s able to perform the task in parallel so why would anyone want to constrain it to only checking one computer at a time? Most commonly, this is done for error handling to determine if a computer is unreachable, if the credentials are invalid, and if the command generates an error such as the registry key not existing. I started out first by using the built-in Error variable, clearing it and then iterating through it if any errors occurred. I decided that wasn’t necessarily a good idea since something else could potentially pollute the built-in variable so I decided to specify my own variable by using the ErrorVariable parameter.  The function uses the ErrorAction parameter with the SilentlyContinue value. Using that particular option silences the interactive errors but still populates the variable that’s specified with ErrorVariable so I’m able to iterate through the errors and display warnings for systems whose results weren’t returned due to some sort of error. I thought this solution was unique and I’m interested in knowing what you think about it. The function shown in this blog article can be downloaded from my PowerShell repository on GitHub. ยต

Powershell

Powershell

via Mike F Robbins http://mikefrobbins.com

March 30, 2017 at 12:50AM

No comments:

Post a Comment