powershellwinrmwinrs

How to execute commands using powershell after doing remote login using winrs


I am new to PowerShell scripting. So please pardon me if I am asking a silly question. I have a task to connect to the command prompt of a remote desktop and run a series of commands on the command line.

I am using winrm to access the remote desktop machine. I have written the following code in a test.ps1 file:

powershell.exe -c "winrm set winrm/config/client '@{TrustedHosts=remoteHostServer}'"
powershell.exe -c "winrs /r:remoteHostServer /username:admin /password:xxxxxx cmd.exe"
powershell.exe -c "C:\test\"
powershell.exe -c "java test.java"

When I am executing the above code, I am reaching the following line:

C:\Users\admin>

But then it is not changing the directory to the path "C:\test" and execute the java file. Can anyone say what else should I do to execute the java files present in the path "C:\test" ?


Solution

  • Note: Instead of using winrs calls via powershell.exe to execute remote commands, consider using PowerShell's remoting, which is equally WinRM-based.


    Therefore:

    winrm set winrm/config/client "@{TrustedHosts=remoteHostServer}"
    winrs /r:remoteHostServer /username:admin /password:xxxxxx powershell -c "Set-Location C:\test; java test.java"
    

    Note that you do not need PowerShell to execute your specific remote command either. Here's the version without PowerShell, using the -d option to set the remote working directory:

    winrm set winrm/config/client "@{TrustedHosts=remoteHostServer}"
    winrs /r:remoteHostServer /username:admin /password:xxxxxx -dC:\test java test.java
    

    Note that the remote cmd.exe session that winrs implicitly creates automatically ends when a given command finishes executing (the powershell ... call in this case).
    That is, the remote session ends and returns control to the caller once the remote command terminates.

    An interactive remote session can only be entered if you specify a shell executable as the command to execute, such as cmd.exe and powershell.exe without arguments (or with /K / -NoExit).
    However, note that the commands you submit remotely will be echoed before their output prints; while there is a -noecho option to suppress that, it unfortunately also hides commands as they're being typed.


    Sending many commands to execute remotely via winrs.exe and PowerShell:

    The above shows that you can simply pass multiple commands, separated with ;, inside the "..." string passed to the -Command (-c) parameter of powershell.exe, the Windows PowerShell CLI.
    Given that the command-line length limit is close to 32,767 characters, this makes it possible to send many commands.
    However, the single-line requirement and the need to escape embedded " chars. make this approach awkward.

    The alternatives are: