The other day I shared a PowerShell function to query the registry on remote computers to find installed versions of PowerShell. The function leveraged PowerShell remoting with the flexibility of using a computer name with an optional credential or existing PSSessions. The more I thought about it, the more I realized that the structure could be re-used for any command that I wanted to run on a remote computer. I think this is a terrific way to use PowerShell. With a little re-work, I came up with what I'm calling a remote function framework.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
The majority of the function's parameters are based on what you would use to create a PSSession. The function uses the session to run a scriptblock remotely. Because I wanted to support PowerShell 7 which can use SSH for remoting, I wanted to add the necessary parameters like Hostname. Those parameters are only available on PowerShell 7 so I'm defining them as dynamic parameters with their own parameter set. Although, you could just as easily define the parameters in the Param block.
The function creates temporary sessions as needed one at a time.I did this so that I could better handle exceptions. The code also had to account for values being passed by a parameter or from the pipeline. To simplify things, I removed the default value for $Computername and made it mandatory.
To create your own command from my framework, all you really need to do is define the scriptblock, and any optional parameters you might need.
The framework function is on Github.
I've left a number of #TODO comments to guide you on the changes you need to make. As a proof of concept, here is a function that terminates a process on a remote computer.
As you look through the code you can see how I'm handling parameters I need for the remote scriptblock. Including support for -WhatIf. The way I have this written, $PSBoundParameters is getting splatted to New-PSSession, so you need to remove anything you've added that doesn't belong. You can see how I'm doing that in the code.
Within a few minutes I had a fully functioning command.
And it works this way as well.
I'm looking forward to seeing what else I can do with this framework. I'd love to hear how you use it. Enjoy.
I created a json snippet version of the framework function that you can use in VS Code. https://gist.github.com/jdhitsolutions/111ba054133bde290592d7436af30fa5
Again, this function looks really handy and powerful, I’m trying to fully understand it and already have several ideas to re-use it to fetch information on remote host. Thanks !