Press "Enter" to skip to content

Windows Remote Command Line Troubleshooting Tips and Tricks

johnyan 0

Last updated on August 9, 2019

Here are some scripts and methods to do remote troubleshooting or running some commands in remote machines. I found they are very useful especially in a enterprise environment if you have your domain admin account.
Prerequisites to run remote commands:

  • Install .NET Framework 4.5.2 from \\shareserver\it\$Install\Scripting prerequisites\NDP452-KB2901907-x86-x64-AllOS-ENU.exe
    • or from https://www.microsoft.com/en-ca/download/details.aspx?id=42642
  • Install Windows Management Framework
    5.1:
    •  copy the folder \\shareserver\it\$Install\Scripting prerequisite\Windows Management Framework 5.1 to your C drive or download from https://docs.microsoft.com/en-us/powershell/wmf/5.1/install-configure
    •  Open PowerShell as an administrator,
      navigate into the directory on your C drive, and run the command
      • .\Install-Wmf.ps1
  • Install Microsoft Visual C++ 2017 redistributable from \\shareserver\it\$Install\Scripting prerequisite\VC_redist.x64.exe
    • Download from https://www.microsoft.com/en-us/download/details.aspx?id=52685
  • From a PowerShell prompt running as an administrator, run the command
    • Set-ExecutionPolicy Unrestricted -Force
  • From a PowerShell prompt running as
    an administrator, run the command
    • winrm quickconfig

Sysinternals from Web Browser:

Run Powershell as Administrator

Click
Start, then type
powershell in the search field. Right-click “Windows PowerShell”, then click “Run
as Administrator” and enter your Domain Admin credentials.

You receive
an elevated PowerShell command prompt window running with your Domain Admin
credentials, which should have Administrator rights to any computer joined to
the enterpriese domain. 

Within this
window, change directory to C:\scripts
  

Remote Login Into PowerShell Session

PS C:\Scripting\PSTools>
PS C:\Scripting\PSTools> enter-pssession -ComputerName test-machine
[test-machine]: PS C:\Users\JADMIN\Documents>

Collect remote installed apps

1.    Run the command:
.\Get-InstalledApps
2.    You will be prompted for a computer
name. Enter the target computer’s DNS name without the domain, e.g.
testmachine1
3.    The script takes the following
actions:
a.    Modifies your local TrustedHosts
list to allow you to connect to the target computer
b.    Enables WinRM on the target computer
c.    Runs a Get-WmiObject command on the
target computer and outputs a list of installed applications to the screen
4.    Verify the list of applications.

Here is output:


PS C:\Scripting> .\Get-InstalledApps.ps1
.\Get-InstalledApps.ps1 : File C:\Scripting\Get-InstalledApps.ps1 cannot be loaded because running scripts is
disabled on this system. For more information, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ .\Get-InstalledApps.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess
PS C:\Scripting> Set-ExecutionPolicy Unrestricted -Force
PS C:\Scripting> .\Get-InstalledApps.ps1
Enter the target computer name: testmachine1

PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com


WinRM already is set up to receive requests on this machine.
WinRM already is set up for remote management on this machine.
winrm.cmd exited on sarefeen-l with error code 0.

Gathering information on installed apps, please wait...

Name
----

 Tools for .Net 3.5
Adobe Acrobat Reader DC
Adobe Refresh Manager
Amazon Redshift ODBC Driver 64-bit
Check Point VPN
Cisco AnyConnect Secure Mobility Client
Desktop Authority Computer Agent
Dolby Audio X2 Windows API SDK
Google Chrome
Google Update Helper
Java 7 Update 55
Java 8 Update 161 (64-bit)
Java Auto Updater
...

The script Get-InstalledApps content is:

#Prompt for target computer name
$Target = read-host "Enter the target computer name"

#Modify local TrustedHosts
set-item wsman:\localhost\Client\TrustedHosts -value "$Target" -Force

#Ensure WinRM is enabled
set-item wsman:\localhost\Client\TrustedHosts -value "$Target" -Force
.\PSTools\psexec \\$Target -s winrm.cmd quickconfig -q

#Create remote session
$session = New-PSSession -ComputerName $Target

