简体   繁体   中英

Can I RDP through mstsc and run a script on that remote desktop?

I'm writing a script which needs to RDP to a few servers, do processes there and then come back.

mstsc /v:<computer> by itself looks great as it's security/credential prompt is the same as if you manually executed it.

However, after some research it appears that's meant to be a command line utility and nothing more because trying things like:

mstsc /v:104.209.198.181 | Invoke-Command -ScriptBlock {"New-Item C:\Users\<me>\Desktop\Success.txt -ItemType file"} 

doesn't work.

So I tried Enter-PSSession <computer> -Credential $env:UserName which people use but it looks like a mess to deal with compared to mstsc because it looks primitive (an article I read yesterday tried to say this type of prompt is ALWAYS a phishing scam which obviously it's not but try telling management), it doesn't auto-populate domains, and I get a WinRM error which I'm sure will be a rabbit hole.

So is it possible to RDP with mstsc and then pipe commands to it so they're executed on that computer?

The answer is no. You cannot initiate some kind of pipe using MSTSC.exe .

You can, however, use PSRemoting to send the command like you're trying to do already:

Invoke-Command -ComputerName '<FQDN>' -ScriptBlock {
    New-Item -Path "$HOME\Desktop\Success.txt" -ItemType File
}

If you don't know the FQDN, then look up the IP using DNS:

[System.Net.Dns]::GetHostEntry('104.209.198.181')

All this failing.. you can fall back on WMI, but you don't get any console feedback:

$WmiArgs = @{
    'Class'        = 'Win32_Process'
    'Name'         = 'Create'
    'ArgumentList' = 'powershell -NoProfile -NonInteractive -WindowStyle Hidden -Command "New-Item -Path $HOME\Desktop\Success.txt -ItemType File"'
    'ComputerName' = '104.209.198.181'
}
Invoke-WmiMethod @WmiArgs

While I tested the above is working, you can shorthand even this!

([wmiclass]'\\104.209.198.181\root\cimv2:win32_process').
    Create('powershell -NoP -NonI -W Hidden -C "New-Item -Path $HOME\Desktop\Success.txt -ItemType File"')

With this method, however, you cannot pass credentials.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM