A very short post simply to expose a cool trick that will most likley help all of us out when we are doing PowerShell remoting and answer the following question: How to run a local powershell function remotley ?
I stumbled on this topic because I wrote this function locally, and I developped it because I was logic for me that I would only be able to work locally.
Eventually I ended up needing to get that same information from remote machines, but I did not want to add any “computerName” parameter to my function. The idea was to keep it as simply as possible.
My function was a function that retrieves the software updates that are currently installed on the machine. It is based on a ComObject, which doesn’t have native remoting capabilities.
The function is named “Get-WindowsUpdates” (the content of this function is yet not that important right now since this will work for any function. But if you are curious can get it right here –> https://www.powershelldistrict.com/get-windowsupdates/). In a report script (which I will blog about shortly too ;)) I actually needed to get this information as well. I then asked my self How to run a a local powershell function remotley ?
How to run a local powershell function remotley ?
The answer is Invoke-Command in combination with the function: ps drive. See my example below
1
2
3
4
5
|
#Asking the credentials.
$Creds = Get-Credential
#Getting the updates using the Function: drive
$InstalledUpdates = Invoke-Command -ScriptBlock ${function:Get-WindowsUpdates} -ComputerName “Server01” -Credential $creds -ErrorAction stop
|
Voila, pretty simple, but this will defenitly save you some time and efforts when remoting is needed.
Stéphane
Leave A Comment