Overview

22 Using someone else’s scripts

This chapter recognizes that most PowerShell users will borrow scripts from the internet and focuses on the practical skill of making someone else’s code your own. It uses intentionally imperfect, real‑world examples that may include techniques not yet covered, emphasizing a disciplined, line‑by‑line approach: identify and track variables, read help for unfamiliar commands, test small snippets safely (ideally in a VM), and avoid skipping any line you don’t understand. The goal is to quickly orient yourself in unfamiliar code, assess what it does, and decide where and how to tailor it for your environment.

The first example, Get-ADExistence, demonstrates a function that takes one or more computer names (including pipeline input) and checks Active Directory for corresponding computer accounts. Using the Begin/Process/End pattern, it loops through each name and wraps Get-ADComputer in a Try/Catch to distinguish “found” from “not found.” It compiles results into a hashtable, converts that into a custom object, and writes it to the pipeline, reporting the target name, whether the account is enabled, and whether it exists in AD. The walkthrough highlights how to read a parameter block, recognize pipeline behavior, and interpret Try/Catch/Finally flow, while prompting you to consider simple extensions such as writing results to text or CSV.

The lab script, Get-LastOn, investigates recent logon/logoff activity by querying the Security event log (commonly requiring Administrator rights). It parameterizes scope (computer name, maximum events, event IDs), filters for relevant records (for example, 4624 and 4647), and parses the message text to extract the account name and domain, building uniform objects with time, computer, ID, and domain for downstream sorting and deduplication. A noted issue (a blank computer column) and the invitation to predict potential errors reinforce the chapter’s method: read every line, use PowerShell help and examples, test thoughtfully, and adjust the script to suit your systems and requirements.

 Lab answer

The script file seems to define two functions that won’t do anything until called. At the end of the script is a command, Get-LastOn, which is the same name as one of the functions, so we can assume that’s what is executed. Looking at that function, you can see that it has numerous parameter defaults, which explains why nothing else needs to be called. The comment-based help also explains what the function does. The first part of this function is using Get-WinEvent:

If this were a new cmdlet, we’d look at help and examples. The expression seems to be returning a user defined maximum of events. After looking at the help for Get-WinEvent we see that the parameter -MaxEvents will return the maximum number of events sorted from newest to oldest. Therefore or variable of $MaxEvents comes from a parameter and has a default value of 5000. These event logs are then filtered by Where-Object, looking for two event log values (event ID of 4627 and 4647), also from the parameter.

Next it looks like something is done with each event log in the foreach loop. Here’s a potential pitfall:

In the foreach loop, it looks like other variables are getting set. The first one is taking the event object and piping it to something called parseEventmessage. This doesn’t look like a cmdlet name, but we did see it as one of the functions. Jumping to it, we can see that it takes a message as a parameter and splits each one into an array. We might need to research the –Split operator.

Each line in the array is processed by another foreach loop. It looks like lines are split again, and there is a try/catch block to handle errors. Again, we might need to read up on that to see how it works. Finally, there is an if statement, where it appears that if the split-up strings are not empty, then a variable called $props is created as a hash table or associative array. This function would be much easier to decipher if the author had included some comments. Anyway, the parsing function ends by calling New-Object, another cmdlet to read up on.

This function’s output is then passed to the calling function. It looks like the same process is repeated to get $domain.

Oh, look, another hash table and New-Object, but by now we should understand what the function is doing. This is the final output from the function and hence the script.

FAQ

What’s the safest way to start using a PowerShell script I found online?Do a line-by-line review. Identify each variable and what you think it contains, read help for every unfamiliar command, and test risky or unknown snippets in a VM. Don’t skip lines—confirm what each line does before running the whole script.
How does the -Computers parameter in Get-ADExistence accept input?It’s defined as [string[]] and marked Mandatory, ValueFromPipeline, and ValueFromPipelineByPropertyName. That means you can pass one or many names directly, pipe strings, or pipe objects that have a property named Computers (or an aliased name) to the function.
What are Begin, Process, and End blocks, and why is the work in Process?These blocks are part of an advanced function. Begin runs once before pipeline input, Process runs once per incoming item (ideal for per-computer work), and End runs once after all input is processed. The “meat” goes in Process so each piped value is handled correctly.
How does Try/Catch/Finally help in the AD existence check?Try attempts Get-ADComputer and Catch handles failures (for example, the computer isn’t in AD). Using -ErrorAction Stop ensures errors are caught. Finally runs regardless and outputs a consistent object so the pipeline keeps flowing.
Why build a hashtable and then a PSObject for output?Creating a hashtable of properties and converting it to a PSObject yields structured, predictable output. That makes it easy to sort, filter, export to CSV, or hand off to other commands without brittle text parsing.
What do I need installed for Get-ADExistence to work?You need Windows with the Active Directory module (for example, RSAT or AD DS tools) and network/permission access to query AD. The function relies on Get-ADComputer, which isn’t available on macOS/Linux or on Windows without the AD module.
How do I save the script’s results to a CSV or text file?Pipe the output to Export-Csv or Out-File. Examples: Get-ADExistence -Computers comp1,comp2 | Export-Csv .\results.csv -NoTypeInformation or Get-ADExistence comp1 | Format-Table | Out-File .\results.txt.
How can I quickly understand unfamiliar commands or syntax in a script?Use Get-Help Command -Full or -Online for documentation and examples, and Get-Command to discover parameter sets. Run small tests, use Get-Member to inspect objects, and search help/wildcards for keywords like if, [environment], or specific cmdlets.
What does the Get-LastOn lab script do, and what pitfalls should I expect?It reads the Security log (via Get-WinEvent) for recent logon/logoff events (IDs 4624 and 4647), parses the message text to extract account and domain, and outputs the results. You may need to run as Administrator, remote access may require rights, event IDs vary by OS, and the sample notes a “blank Computer” column bug to investigate.
What safety checks should I do before running someone else’s script?Verify the source and integrity, scan for risky commands (like Invoke-Expression, web downloads, or registry writes), and prefer -WhatIf/-Confirm where available. Test in a non-production VM, review required modules/permissions, and consider execution policy/signing requirements.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn PowerShell in a Month of Lunches, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn PowerShell in a Month of Lunches, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn PowerShell in a Month of Lunches, Fourth Edition ebook for free