Executing Powershell commands on remote computers

ps1_1All, today I had a requirement to execute powershell scripts using C# windows application code inside a windows application. That is an easier solution. But it is internally linked to executing the same powershell scripts in remote systems like servers. Because the C# windows application is not allowed to run inside the servers.

Problem:

All the windows systems are not allowed to run remote executions due to obvious security reasons.

Solution:

  • On the computer you want to access remotely (target), open a PowerShell window as Administrator
  • To enable PowerShell Remoting, run the following command
  • Enable-PSRemoting -Force

  • This command starts the WinRM service, sets it to start automatically with your system, and creates a firewall rule that allows incoming connections. The -Force part of the command tells PowerShell to perform these actions without prompting you for each step.
  • If you are not connected to a single domain, then you need to run the above command in the Source system also (from where you want to connect to target)
  • On both computers, configure the TrustedHosts setting so the computers will trust each other. If you’re doing this on a trusted home network, you can use this command to allow any computer to connect:
  • Set-Item wsman:\localhost\client\trustedhosts *

  • In the above command you can use IP addresses with comma separation instead of *
  • On both computers, restart the WinRM service so your new settings will take effect:
  • Restart-Service WinRM

  • You can validate the connection using below command
  • Test-WsMan COMPUTERNAME

ps1_remote

  • Now run the below to just get the list of contents inside C drive of target system
  • Invoke-Command -ComputerName COMPUTERNAME -ScriptBlock { Get-ChildItem C:\ } -credential COMPUTERNAME\USERNAME

  • You will be prompted credentials box & then the directory listing will be shown in the Source PS1 window.

ps1_remote_2

Thanks to below link:

http://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/

 If at all there is a need to execute a PS1 file instead of having commands inside the SCRIPT BLOCK, then use below

Picking from Local server path:

Invoke-Command -ComputerName COMPUTERNAME -FilePath “C:\Services.ps1” -credential COMPUTERNAME\USERNAME

Picking from Remote server path:

Invoke-Command -ComputerName COMPUTERNAME -ScriptBlock { C:\Services.ps1 } -credential COMPUTERNAME\USERNAME

Skipping the Password Windows Prompt:

$secureString = 'pass' | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object pscredential('USERNAME', $secureString)

Invoke-Command -ComputerName COMPUTER -ScriptBlock { COMMAND } 
-Credential $credential

Leave a comment