PowerShell one liners for common tasks

Introduction

Commands validated with PowerShell 5.1 on Windows 10, some commands may work on other versions.

For information on using PowerShell, including how to find additional commands that are not listed here, see General PowerShell usage tips.

To see the additional parameters for any of these commands, you can use the following command:

help [command] -full

PowerShell

Clear the console window

Clear-Host

View the command history for the current session

get-history | more

Repeat a command in the history

invoke-history [id from output of get-history]

Save the history to a csv file

invoke-history | export-csv [output path & filename]

Save session input and output to a file

start-transcript [output path & filename] -IncludeInvocationHeader

Stop saving the transcript

stop-transcript

Networking

Get Information

ipconfig /all equivalent
gip is short for Get-NetIPConfiguration.

gip

Show network adaptors

get-netadapter

Print routing table

get-netadapter [name] | get-netroute [[-addressfamily ipv4]]

Show active network connections

Get-NetTCPConnection | ? State -eq Established | sort Localport | FT -Autosize

Show client’s DNS Cache

Get-DnsClientCache

Show the client’s mapped drives

Get-SmbMapping

Run Tests

Ping equivalent

test-connection [computer]

‘Continuous’ ping
(999999999 pings)

test-connection [computer] -count 999999999

Traceroute
tnc is short for Test-NetConnection. -tr is short for -TraceRoute.

tnc [computer] -tr

Test if a remote port is accessible / open

tnc [computer] -p [port]

Test if a remote port is accessible / open (more info)

tnc [computer] -p [port] -inf detailed

DNS lookup

resolve-dnsname [computer]

Make Changes

Map a network drive

New-SmbMapping -LocalPath [drive_letter]: -RemotePath [UNC Path]

Microsoft Exchange 2010 on prem

Introduction

These commands must be run from a machine with the Exchange management tools installed, and the following command must be added to a powershell or script session first:

. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto

Alternatively (adds -CommandName to speed up connection to exchange, by only including the cmdlets you choose to use):

$session = New-PSSession -ConfigurationName Microsoft.Exchange `
-ConnectionUri 'http://[exchange_hostname]/PowerShell/?SerializationLevel=Full' `
-Authentication Kerberos
Import-PSSession -Session $session `
-CommandName Get-Mailbox,New-Mailbox,Enable-Mailbox,Set-Mailbox -FormatTypeName *

Get Information

List accounts that have send as access on other mailboxes
Credit to and for further information: https://www.ucunleashed.com/277.

Get-Mailbox -ResultSize Unlimited | Get-ADPermission | `
Where-Object {($_.ExtendedRights -like "*send-as*") -and `
-not ($_.User -like "nt authority\self")} | Format-Table Identity, User -auto

List accounts that have full access to other mailboxes
Credit to and for further information: https://www.ucunleashed.com/277.

Get-Mailbox -ResultSize Unlimited | Get-MailboxPermission | `
Where-Object {($_.AccessRights -match "FullAccess") -and `
-not ($_.User -like "NT AUTHORITY\SELF")} | Format-Table Identity, User

View the mailbox size limits on an account

Get-Mailbox [identity] | Format-List *Quota

View the list of currently quarantined activesync devices

Get-ActiveSyncDevice -filter {deviceaccessstate -eq 'quarantined'} | `
select identity, deviceid | fl

Make Changes

Set the mailbox size limits on an account
[size] in mb or gb, e.g. 500mb, 2gb

Set-Mailbox [identity] -IssueWarningQuota [size] -ProhibitSendQuota [size] `
-ProhibitSendReceiveQuota [size] -UseDatabaseQuotaDefaults $false

Add cc to a mailbox (cc to another exchange account)

Set-Mailbox -Identity "Full Name" -DeliverToMailboxAndForward $true -ForwardingAddress "Full Name"

Remove cc from a mailbox (from another exchange account)

Set-Mailbox -Identity "Full Name" -ForwardingAddress $null -ForwardingSmtpAddress $null

Approve a quarantined activesync device
Use the first command to get the device ID required for the second command.

Get-ActiveSyncDevice -filter {deviceaccessstate -eq 'quarantined'} | `
select identity, deviceid | fl
Set-CASMailbox –Identity [account] –ActiveSyncAllowedDeviceIDs [DEVICEID]

Computer & Hardware

Get Information

Get local computer name

$env:computername

Get last bootup time of a remote computer

[Management.ManagementDateTimeConverter]::ToDateTime((Get-WmiObject Win32_OperatingSystem `
-Property LastBootUpTime -ComputerName [computer]).LastBootUpTime)

or

Get-WmiObject win32_operatingsystem -ComputerName [computer] | `
select @{Name="Last Boot Time"; Expression={$_.ConvertToDateTime($_.LastBootUpTime)}}, PSComputerName

Make Changes

Rename a computer

rename-computer -name [original_name] -newname [new_name]

Restart computer

restart-computer

Restart remote computer

restart-computer -computername [computer]

Stop computer

stop-computer

Start a process

Start-Process -FilePath [executable] -Wait -WindowStyle Maximized

Remove Windows feature

disable-windowsoptionalfeature -feature [featurename]

Windows Registry

Get Information

List keys one level down from a registry path
Add the -force parameter to include hidden or system keys. To display all keys from the path down, include the -recurse parameter.

Get-ChildItem -Path [path e.g. hkcu:\]

Browse the registry like a file system

Set-Location hkcu:
cd SOFTWARE
dir

Make Changes

Create a new key

New-Item -Path [path and key, e.g. hkcu:\new_key]

Delete a key

Remove-Item -Path [path and key, e.g. hkcu:\new_key]

Set a registry value

If you are browsing the registry like a file system as referenced above, the path below can be referenced as you would a normal file system location, e.g. -Path .\Key for a key in the current working directory / location.

If you receive a permission denied message, change the user that the powershell console or commands are run under to one that has the required permissions to the registry location.

Set-ItemProperty -Path [path and key, e.g. hkcu:\key] -Name [PropertyName] -Value [New Value]

Windows Services

Get Information

List all services

Get-Service [optional wildcard search on service name (not display name)] | `
sort [Status, Name or Displayname]

List running services

Get-Service [[optional wildcard search on service name (not display name)] | `
where Status -eq running | sort [Status, Name or Displayname]

Search for a service running on a remote computer, search based on Display Name

get-service -computername hyd-rdsh-10 | where DisplayName -match [search_expression]

Make Changes

Start service

start-service [service name]

Stop service

stop-service [service name]

Restart service

restart-service [service name]

Printers

Get Information

View print shares on a computer

get-printer -computername [Computer Name] | where Type -eq Local | `
select ComputerName, Name, ShareName, Location, Comment | Out-GridView

View print queues in an error state

Get-Printer -ComputerName [computer] | where PrinterStatus -eq Error | `fl Name,JobCount

View jobs on a print queue

Get-PrintJob -ComputerName [computer] -PrinterName [print queue]

View print job information

Get-PrintJob -ComputerName [computer] -PrinterName [computer] | `
where id -eq [job number] | fl JobStatus,UserName

Make Changes

Add printer queue

add-printer -connect [path to printer, e.g. \\computer\queue_name]

Remove printer queue

Remove-Printer -Name "[Printer Path and Name]"

Files

Get Information

List all .jpg files in a location including sub directories

Get-ChildItem -Path [Drive]:[Path] -Recurse -Include *.JPG

Make Changes

Copy files from one location to another

Copy-Item [path, optionally including file reference] -Destination [path] -Verbose

Move files from one location to another

Move-Item [path] -Destination [path] -Verbose

Rename a file or folder

Rename-Item [path] -NewName [path]

Active Directory

Get Information

List all inactive user accounts

search-adaccount -accountinactive -datetime "[date]" -usersonly

Make Changes

Set title of an AD account

set-aduser [name] -title [new_title]

Disable an AD account

disable-adaccount -identity "[AD user]"

Microsoft Configuration Manager / SCCM

Get Information

List applications available for installation in Software Center
Where [path_to_computers_file] is a text file containing a list of computers. For a single computer, just use the computer name after -ComputerName.

Get-WmiObject -Class ccm_application -Namespace root\ccm\clientsdk `
-ComputerName (get-content [path_to_computers_file]) | `
Where-Object { ($_.InstallState -ne "Installed") `
-and ($_.ApplicabilityState -eq "Applicable") `
-and ($_.IsMachineTarget -eq $True) `
-and ($_.EvaluationState -ne 1)} | `
select FullName,__SERVER
%d bloggers like this: