PowerShell interview questions: pipeline, errors, functions and remoting
PowerShell interview questions check whether you think in objects rather than text: how the pipeline passes .NET objects between cmdlets, how to filter and shape them, and how errors behave when a command fails halfway through a list. Rounds for Windows, Microsoft 365, Azure and endpoint roles then move to remoting, credentials, safe changes with -WhatIf and writing a reusable advanced function.
By Evin JohnPublished 8 min read
Who gets asked PowerShell questions
PowerShell comes up for Windows and systems administrators, Microsoft 365 and identity admins, endpoint and Intune engineers, Azure cloud engineers, DevOps engineers on Windows estates, and blue-team security analysts who read attacker scripts. Interviews tend to mix three things: quick concept questions, a request to write a one-liner or a short function on a whiteboard or shared screen, and a scenario such as "report every server with low disk space" or "find accounts nobody has used in 90 days". If you come from bash, the shell scripting habits about quoting and exit codes still matter, but the core idea is different: you pass objects, not lines of text.
Fundamentals
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What makes the PowerShell pipeline different from a Unix pipe? | Core model | Cmdlets pass .NET objects, not text. Get-Process | Sort-Object CPU sorts on a real property, so no column cutting or regex is needed. Text appears only at the end, when objects are formatted for the screen. |
| How do you discover a command you have never used? | Self-sufficiency | Get-Command *service* to find it, Get-Help Restart-Service -Examples for usage, and piping the output to Get-Member to see its type, properties and methods. |
| Why do cmdlets follow Verb-Noun names? | Conventions | Approved verbs (Get, Set, New, Remove, Start, Test) make commands guessable and searchable. Get-Verb lists them, and modules that use unapproved verbs trigger a warning on import. |
| Windows PowerShell 5.1 versus PowerShell 7? | Versions | 5.1 is built on .NET Framework, ships in Windows and only gets fixes. PowerShell 7 runs on modern .NET, works on Windows, macOS and Linux, installs side by side as pwsh, and adds features such as ForEach-Object -Parallel, the ternary operator and the && and || chain operators. |
What is $_ (also $PSItem)? | Pipeline variable | The current object inside a script block that processes pipeline input, such as the filter of Where-Object or the body of ForEach-Object. |
| How do -eq, -like, -match and -contains differ? | Operators | -eq compares values, -like uses wildcards, -match uses a regular expression and fills $Matches, and -contains asks whether a collection holds a value (-in is the same with sides swapped). All are case-insensitive unless you use the c-prefixed forms such as -ceq. |
| What is a provider? | Navigation | An adapter that exposes a data store like a drive: the file system, the registry (HKLM:), environment variables (Env:), certificates (Cert:). The same Get-ChildItem and Set-Item work across them. |
| Arrays versus hashtables versus PSCustomObject? | Data types | An array is an ordered list, a hashtable maps keys to values, and [PSCustomObject]@{...} builds an object with named properties that formats, exports to CSV and pipes like any cmdlet output. |
| What is the execution policy? | Security basics | A setting that controls whether scripts load and whether they must be signed (Restricted, AllSigned, RemoteSigned, Unrestricted, Bypass). It guards against running scripts by accident; it is not a security boundary, since anyone can paste code into a session. |
Output prediction rounds like these three, because each catches a habit carried over from other languages.
$names = @('web01', 'web02', $null, 'db01')
$names -eq $null # filters: returns the $null element, not $true or $false
$null -eq $names # False: with $null on the left you get one Boolean
$total = 0
1..3 | ForEach-Object { $total += $_ }
"Total: $total" # Total: 6, the script block runs in the caller's scope
function Get-Two { 'starting'; return 2 }
$x = Get-Two
$x.Count # 2: every value a function emits is output, not only returnErrors, functions and modules
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Terminating versus non-terminating errors? | Error model | A non-terminating error is written to the error stream and the cmdlet moves on to the next item. A terminating error stops the pipeline. try/catch only catches the second kind, which is why -ErrorAction Stop matters inside try. |
| How do you check whether an external program like robocopy succeeded? | Native commands | Read $LASTEXITCODE, since a native exit code does not throw. Know the program's convention: robocopy uses codes below 8 for success with different meanings. |
| What does [CmdletBinding()] add to a function? | Advanced functions | Common parameters such as -Verbose, -ErrorAction and -Debug, the $PSCmdlet object, and with SupportsShouldProcess, -WhatIf and -Confirm. |
| How does a function accept pipeline input? | Pipeline binding | Mark a parameter ValueFromPipeline or ValueFromPipelineByPropertyName and put the work in a process block, which runs once per incoming object. begin and end run once before and after. |
| Name a few parameter validation attributes. | Input safety | Mandatory, ValidateSet for a fixed list, ValidateRange for numbers, ValidatePattern for a regex and ValidateScript for custom checks. They fail fast with a clear message before your code runs. |
| What is the difference between a script, a module and a manifest? | Packaging | A .ps1 runs top to bottom. A .psm1 module groups functions and controls exports. A .psd1 manifest declares version, dependencies, required PowerShell edition and exported commands, which publishing to a gallery requires. |
| What is scope, and what does dot-sourcing do? | Scoping | Scripts and functions get their own scope, so variables they set vanish when they end. Dot-sourcing (. .\helpers.ps1) runs the file in the current scope so its functions and variables stay. |
Why does "Skipping $root: failed" throw a parse error? | String expansion | The colon makes PowerShell read $root: as a scope or drive qualifier. Write ${root}: or use the format operator. Property access in strings needs a subexpression, $($file.Name). |
function Remove-OldFile {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[string[]]$Path,
[ValidateRange(1, 3650)]
[int]$OlderThanDays = 30
)
begin {
$cutoff = (Get-Date).AddDays(-$OlderThanDays)
$removed = 0
}
process {
foreach ($root in $Path) {
try {
$files = Get-ChildItem -LiteralPath $root -File -Recurse -ErrorAction Stop
}
catch {
Write-Warning "Skipping ${root}: $($_.Exception.Message)"
continue
}
foreach ($file in $files) {
if ($file.LastWriteTime -lt $cutoff -and
$PSCmdlet.ShouldProcess($file.FullName, 'Delete')) {
Remove-Item -LiteralPath $file.FullName -ErrorAction Stop
$removed++
}
}
}
}
end {
Write-Verbose "Removed $removed file(s) last written before $cutoff"
}
}
# Preview, then run for real:
# 'D:\Logs', 'E:\AppLogs' | Remove-OldFile -OlderThanDays 14 -WhatIf
# 'D:\Logs', 'E:\AppLogs' | Remove-OldFile -OlderThanDays 14 -VerboseObjects at work: reports and filtering
Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType = 3" |
Select-Object DeviceID,
@{ Name = 'SizeGB'; Expression = { [math]::Round($_.Size / 1GB, 1) } },
@{ Name = 'FreeGB'; Expression = { [math]::Round($_.FreeSpace / 1GB, 1) } },
@{ Name = 'FreePct'; Expression = { [math]::Round(100 * $_.FreeSpace / $_.Size) } } |
Where-Object FreePct -lt 15 |
Sort-Object FreePct |
Export-Csv -Path .\low-disk.csv -NoTypeInformation- Why filter left?
Get-ChildItem -Filter *.logor a CIM-Filterlets the provider or the remote system do the work. Piping everything to Where-Object first pulls every object across and then throws most away. - What is a calculated property? A hashtable with Name and Expression keys inside Select-Object, used to rename, convert units or derive a value per object.
- Select-Object versus Format-Table? Select-Object returns objects you can keep piping. Format-Table returns formatting instructions for the screen, so exporting or filtering after it produces junk.
- Why does ConvertTo-Json print type names instead of nested data? Its default depth is 2. Deeper objects get flattened to strings, so set -Depth explicitly; newer versions warn when they truncate.
- Why is `$results += $item` in a big loop slow? Arrays have a fixed size, so each += copies the whole array. Assign the loop's output to a variable (
$results = foreach (...) { ... }) or use a generic List. - ForEach-Object versus the foreach statement? The cmdlet streams one object at a time and keeps memory low. The statement loads the whole collection first and runs faster for data already in memory.
- When would you use ForEach-Object -Parallel? In PowerShell 7, for independent I/O-bound work such as querying many hosts. Each block runs in its own runspace, so outside variables need
$using:, and -ThrottleLimit caps concurrency.
Remoting, security and credentials
- How does PowerShell remoting work? Over WinRM (WS-Management) by default on Windows; PowerShell 7 can also remote over SSH.
Invoke-Command -ComputerNamefans one script block out to many machines in parallel and tags results with PSComputerName;Enter-PSSessiongives an interactive shell on one. - What is the double-hop problem? From a remote session you try to reach a third resource, such as a file share, and get access denied because your credentials were not delegated. Fixes include resource-based Kerberos constrained delegation, passing a credential explicitly, or CredSSP, which carries its own risk because it caches credentials on the remote host.
- Why CIM cmdlets instead of Get-WmiObject? The WMI cmdlets are not available in PowerShell 7. Get-CimInstance uses WS-Man by default, works through firewalls that allow WinRM and supports reusable CIM sessions.
- How do you handle credentials in scripts? Never hardcode them. Use Get-Credential interactively, a managed identity or service account for automation, or the SecretManagement module with a vault. A SecureString exported with ConvertFrom-SecureString on Windows is tied to that user and machine.
- What is Just Enough Administration (JEA)? A constrained remoting endpoint that lets a user run only approved commands with chosen parameters, often under a temporary virtual account, so help desk staff can restart a service without being local admins.
- What logging would you turn on for security? Script block logging, module logging and transcription, forwarded to a SIEM. Mention AMSI, which lets antivirus inspect script content after deobfuscation, and constrained language mode, which application control policies can enforce.
- How do you test PowerShell code? Pester for unit tests (Describe, It, Should, with mocks for cmdlets that touch real systems) and PSScriptAnalyzer for linting in CI.
Scenario questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| List user accounts that have not signed in for 90 days. | Active Directory | Search-ADAccount -AccountInactive with a 90-day TimeSpan and -UsersOnly, or Get-ADUser with lastLogonTimestamp. Mention that this attribute replicates with a lag of days, so treat the cutoff as approximate, and disable before deleting. |
| A script works in the console but fails as a scheduled task. | Context | Different user, no profile, a different working directory, mapped drives missing, execution policy for that account, or 32-bit versus 64-bit host. Log with Start-Transcript and use full paths. |
| Restart a service on 300 servers and report which ones failed. | Fan-out | Invoke-Command with a throttle limit, try/catch inside the script block that returns a status object per host, and a separate list of hosts that were unreachable from the -ErrorVariable. |
| A teammate's script deleted more than intended. | Safe change | Add SupportsShouldProcess, run with -WhatIf first, log every target before acting, and scope the filter tightly. Restore from backup and add a Pester test for the filter. |
| Automate Microsoft 365 user offboarding. | Cloud admin | The Microsoft Graph PowerShell SDK, an app registration with only the permissions needed, steps for blocking sign-in, revoking sessions, converting the mailbox and removing licenses, each logged and idempotent. |
| Make a module shareable across the team. | Engineering practice | A manifest with a version, Pester tests and PSScriptAnalyzer in CI, publishing to an internal repository, and semantic versioning so scripts can pin a known version. |
Fictional example
- Interviewer
- This script wraps Copy-Item in try/catch, the copy fails with a red error, and the catch never runs. Why?
- Candidate
- Copy-Item is writing a non-terminating error. It reports the failure for that item and keeps going, so from the pipeline's point of view nothing was thrown, and try only reacts to terminating errors. I would add -ErrorAction Stop to the Copy-Item call so the failure becomes terminating inside the try. I would not set the global preference to Stop for the whole script unless I meant it, because that changes every cmdlet. In the catch I would log the target path and the exception message, and decide per item whether to continue or rethrow. If the copy were done with robocopy instead, try/catch would not help at all; I would check its exit code instead.
How to prepare for PowerShell interview questions
- Install PowerShell 7 next to 5.1Run the same scripts in both and note what differs: missing WMI cmdlets, new operators, default encodings and module compatibility.
- Live in Get-Member for a weekPipe every new command's output to Get-Member before using it. Interviewers can tell when you guess property names.
- Write three advanced functionsOne that reads, one that changes something with -WhatIf support, and one that fans out to several machines. Add comment-based help and parameter validation to each.
- Practice error handling on purposePoint commands at missing paths and locked files, then catch them, log them and decide whether to continue. Repeat with a native executable and its exit code.
- Add testsWrite a Pester test with a mocked cmdlet and run PSScriptAnalyzer over your scripts; both come up in senior rounds.
For the other side of automation, see shell scripting interview questions. Windows admins are often asked to put a web front end behind a reverse proxy too, covered in Nginx interview questions, and Azure interview questions covers the cloud services many PowerShell scripts manage.
A useful drill is explaining a script line by line to someone who did not write it. Natively, an AI interview assistant on Mac and Windows, can transcribe that kind of mock round, read a function or a red error block from a screenshot, and surface a suggested explanation while you talk it through. On Pro or during the free trial it adds the résumé and job description you upload to what it knows, and every practice session keeps its transcript and notes for later review.
Questions people ask
What are common PowerShell interview questions?
How the object pipeline differs from text pipes, Get-Help and Get-Member, -eq versus -like versus -match, terminating versus non-terminating errors, advanced functions with -WhatIf, remoting with Invoke-Command, and the double-hop problem.
Why doesn't try/catch catch my PowerShell error?
Most cmdlet errors are non-terminating, so nothing is thrown. Add -ErrorAction Stop to the command inside try, or check $LASTEXITCODE for external programs.
What is the difference between Windows PowerShell and PowerShell 7?
Windows PowerShell 5.1 ships with Windows on .NET Framework and only receives fixes. PowerShell 7 runs on modern .NET across Windows, macOS and Linux, installs side by side as pwsh and gets the new features.
Is the PowerShell execution policy a security feature?
Only loosely. It stops scripts from running by accident and can require signatures, but it is not a security boundary because a user can still run code directly in a session.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
