PowerShell: How to run a powershell script on a remote machine using WMI

5.6k Views Asked by At

To be specific: I want to run a powershell script on a remote windows server, but I can connect to this server using WMI only.

I used, for example, Get-Wmiobject to get some data like the running processes, but I failed after a lot of searching, to find a way to run a powershell script block on this remote one. One of the commands that I found is Invoke-Command but this one uses the winRM which is not opened to that remote server.

So, it is NOT allowed to run a powershell script on a remote server using WMI? I didn't find a clear and a direct answer for that.

2

There are 2 best solutions below

3
mklement0 On

tl;dr

Consider using psexec as an alternative to PowerShell remoting for executing arbitrary commands.


The list of PowerShell commands that support targeting remote machines without relying on PowerShell remoting is limited (see below); they may all be WMI-based (I'm not sure), and they're focused on retrieving and manipulating remote resources (as WMI is in general) rather than providing the ability to execute arbitrary commands.

Update: Alberto Varga's helpful answer points out that the Win32_Process WMI class's .Create method indeed does allow creation of arbitrary processes; the documentation of PowerShell's Invoke-WmiMethod cmdlet even contains an example.

By contrast, Invoke-Command, which does offer the ability to execute arbitrary commands, does use PowerShell remoting, as you've discovered, which requires the WS-Management protocol, as implemented by Microsoft's WinRM service, among other prerequisites - see Get-Help about_Remote_Requirements.

The most generic of the non-remoting commands listed below is Invoke-WmiMethod, which provides open-ended access to WMI classes and their methods.

Note, however, that Microsoft recommends using the more recent *-Cim* cmdlets such as Invoke-CimMethod in the interest of cross-platform support, and that these CIM-compliant cmdlets again rely on WS-Management (WSMan) standards, as PowerShell remoting does.


List of PowerShell cmdlets that support targeting remote machines via -ComputerName without using PowerShell remoting, as of PSv5.1 (see Get-Help about_Remote_FAQ for background info):

Add-Computer
Clear-EventLog
Get-EventLog
Get-HotFix
Get-Process
Get-Service
Get-WmiObject
Invoke-WmiMethod
Limit-EventLog
New-EventLog
Register-WmiEvent
Remove-Computer
Remove-EventLog
Remove-WmiObject
Rename-Computer
Restart-Computer
Set-Service
Set-WmiInstance
Show-EventLog
Stop-Computer
Test-Connection
Write-EventLog
0
albvar On

This can be easily done. What you want is Win32_Process and method called Create. This allows you to spawn processes on remote machines 2K3 and higher.