#Run command in remote session
Write-Host " "
Write-Host "Gathering information on installed apps, please wait..." -foregroundcolor yellow
Invoke-Command -session $session -scriptblock{Get-WmiObject -Class Win32_Product | Sort-Object -Property Name | FT Name}

#Clean up sessions
Remove-PSSession *

Scan Remote Computer by Symantec Endpoint Protection

1.    Run the command:
.\Scan-RemoteComputer
2.    You will be prompted for a computer
name. Enter the target computer’s DNS name without the domain, e.g. testmachine1
3.    The script takes the following
actions:
a.    Modifies your local TrustedHosts
list to allow you to connect to the target computer
b.    Enables WinRM on the target computer
c.    Runs a psexec command to start a
Symantec Endpoint Protection scan of the target computer
d.    When the scan is complete, displays
the location of the log file(s) on the remote computer
4.    Connect to the remote computer by
browsing to the target computer’s C drive (e.g.
 \\testmachine1\c$) in File Explorer. When prompted for credentials, enter your Domain
Admin credentials.
5.    Copy the log file to your computer
for analysis.
PS C:\Scripting> .\Scan-RemoteComputer.ps1
Enter the target computer name: testmachine1

PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com


WinRM already is set up to receive requests on this machine.
WinRM already is set up for remote management on this machine.
winrm.cmd exited on testmachine1 with error code 0.
Scan is starting on testmachine1 (all drives, all files). This will take a while to complete! Do not close this window.

PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com


The script  Scan-RemoteComputer content is:

#Prompt for target computer name
$Target = read-host "Enter the target computer name"

#Modify local TrustedHosts
set-item wsman:\localhost\Client\TrustedHosts -value "$Target" -Force

#Ensure WinRM is enabled
set-item wsman:\localhost\Client\TrustedHosts -value "$Target" -Force
.\PSTools\psexec \\$Target -s winrm.cmd quickconfig -q

Write-Host "Scan is starting on $Target (all drives, all files). This will take a while to complete! Do not close this window." -foregroundcolor yellow

.\PSTools\psexec \\$Target -s "c:\Program Files (x86)\Symantec\Symantec Endpoint Protection\doscan.exe" /C /ScanAllDrives

Write-Host "Scan on $Target is complete. Check the log file at \\$Target\c$\ProgramData\Symantec\Symantec Endpoint Protection\(version number)\Data\Logs\AV for results." -foregroundcolor green

Run arbitrary commands on a
remote computer

Within the
elevated PowerShell window, change directory to C:\Scripting\PSTools:
     
cd\
     
cd .\Scripting\PSTools


PSTools can be downloaed from https://docs.microsoft.com/en-us/sysinternals/downloads/pstools


Run the
command:
.\psexec \\(target computer name) cmd (e.g.: .\psexec \\testmachine1 cmd)
Note that
the title bar of the PowerShell window changes to indicate the remote computer
name and the name of the command you ran, and that the command prompt changes
from PS C: to C:.
PS C:\Scripting> cd .\PSTools
PS C:\Scripting\PSTools> dir


    Directory: C:\Scripting\PSTools


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       29/09/2015  12:29 PM           7005 Eula.txt
-a----       20/06/2017  11:06 AM              0 psexec
-a----       29/09/2015  12:29 PM         396480 PsExec.exe
-a----       29/09/2015  12:29 PM         105264 psfile.exe
-a----       29/09/2015  12:29 PM         333176 PsGetsid.exe
-a----       29/09/2015  12:29 PM         390520 PsInfo.exe
-a----       29/09/2015  12:29 PM         468592 pskill.exe
-a----       29/09/2015  12:29 PM         232232 pslist.exe
-a----       29/09/2015  12:29 PM         183160 PsLoggedon.exe
-a----       29/09/2015  12:29 PM         178040 psloglist.exe
-a----       29/09/2015  12:29 PM         171608 pspasswd.exe
-a----       29/09/2015  12:29 PM         227520 psping.exe
-a----       29/09/2015  12:29 PM         169848 PsService.exe
-a----       29/09/2015  12:29 PM         207664 psshutdown.exe
-a----       29/09/2015  12:29 PM         187184 pssuspend.exe
-a----       29/09/2015  12:29 PM          66582 Pstools.chm
-a----       29/09/2015  12:29 PM             39 psversion.txt


