Tunnel a PowerShell script to a remote machine and invoke via WMI

In my blog post „Invoke a remote command without WinRM, psexec or similar – Access administrative shares even if they have been removed“ I demonstrated how to use WMI to execute a command on a remote computer. The task was pretty simplistic as I only had to create a share. However as this was working pretty well and also out of curiosity I wanted to know if I can use the same process for more complex scenarios.

So I wanted to know, if I can also invoke a full PowerShell script via this way, while the script itself is not available on the remote computer.

Let’s start with a small script. I’m using a ScriptBlock for demonstration purposes, but reading a script file is working the exact same way. To keep it simple, I’m just reading the folders on the System drive and export them to csv file in the temp folder:

Nothing fancy.

Now a quick look on how to execute a PowerShell script. Looking at the command line options for PowerShell.exe, most of you probably know the File parameter, which can be used to execute a script file. In the current scenario this won’t really help, as the script isn’t available on the remote computer. Another option would be the Command parameter, that takes either a string or a ScriptBlock. However, as our ScriptBlock/Script can contain special characters, line breaks, quotation marks etc, it might get complicated to escape them properly. A relatively unknown parameter is the EncodedCommand, which takes a Base64 encoded string.

So let’s get a Base64 encoded string from the ScriptBlock using the following snippet:

Prepare the PowerShell.exe command:

And finally use the snippet from the mentioned blog post to execute this command on a remote computer:

Execute and check on the remote computer if it created the file in your temp folder.

Tadaaaaa. 😉

A few things to note:

  • The script should run completely unattended.
  • Make sure it’s handling errors and exceptions properly.
  • You won’t get any direct feedback from the script.
  • You will not be able to interact with any network location.
  • Variable substitution can be challenging.




Das könnte Dich auch interessieren...

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.