PowerShell Cheat Sheet

A PowerShell Cheat Sheet gained from random notes and blog posts.

Count Rows within a .CSV File
Check a Port is Open
Disk Management
Set IP Address
Create Windows Firewall Rule
Map Network Drive
Compress & Password Protect Files
Send an Email


Count Rows within a .CSV File

# Count rows within CSV files, in a specified directory.
Get-ChildItem "C:\myfolder\" -re -in "*.csv" |
Foreach-Object { 
    $fileStats = Get-Content $_.FullName | Measure-Object -line
    $linesInFile = $fileStats.Lines -1
    Write-Host "$_,$linesInFile" 
}

Check a Port is Open

# Check a port is open (pre Win08/Svr2012).
$Ipaddress= Read-Host "Enter the IP address:"
$Port= Read-host "Enter the port number to access:"
$t = New-Object Net.Sockets.TcpClient
$t.Connect($Ipaddress,$Port)
if($t.Connected)
    {"Port $Port is operational."}
else {"Port $Port is closed."}

Disk Management

# Get disk & volume info 
Get-Disk | Get-Partition | Get-Volume


# Adding new volume 
Get-Disk

Initialize-Disk -Number <number> -PartitionStyle MBR

New-Partition -DiskNumber <number> -AssignDriveLetter -UseMaximumSize

Format-Volume -DriveLetter <drive letter> -FileSystem NTFS -NewFileSystemLabel <label> -AllocationUnitSize 64KB


# Resizing disk 
"rescan" | diskpart #(rescan disks after changes) 

$size = (Get-PartitionSupportedSize –DiskNumber 3 –PartitionNumber 1) 

Resize-Partition -DiskNumber 3 –PartitionNumber 1 -Size $size.SizeMax 


# Set online/offline & read-only
Set-Disk 1 -IsReadOnly $false

Set-Disk 1 -IsOffline $false
 

# Check allocation unit size
$wql = "SELECT Label, Blocksize, Name FROM Win32_Volume WHERE FileSystem='NTFS'" 

Get-WmiObject -Query $wql -ComputerName '.' | Select-Object Label, Blocksize, Name 


# Map disk drives to Volumes wmi
Get-WmiObject Win32_DiskDrive | ForEach-Object {
    $Partitions = Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($_.DeviceID.Replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"
    $Vols = $Partitions | ForEach-Object {Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($_.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"}
    $_ | Select-Object SerialNumber,DeviceID,Size,@{l='Volumes';e={$Vols.DeviceID}}
}

Set IP Address

# Set IP address 
New-NetIPAddress -InterfaceAlias Ethernet -IPAddress 10.1.1.2 -DefaultGateway 10.1.1.1 -PrefixLength 24

Create Firewall Rule

# New firewall rule
if (-not( Get-NetFirewallRule -DisplayName “Allow Inbound SQL (1433)” -ErrorAction SilentlyContinue)) { 
New-NetFirewallRule `
    -DisplayName “Allow Inbound SQL - 1433” `
    -Direction Inbound `
    -Protocol TCP `
    -LocalPort 1433 `
    -Action Allow }

Map Network Drive

# Map network drive 
$net = new-object -ComObject WScript.Network 
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password") 

#Remove
$net.removenetworkdrive("u:")

Compress & Password Protect Files

$PathTo7Zip = "C:\Program Files\7-Zip\7zG.exe"
$OutputFilePath = "C:\temp\test4.zip"
$FilesToZip = "C:\newfolder\"
$Password = 'PASSWORD!'
$Args = "a -tzip ""$OutputFilePath"" ""$FilesToZip"" -mx9 -p$Password"
$WindowStyle = "Normal"
$p = Start-Process $PathTo7Zip -ArgumentList $Args -Wait -PassThru -WindowStyle $WindowStyle

Send an Email

# Send email 
Send-MailMessage -From someon@dot.com -To someon@dot.com -Subject "Subject" -Body "Body" -SmtpServer smptservername