PS C:\Scripting\PSTools> .\psexec \\testmachine1 cmd

PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com


Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\windows\system32>hostname
testmachine1

PS C:\windows\system32> enter-pssession -ComputerName testmachine1 -Credential admin
[testmachine1]: PS C:\Users\ADMIN\Documents>


You also can remote start a PowerShell session using command :

enter-pssession -ComputerName testmachine1 -Credential admin

Some other useful PowerShell commands


Get Windows DLL File Information / Version

PS C:\windows\system32> (get-item .\zipfldr.dll).versioninfo

ProductVersion   FileVersion      FileName
--------------   -----------      --------
6.1.7600.16385   6.1.7600.1638... C:\windows\system32\zipfldr.dll


PS C:\windows\system32>
PS C:\windows\system32> get-item .\zipfldr.dll


    Directory: C:\windows\system32


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       08/06/2018  12:21 PM         369664 zipfldr.dll

Or using vbs script:

PS C:\windows\system32> cscript .\versioninfo.vbs .\zipfldr.dll
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

6.1.7601.24168
PS C:\windows\system32> cscript //nologo .\versioninfo.vbs .\zipfldr.dll
6.1.7601.24168
PS C:\windows\system32>
PS C:\windows\system32> type .\versioninfo.vbs
set args = WScript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
WScript.Echo fso.GetFileVersion(args(0))
Wscript.Quit

PS C:\windows\system32> cscript //nologo .\versioninfo.vbs .\xolehlp.dll
2001.12.8530.16385
PS C:\windows\system32> (get-item .\xolehlp.dll).versioninfo

ProductVersion   FileVersion      FileName
--------------   -----------      --------
6.1.7600.16385   2001.12.8530.... C:\windows\system32\xolehlp.dll
PS C:\windows\system32>


It looks like there are difference between those two ways. vbs script will get you FileVersion, and get-item will list both ProductVersion and FileVersion.

PS C:\ISOScripting\PSTools>tasklist

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0         24 K
System                           4 Services                   0      7,316 K
smss.exe                       368 Services                   0        492 K
csrss.exe                      596 Services                   0      2,828 K
wininit.exe                    684 Services                   0      1,396 K
csrss.exe                      704 Console                    1    122,460 K
cmd.exe                       7956 Console                    1      4,528 K
....
C:\ISOScripting\PSTools>taskkill /pid 7956

Some Examples for using PSEXEC:

  • PSEXEC \\workstation64 CMD

Execute a program that is already installed on the remote system:

  • PSEXEC \\workstation64 “c:\Program Files\test.exe”

Connect to workstation64 and run IPCONFIG to display the remote PC’s IP address:

  • PSEXEC \\workstation64 ipconfig

Connect to workstation64 and list a directory:

  • PSEXEC \\workstation64 -s cmd /c dir c:\work

Connect to workstation64 and copy a file from another server:

  • PSEXEC \\workstation64 -s cmd /c copy \\server21\share45\file.ext c:\localpath

Execute IpConfig on the remote system, and display the output locally:

  • PSEXEC \\workstation64 ipconfig /all

Copy the program test.exe to the remote system and execute it interactively, running under the account DannyGlover:

  • PSEXEC \\workstation64 -c test.exe -u DannyGlover -p Pa55w0rd

Run Internet Explorer on the local machine but with limited-user privileges:

  • PSEXEC -l -d “c:\program files\internet explorer\iexplore.exe”

Run Regedit on the local machine with SYSTEM privileges:

  • PSEXEC -s -i regedit.exe

From PowerShell, run a VBscript on a remote workstation and pass some parameters:

  • PS C:> $script=’C:\Program Files\demo.vbs’
  • PS C:> $args = “some more text”
  • PS C:> PSEXEC -s \\workstation64 c:\windows\system32\cscript.exe $script $args

Some Other Useful Commands:

  • tasklist -s RemoteMachineName
  •  .\pslist -accepteula

Note:

-accepteula Suppress the display of the license dialog.

List/Stop/Disable/Enable/Start Remote Services

List Remote Machine’s Service and generate a htm file to show

<# 
.SYNOPSIS
Shows a list of services on remote operating system.
 
.DESCRIPTION
Function to retrieve a list of services.
 
.EXAMPLE
PS> .\Get-Remote-Services.ps1
#> 

Get-Service * -computername test1.51sec.org | Select-Object Status, Name, DisplayName | ConvertTo-HTML | Out-File C:\temp\Test.htm
Invoke-Expression C:\temp\Test.htm

List Local Machine’s Service

<# 
.SYNOPSIS
Shows a list of services on your operating system.
 
.DESCRIPTION
Function to retrieve a list of services.
 
.EXAMPLE
PS> .\Get-Services.ps1
#> 

Get-WmiObject win32_service | Select Name, DisplayName, State, StartMode | Sort State, Name

Disable Remote Machine’s Service and Stop it
.\Disable-Remote-Service.ps1 test1.51sec.org RemoteRegistry

[cmdletbinding()]            
param(            
 [string[]]$ComputerName = $env:ComputerName,            
 [parameter(Mandatory=$true)]            
 [string[]]$ServiceName            
)            
            
foreach($Computer in $ComputerName) {            
 Write-Host "Working on $Computer"            
 if(!(Test-Connection -ComputerName $Computer -Count 1 -quiet)) {            
  Write-Warning "$computer : Offline"            
  Continue            
 }            
             
 foreach($service in $ServiceName) {            
  try {            
   $ServiceObject = Get-WMIObject -Class Win32_Service -ComputerName $Computer -Filter "Name='$service'" -EA Stop            
   if(!$ServiceObject) {            
    Write-Warning "$Computer : No service found with the name $service"            
    Continue            
   }            
   if($ServiceObject.StartMode -eq "Disabled") {            
    Write-Warning "$Computer : Service with the name $service already in disabled state"            
    Continue            
   }            
               
   Set-Service -ComputerName $Computer -Name $service -EA Stop -StartMode Disabled            
   Write-Host "$Computer : Successfully disabled the service $service. Trying to stop it"            
   if($ServiceObject.Status -eq "Running") {            
    Write-Warning "$Computer : $service already in stopped state"            
    Continue            
   }            
   $retval = $ServiceObject.StopService()            
            
   if($retval.ReturnValue -ne 0) {            
    Write-Warning "$Computer : Failed to stop service. Return value is $($retval.ReturnValue)"            
    Continue            
   }            
               
   Write-Host "$Computer : Stopped service successfully"            
               
  } catch {            
   Write-Warning "$computer : Failed to query $service. Details : $_"            
   Continue            
  }            
             
 }            
            
}

PS C:\ISOScripting> .\Disable-remote-service.ps1 10.1.1.5 RemoteRegistry
Working on 10.1.1.5
10.1.1.5 : Successfully disabled the service RemoteRegistry. Trying to stop it
10.1.1.5 : Stopped service successfully

Enable / Start Remote Service

Set-Service -Name RemoteRegistry -ComputerName 10.1.1.12 -StartupType Manual -ErrorAction Stop
Start-Service -InputObject (Get-Service -Name RemoteRegistry -ComputerName 10.1.1.12) -ErrorAction Stop

Check Remote Machines Firewall Status

PS C:\ISOScripting\pstools> .\psexec.exe \\test1.51sec.ca netsh fir sh config

PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com



Domain profile configuration:
-------------------------------------------------------------------
Operational mode                  = Enable
Exception mode                    = Enable
Multicast/broadcast response mode = Enable
Notification mode                 = Enable

Service configuration for Domain profile:
Mode     Customized  Name
-------------------------------------------------------------------
Enable   No          File and Printer Sharing

