How to Execute a Command in a Remote Computer

How do I run a remote command in a specific session on a remote computer?

Just as myself, and Bender the Greatest mention, you can take the Scheduled Task route to run it under the users context:

try {
$command = "(New-Object -ComObject WScript.Shell).AppActivate((get-process notepad).MainWindowTitle)"
$computer = $env:COMPUTERNAME
if (Test-Connection -ComputerName $Computer -Count 1 -ErrorAction "Stop") {
$username = Get-CimInstance -ClassName "Win32_ComputerSystem" -ComputerName $computer | Select-Object -ExpandProperty UserName
if (-not$Username) {
Write-Output -InputObject "No user logged into: $Computer."
Break
}
else {
Write-Verbose -Message "Current logged in user: $Username."
Invoke-Command -ScriptBlock {
$time = (Get-Date).AddMinutes(2).ToString("HH:mm")

#The name of your scheduled task.
$taskName = "MainWindow"

#Task description.
$description = "Bring notepad to front."

#Task action - what it should do.
$taskAction = New-ScheduledTaskAction -Execute 'PowerShell.exe' `
-Argument "-Command $using:command"

#Task trigger
$taskTrigger = New-ScheduledTaskTrigger -At $time -Once

#Register the scheduled task.
Register-ScheduledTask -TaskName $taskName `
-Description $description `
-Action $taskAction `
-User $using:username #| Out-Null

#Run the task
Start-ScheduledTask -TaskPath $taskName #| Out-Null

#optional timer
#Start-Sleep -Seconds 1

#Remove the newly created task since it's done running
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false

} -ComputerName $computer
}
}

}
catch {
Write-Output -InputObject $_.Exception.Message
}

You may have to remove the pre-pended domain in the username for Task Scheduler to properly find the user in AD (ran into this issue before - should work though). As you can see it's a tedious process but, it can be done. The biggest hassle is trying to piece it all together as it can become a bit confusing.

If you have the time, I'd recommend turning it into a function that accepts a -Command, and -FilePath argument for future use as well as robustness.


I haven't tested it out, but I wouldn't see why it wouldn't work. You may have to provide administrative credentials given your environment but, when using Kerberos you should be good; as long as your session is ran as Admin.

Enter-PSSession doesn't execute command on remote computer

You create PSSession when you want to execute multiple commands on a remote system. However, if you only need to run a single command/script, no need for a persistent PSSession.

You use Enter-PSSession for interactive work. However, when you using PSSession in a script/function, simply use Invoke-Command instead. It will be easier and faster.

Example

$secure_password = 'password' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'administrator', $secure_password

Invoke-Command -ComputerName 192.168.1.222 -Credential $cred -ScriptBlock { New-Item -Name "C:\Users\Administrator\Desktop\new_folder" -ItemType Directory }

Note: It is a bad idea to hardcode clear-text passwords into your scripts. Have a look at a native way to store credentials externally: SecretManagement

How can I launch .cmd files on a remote machine?

You need to change the working directory in the scriptblock. Add a Set-Location before calling the batch script:

Invoke-Command -ComputerName test123 -ScriptBlock {
Set-Location 'C:\'
& cmd /c ".\myfile.cmd"
}

If you need to create a detached process, you can do that for instance via WMI:

$hostname = 'test123'
$command = 'C:\path\to\script.cmd'
$workdir = 'C:\working\directory'

$p = [wmiclass]"\\$hostname\root\cimv2:Win32_Process"
$p.Create($command, $workdir)

Note that you need admin privileges on the remote host for this.

How can I run a command in windows that is triggered/detects logging in remotely vs local?

Create 2 tasks

  • Administrative Tools
  • Task Scheduler
  • Action -> Create Task
  • Triggers Tab
  • New Button
  • Begin Task -> On connection to user session
  • Either: Connection from remote computer OR Connection from local computer

Execute CMD in remote desktop and receive output

If you are not sticking with python. You can use PsExec to execute remote commands.

https://learn.microsoft.com/en-us/sysinternals/downloads/psexec



Related Topics



Leave a reply



Submit