Tools Links Login

8 Useful PowerShell Quickies

In my current position, I use PowerShell quite a bit, but not just for automation of repetitive tasks. I thought I would take a few minutes to jot down a few one-offs that might be of use to other folks.

Some of these might even be useful in larger scripts.

Stopping Processes

From time to time, it becomes necessary to manually stop a running process. This might be required to perform updates, or it might just be hosed.

I have used this method to stop all running instances of an app in a multi-user environment, in order to perform an update on the app, when users ignore the maintenance window. I just use this to kill it, then perform the update.

In this example, all instances of notepad are stopped:

get-process notepad | stop-process -Force

Tail with PowerShell

On Unix-like operating systems, the tail command reads a file, and outputs the last part of it (the "tail"). The tail command can also monitor data streams and open files, displaying new information as it is written.

Without some custom coding this has been missing from Windows, until the introduction of PowerShell. This has been around for awhile, but some folks haven't heard the news. So here it is, Tail via PowerShell.

Get-Content C:\inetpub\logs\LogFiles\W3SVC1\u_ex200422.log -Wait

This one-liner will write the output of the IIS log file specified, as entries get written, or until you break out of it with Control-C.

Remote Restart

Let's say you have to shutdown or restart a remote machine, quickly. This might be due to bad behavior coming from the computer, or you might simply need to restart it to apply an update of some sort. There are all kinds of reasons to need to restart it.

Being the lazy sysadmin that you are, you don't feel like walking across the building and poking the button. Sure, you could use Shutdown /I and specify the computer name. But why not use Powershell?

This snippet will perform a restart on the specified computer, provided the account you are running it with has necessary permissions on the target machine.

Restart-Computer -Force -ComputerName TargetToRestart

Who is Online

Need to get a list of currently responding IP addresses on a subnet? Try this on for size. Note: I updated this with a more robust script. Not the fastest, gives better output. Not really a one-line quickie, but useful nonetheless.

# This script pings a range of IP addresses and reports which ones are online

# Define the IP range

$subnet = "192.168.1" # Change this to your subnet
$startIP = 1 # Starting host number
$endIP = 254 # Ending host number

# Create an array to store results

$results = @()

Write-Host "Starting ping sweep of $subnet.$startIP to $subnet.$endIP..." -ForegroundColor Cyan
Write-Host ""

# Loop through the IP range

for ($i = $startIP; $i -le $endIP; $i++) {
    $ip = "$subnet.$i"

    # Perform ping with 1 count and 1 second timeout

    $ping = Test-Connection -ComputerName $ip -Count 1 -Quiet -ErrorAction SilentlyContinue

    if ($ping) {
        Write-Host "[ONLINE] $ip" -ForegroundColor Green
        $results += [PSCustomObject]@{
            IPAddress = $ip
            Status = "Online"
        }
    } else {
        Write-Host "[OFFLINE] $ip" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "Ping sweep completed!" -ForegroundColor Cyan
Write-Host "Total online hosts: $($results.Count)" -ForegroundColor Yellow

If you really want a one-liner for this, try the following code:

$online = 1..254 | ForEach-Object { if (Test-Connection "192.168.1.$_" -Count 1 -Quiet) { "192.168.1.$_" } }

This one makes use of the pipeline, and it'll still get you the information you want, but not quite as pretty on the output.

Password Generator

Did you know you could leverage PowerShell and a bit of .Net to generate complex passwords?

Take note of the two values in parenthesis at the end of the GeneratePassword command. The first number defines the length of the password, while the second number defines the number of characters to have which will be numbers or special characters.

Add-Type -Assembly System.Web
[Web.Security.Membership]::GeneratePassword(14,4)

Who's Running?

If you're anything like me, you might leverage the Windows task scheduler to automate some processes. You don't have to use the Task Scheduler GUI to get information about currently running tasks, though. This is easily accomplished with the Get-ScheduledTask cmdlet.

(get-scheduledtask).where({$_.state -eq 'running'})

Defender Scan

You can kick off a scan with Windows Defender using PowerShell:

Start-MpScan -ScanType QuickScan

Valid options for -ScanType are:

You can also specify a drive to scan with the -ScanPath switch.

Save Yourself

Let's say you have a script that performs some configuration changes to a computer, and you want to give yourself and automated safety net. You can use the built-in ability of Windows to create System Restore Points, utilizing the Checkpoint-Computer cmdlet.

Checkpoint-Computer -RestorePointType "Modify_Settings" -Description "Prior to Service Pack"

To get a list of restore points, you would use the Get-ComputerRestorePoint, as shown below:

PS C:\> Get-ComputerRestorePoint
CreationTime           Description                    SequenceNumber    EventType         RestorePointType
------------           -----------                    --------------    ---------         ----------------
4/7/2020 8:23:10 AM    Scheduled Checkpoint           19                BEGIN_SYSTEM_C... 7
4/14/2020 12:12:30 PM  Windows Update                 20                BEGIN_SYSTEM_C... 17

To restore to a particular checkpoint, use the Restore-Computer cmdlet:

Restore-Computer -RestorePoint 19

Note: you can only make one restore point every 24 hours with this method

Got a Quickie?

Have you got a quickie you'd like share? Drop a note in the comments below. Or, better yet, register for an account on this site, and you can do your own writeup, showing off your big ol' brain. ;)

About this post

Posted: 2020-04-22
By: dwirch
Viewed: 1,175 times

Categories

Scripting

Powershell

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.