Allowed programs configuration for Domain profile:
Mode     Traffic direction    Name / Program
-------------------------------------------------------------------
Enable   Inbound              VMware Workstation VMX / C:\program files (x86)\vmware\vmware workstation\x64\vmware-vmx.e
xe
Enable   Inbound              g2viewer.exe / C:\users\andywong\appdata\local\temp\g2_1470\g2viewer.exe
Enable   Inbound              SNAC Service / C:\Program Files (x86)\Symantec\Symantec Endpoint Protection\12.1.4013.4013
.105\Bin64\snac64.exe
Enable   Inbound              SMC Service / C:\Program Files (x86)\Symantec\Symantec Endpoint Protection\12.1.4013.4013.
105\Bin64\Smc.exe
Enable   Inbound              Nuance Pdf Converter Professional / C:\Program Files (x86)\Nuance\PDF Professional 8\bin\G
aaihoDoc.exe
Enable   Inbound              Nuance Pdf Create Assistant / C:\Program Files (x86)\Nuance\PDF Professional 8\bin\GPDFDir
ect.exe
Enable   Inbound              Nuance Activation / C:\Program Files (x86)\Nuance\PDF Professional 8\PdfPro8Hook.exe
Enable   Inbound              Nuance Pdf Converter Assistant / C:\Program Files (x86)\Nuance\PDF Professional 8\PDFRoute
r.exe

Port configuration for Domain profile:
Port   Protocol  Mode    Traffic direction     Name
-------------------------------------------------------------------
8298   TCP       Enable  Inbound               TechSmith Snagit
56789  TCP       Enable  Inbound               VMware vCenter Converter Standalone - Server
9089   TCP       Enable  Inbound               VMware vCenter Converter Standalone - Agent
2799   TCP       Enable  Inbound               Altova License Metering Port (TCP)
2799   UDP       Enable  Inbound               Altova License Metering Port (UDP)

ICMP configuration for Domain profile:
Mode     Type  Description
-------------------------------------------------------------------
Enable   2     Allow outbound packet too big
Enable   8     Allow inbound echo request

Standard profile configuration (current):
-------------------------------------------------------------------
Operational mode                  = Enable
Exception mode                    = Enable
Multicast/broadcast response mode = Enable
Notification mode                 = Enable

Service configuration for Standard profile:
Mode     Customized  Name
-------------------------------------------------------------------
Enable   No          Network Discovery

Allowed programs configuration for Standard profile:
Mode     Traffic direction    Name / Program
-------------------------------------------------------------------
Enable   Inbound              Firefox (C:\Program Files (x86)\Mozilla Firefox) / C:\Program Files (x86)\Mozilla Firefox\
firefox.exe
Enable   Inbound              SNAC Service / C:\Program Files (x86)\Symantec\Symantec Endpoint Protection\12.1.4013.4013
.105\Bin64\snac64.exe
Enable   Inbound              SMC Service / C:\Program Files (x86)\Symantec\Symantec Endpoint Protection\12.1.4013.4013.
105\Bin64\Smc.exe
Enable   Inbound              Microsoft OneNote / C:\Program Files (x86)\Microsoft Office\Office14\ONENOTE.EXE

Port configuration for Standard profile:
Port   Protocol  Mode    Traffic direction     Name
-------------------------------------------------------------------
8298   TCP       Enable  Inbound               TechSmith Snagit
56789  TCP       Enable  Inbound               VMware vCenter Converter Standalone - Server
9089   TCP       Enable  Inbound               VMware vCenter Converter Standalone - Agent
2799   TCP       Enable  Inbound               Altova License Metering Port (TCP)
2799   UDP       Enable  Inbound               Altova License Metering Port (UDP)

ICMP configuration for Standard profile:
Mode     Type  Description
-------------------------------------------------------------------
Enable   2     Allow outbound packet too big

Log configuration:
-------------------------------------------------------------------
File location   = C:\Windows\system32\LogFiles\Firewall\pfirewall.log
Max file size   = 4096 KB
Dropped packets = Disable
Connections     = Disable

IMPORTANT: Command executed successfully.
However, "netsh firewall" is deprecated;
use "netsh advfirewall firewall" instead.
For more information on using "netsh advfirewall firewall" commands
instead of "netsh firewall", see KB article 947709
at http://go.microsoft.com/fwlink/?linkid=121488 .

netsh exited on test1.51sec.ca with error code 0.
PS C:\ISOScripting\pstools>



Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: