Because there is still little time, at the time of publishing this article, it does not contain too many commands, but I will add more over time. I have notes in various places that I want to organize. There is definitely an opportunity for you to share an interesting command in the comments.
General
Enumeration Constants
There are several options for using them.
[Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatPDF [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatRTF")
Listing the values.
[Microsoft.Office.Interop.Word.WdSaveFormat] | Get-Member -Static -MemberType Property
Output Formatting
The main two formatting options are into a table using Format-Table alias FT and using a list with Format-List alias FL. We pass the output to the formatting function using | (pipe). After the function, we can list the columns we want to display. We can also use -AutoSize to adjust the column widths in the table.
Get-Process | FT ProcessName, CPU -AutoSize
Sorting Output
Using Sort-Object we can sort the output we display. If we want to format the output at the same time, we must sort first.
Get-Process | Sort-Object -Descending CPU Get-Process | Sort-Object -Descending CPU | FT name,cpu -AutoSize
Determining Variable Type
$x = 15 $x.GetType().FullName System.Int32
Determining Object Methods and Properties
$object | Get-Member
Object Statistics, Number of Elements
$object | Measure-Object ($object | Measure-Object).Count
Registry
We can browse the registry the same way as the file system. Subtrees are mapped to drives, HKEY_LOCAL_MACHINE to HKLM: and HKEY_CURRENT_USER to HKCU:.
PS C:\>cd HKCU: PS HKCU:\> dir
PS HKCU:\> cd Software PS HKCU:\Software> dir
The Get-ItemProperty cmdlet (for the current one Get-ItemProperty .) is used to read values, Set-ItemProperty to write, and Remove-ItemProperty to delete.
System Environment Variables
Listing all variables.
Get-ChildItem Env:
Displaying a single value.
$Env:COMPUTERNAME
Creating a new value.
$Env:test = "Test"
Event Log Entries
List of logs available in the system.
Get-EventLog -list
Creating a log entry. An entry can only be created for an existing Source, and the EventId is also important.
Write-EventLog -LogName "Application" -Source "PerfOS" -EventId 2011 -EntryType Error -Message "Test"
Display the latest 5 records of a given type and ID from the System log.
Get-EventLog -LogName system -EntryType warning -InstanceId 129 -Newest 5
Opening a Web Address (URL)
Opening a browser window and the given address.
(New-Object -com Shell.Application).Open("https://www.samuraj-cz.com")
Start-Process -FilePath "https://www.samuraj-cz.com"
If we don't want to open a browser, but just call the URL or process the content, we can use the following code, which returns the page content (we can store it in a variable).
(new-object net.webclient).DownloadString("https://www.samuraj-cz.com")
Working with Time
$time = Get-Date (Get-Date).AddHours(-1) (Get-Date).Day
Sending Email
$smtp = new-object Net.Mail.SmtpClient("mail.domain.tld")
$smtp.Send(New-Object System.Net.Mail.MailMessage('recipient@domain.tld','sender@domain.tld','subject','text'))
Or using native means
Send-MailMessage -From sender@domain.tld -To recipient@domain.tld -Subject "subject" -SmtpServer server -Attachments file.txt -Encoding ([System.Text.Encoding]::Unicode) -Body "text"
File System
Working with Files and Directories
Checking if a given directory or file exists.
Test-Path C:\Scripts\test
Creating a directory.
New-Item C:\Scripts\test -type directory
Creating a file.
New-Item C:\Scripts\sample.txt -type file
Finding Folders with AD Group Permissions
Simple search that goes through the given path (including nested folders) and lists the folders that have the specified AD group set. In this case, if there is a group whose name starts the same, it will also find it (not an exact match).
$StrGroup = "DL Group"
$Folder = "C:\1"
Get-ChildItem $Folder -Recurse | where { $_.Psiscontainer } | Get-Acl | where {$_.AccessToString -match $StrGroup} | select path
Operating System
Determining OS Version
For many tasks, we still don't have a native cmdlet, so we can use the broad capabilities of WMI (if we have it enabled).
Returns the OS version, SP info, and architecture (32-bit or 64-bit).
Get-WmiObject Win32_OperatingSystem -ComputerName computer | FL Caption,ServicePackMajorVersion,OSArchitecture
Note: Instead of the Get-WmiObject command, we can use its alias gwmi.
Windows Services
List all services with color differentiation for running ones.
Get-Service | Sort-Object status,displayname |
ForEach-Object { if($_.status -eq "running") {
Write-Host $_.status `t $_.name `t $_.displayname -ForegroundColor "green"
} elseif( $_.status -eq "stopped" ) {
Write-Host $_.status `t $_.name `t $_.displayname -ForegroundColor "red"
} else {
Write-Host $_.status `t $_.name `t $_.displayname
} }
Hardware
Obtaining Information About Connected Disks
In the example, we are determining the manufacturer, model, size, and ID of a USB flash drive. The same can be used for hard drives. We perform the call using PowerShell, but in reality, we are using WMI (Windows Management Instrumentation). We can call locally or on a remote computer (if we have the necessary permissions).
gwmi Win32_DiskDrive | where-object {$_.InterfaceType -like "USB"} | fl Model,Size,PNPDeviceID
gwmi Win32_DiskDrive -ComputerName computer | where-object {$_.InterfaceType -like "USB"} | fl Model,Size,PNPDeviceID
There are no comments yet.