Skip to content
PowerShell

PowerShell

Handy Powershell

Divert errors to a file:

1
 2>> C:\temp\filecontainingerrors.txt
1
Get-childitem -recurse 2>> C:\temp\errors.txt

Open another powershell window as admin:

1
Start-Process powershell -Verb runAs

Get location of exe running proces:

1
get-process  | fl path

Delete contents of folder

1
 Get-ChildItem C:\LocationOfFolder\Folder -Recurse | ForEach { Remove-Item $_.FullName -Force -Recurse }

Change to environment locations:

1
cd $Env:
1
cd $Env:userprofile

Show all environment vairables:

1
dir env:

Show path to PS modules:

$env:PSProfilepath

Add To PATH

1
2
3
4
5
[$env:PATH + ";", [System.EnvironmentVariableTarget](System.Environment]::SetEnvironmentVariable("PATH",)::Machine)

eg:

[$env:PATH + ";C:\Program Files\OpenSSL-Win64\bin", [System.EnvironmentVariableTarget](System.Environment]::SetEnvironmentVariable("PATH",)::Machine)

Restart computer remotely:

1
restart-computer -Computername [-Credential [domain\username](hostname]) -force

Send a message to a user on a remote host:

msg /server: /v


Powershell Remoting

Connect to remote powershell session:

1
2
3
4
5
6
$cred=Get-Credential
$sess = New-PSSession -Credential $cred -ComputerName 
Enter-PSSession $sess

Exit-PSSession
Remove-PSSession $sess

If you are getting an error when remoting like “WinRM cannot process the request.” use Windows PowerShell to add each server to the Trusted Hosts list on your management computer:

1
Set-Item WSMAN:\Localhost\Client\TrustedHosts -Value Server01 -Force

Note: the trusted hosts list supports wildcards, like Server*

To view your Trusted Hosts list:

1
Get-Item WSMAN:\Localhost\Client\TrustedHosts

To empty the list:

1
Clear-Item WSMAN:\Localhost\Client\TrustedHost

If errors show run the following command to check on the winrm service+config:

1
winrm quickconfig

##Services with Powershell Get services running on computer and display in a pauseable list:

1
Get-Service | Where-Object {$_.Status -eq "Stopped"} | More
1
gsv | where {$_.Status -eq "running"} | more

Output Command History to text file:

Get-History | ForEach-Object { $_.CommandLine } > $env.USERPROFILE\testoutput.txt


Get Powershell to display all output in the case that output is displayed truncated:

Pipe to “out-string -width 500” to display in a sting of set number of characters:

1
 | out-string -width 500

In the case of an array change the vairable $FormatEnumerationLimit to -1

1
$FormatEnumerationLimit=-1

Script to ping IP address and log time and status of ping:

https://github.com/AleksPish/NetworkPingTest/blob/master/NetworkDownTest.ps1

Download file from internet:

1
 Invoke-WebRequest  | out-file 

Also can use Download method of WebClient

1
2
3
$client = New-Object System.Net.WebClient
$client.DownloadFile($url, $path)
(new-object System.Net.WebClient).DownloadFile( '$url, $path)

Get public IP address of device:

1
(Invoke-RestMethod ipinfo.io/json).ip

Add Exclusions to security check from downloaded programs:

add-mppreference -exclusionpath ""


Get members of ad group:

get-adgroupmember -identity "" | select-object name


Get Computer / Server Uptime - last boot time

1
(get-date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime

Powershell Modules and comms errors

Install PS module

1
Install-Module 

If there is an error the issue may be with TLS - run the following command first:

1
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Resolve TLS problems for good by updating PowershellGet:

1
Install-PackageProvider Nuget -force -Verbose
1
Install-Module -Name PowershellGet -Force -Verbose

File Admin Powershell

List folders

1
Get-childitem

Move all files of a specified extension from the current directory to another directory, move recursively

1
2
3
4
5
Get-ChildItem -Path 

Move registry keys and values to another key

Move-Item "HKLM:\software\mycompany\*" "HKLM:\software\mynewcompany"

Display errors that were seen when accessing files:

1
$Error | ForEach-Object { Write-Host $_.TargetObject }

Active Directory Powershell

Export details of users in a specific OU:

1
2
$ExportPath = "<Path>
Get-ADUser -Filter * -SearchBase $OUpath | Select-object DistinguishedName,Name,UserPrincipalName,sAMAccountName | Export-Csv -NoType $ExportPath

Get all groups a user is assigned to

1
Get-ADPrincipalGroupMembership username | select name

Get group:

1
Get-ADGroup -Identity 

Get members of group:

1
Get-ADGroupMember -identity 

Change password expiry setting on ad accounts by OU Import-Module ActiveDirectory

1
Get-ADUser -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" | Set-ADUser -PasswordNeverExpires:$True

Search for adusers using powershell:

Can be used with various options: DistinguishedName, Enabled, GivenName, Name, ObjectClass, Object GUID, SamAccountName, SID, Surname, UserPrincipalName.

1
get-aduser -filter "name -eq ''"

Unlock user account:

1
Get-ADuser -identity  | unlock-ADaccount

Check for lock status:

1
Get-ADuser -Identity  -properties Lockedout

Local Accounts commands

Use for managing local accounts:

1
New-localUser -name ""

Change details of local user

1
Set-localuser

Change password:

1
$Password = Read-Host -AsSecureString
1
$UserAccount = Get-LocalUser -Name ""
1
$UserAccount | Set-LocalUser -Password $Password

Add to group:

1
Add-localgroupmember -group "" -member ""

Powershell for Admin

Get powershell update

1
iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"

Get FSMO roles on which domain controllers at domain level:

Get-ADDomain | Select-Object InfrastructureMaster,PDCEmulator,RIDMaster | Format-List

Get FSMO roles on which domain controllers at forest level:

Get-ADForest | Select-Object DomainNamingMaster,SchemaMaster | Format-List

Get all current logged in sessions:

1
(Get-CimInstance Win32_LoggedOnUser)

Installing packages in powershell

Use winget to install packages:

1
winget install 

You may need to specify the source:

1
winget install  --source winget

Upgrade/update packages with winget:

1
winget upgrade --all

Chocolatey is now pretty much depreciated with the introduction of winget - install with MS store

Can use chocolatey to get packages:

1
2
Set-ExecutionPolicy Unrestricted
iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex

For SSH connections:

Putty:

choco install putty

OpenSSH:

choco install openssh # installs open ssh refreshenv # reloads the environment variables ssh remoteClient -i “MyKeyPair.pem” # connects to remoteClient via ssh

poshSSH:

Install-Module Posh-SSH # installs the posh-ssh module Get-Command -Module Posh-SSH # shows all posh-ssh commandlets New-SSHSession myclient -KeyFile “c:\data\MyKeyPair.pem” # connect to my client with the give keyfile Invoke-SSHCommandStream “ifconfig” -SessionId 0 # send ifconfig to the ssh session with id 0 Invoke-SSHCommand -SessionId 0 -Command “ifconfig” # send ifconfig to the ssh session with id 0 Invoke-SSHCommand -SessionId 0 -Command “logout” # send logout to the ssh session with id 0 Remove-SSHSession 0 # removes and closes the ssh session

For firefox:

choco install firefox -y

Issue with psrepository

try to fix psrepository:

1
Register-PSRepository -Default

If this fails use the following:

Install the PSRepository using the following settings:

$Repository = @{ Name = ‘PSGallery’ SourceLocation = ‘https://www.powershellgallery.com/api/v2/' PublishLocation = ‘https://www.powershellgallery.com/api/v2/package/' ScriptSourceLocation = ‘https://www.powershellgallery.com/api/v2/items/psscript' ScriptPublishLocation = ‘https://www.powershellgallery.com/api/v2/package/' InstallationPolicy = ‘Untrusted’ }

Register-PSRepository @Repository

Powershell Alias

gsv Get-Service

spsv Stop-Service

sasv Start-Service

Powershell for Services and Processes

Get all properties of a service and display specific properties of the service:

1
get-service | get-member
1
get-service wuauserv | select Displayname,Status,ServiceName,Can*

Display list of only running services:

1
Get-Service | Where-Object {$_.Status -EQ "Running"}

Remotely Check Service:

1
get-service wuauserv -ComputerName remotePC1

Get Service PID to kill process:

1
$ServicePID = (get-wmiobject win32_service | where { $_.name -eq 'service name'}).processID 
1
Stop-Process $ServicePID -Force

Get top 10 processes by memory usage

1
Get-Process | Select-Object name,workingset64 | Sort-Object -Property workingset64 -Descending | Select-Object 

-First 10

Get User Process with an active GUI (no background processes will be displayed:

1
Get-Process | Where-Object {$_.mainWindowTitle}

Encrypt Passwords for use in Powershell scripts - scheduled tasks

Use Export-Clixml

Easiest way is to export the user credentials as an xml object using export-clixml then import with import-clixml:

1
2
$credential = Get-Credential
$credential | Export-Clixml 

Then import the user credentials from the exported file (the credentials are stored encrypted in the xml file):

1
$credential = Import-Clixml 

Use convertfrom/to-securestring method

Use the convertfrom-securestring command to take a secure string (password) then store as a file eg:

1
$SecurePassword = Read-host -AsSecureString | ConvertFrom-SecureString
1
$SecurePassword | Out-File -FilePath "C:\Encrypted.key"

To use the the passwords in a script use the get-content:

1
$username = "Administrator"
1
$password = Get-Content "C:\Encrypted.key" | ConvertTo-SecureString
1
$credential = New-Object System.Management.Automation.PsCredential($username,$password)

If you want to encrypt the username and password you can do the following:

1
$securecred = Get-Credential
1
$securecred.UserName | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | set-content "C:\Username.key" 
1
$securecred.Password | ConvertFrom-SecureString | set-content "C:\Password.key"

They are stored in separate files

If you want to get the password back as plain text you can use the following:

1
2
$password = Get-Content "C:\Encrypted.key" | ConvertTo-SecureString
$plainpassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

Script Writing Info

Find out what escape character to use for special characters:

1
[Regex]::Escape("")