Upload and run an On Premises PowerShell script from Microsoft Flow

A few months ago I went across a blog post from a Flow team member illustrating how to remotely lock your personal computer from a Flow. I liked it but now I would like to show you how to make it more generic : I want to be able to uplaod a Powershell script (or any other script) from a Flow Button and to run it remotely.

In his post I will illustrate how to upload a PowerShell script (or anything else) and how to run it from a Flow.

When I run my flow from my workstation, I get this :

flowpowershell1

Then I can upload a file containg script code :

flowpowershell2

When I click on Run Flow

flowpowershell3

…and the code run on premises in my data center

flowpowershell5

and of course if the script is  . rundll32.exe user32.dll,LockWorkStation   then can also remotely lock your computer 😉

How does that work ?

First you need to install and configure the data management gateway on your on premises machine; you need to configure it in Microsoft Flow as described here.

Next create a folder where the script will be upload and executed; in my case I created a folder “C:\watchedByFlow”

Next you need to prepare a kind of powershell proxy running on your machine :

$watcher = New-Object System.IO.FileSystemWatcher

$watcher.Path = “C:\watchedByFlow”

$watcher.Filter = “*.*”

$watcher.IncludeSubdirectories = $true

$watcher.EnableRaisingEvents = $true

$actionCreated = {

write-host ‘file created’

$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
write-host ‘running code file $path sent via Flow’
Invoke-Expression $path
Remove-Item $path

}

Register-ObjectEvent $watcher “Created” -Action $actionCreated

while ($true) {sleep 5}

Next run this Powershell script

 

flowpowershell6

Create a Flow starting with a Button and allowing a file upload :

flowpowershell7

Add a File System Create File action (this will require a File System connection)

flowpowershell8

…and voilà it should work ! Happy ?

An alternative would be to use Azure automation from Flow to run On premises script.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s