PowerShell Interview Questions and Answers

Find 100+ PowerShell interview questions and answers to assess candidates’ skills in scripting, automation, system administration, cmdlets, and Windows environment management.
By
WeCP Team

As organizations automate infrastructure management, cloud operations, and system administration, recruiters must identify PowerShell professionals who can streamline operations through scripting and automation. With expertise in Windows administration, Azure automation, and cross-platform scripting, PowerShell specialists play a critical role in modern IT and DevOps environments.

This resource, "100+ PowerShell Interview Questions and Answers," is tailored for recruiters to simplify the evaluation process. It covers a wide range of topics—from PowerShell fundamentals to advanced automation and scripting practices, including cmdlets, pipelines, modules, and DSC.

Whether you're hiring System Administrators, DevOps Engineers, Cloud Engineers, or IT Automation Specialists, this guide enables you to assess a candidate’s:

  • Core PowerShell Knowledge: Cmdlets, pipelines, objects, variables, loops, functions, and error handling.
  • Advanced Skills: Writing reusable scripts and modules, remoting, Desired State Configuration (DSC), integrating with Azure/AWS, and automating infrastructure tasks.
  • Real-World Proficiency: Automating system administration, managing users and services, deploying resources, and monitoring environments efficiently.

For a streamlined assessment process, consider platforms like WeCP, which allow you to:

  • Create customized PowerShell assessments for administration, DevOps, or cloud automation roles.
  • Include hands-on tasks such as writing scripts, debugging automation workflows, or managing infrastructure through PowerShell.
  • Proctor exams remotely while ensuring integrity.
  • Evaluate results with AI-driven analysis for faster, more accurate decision-making.

Save time, enhance your hiring process, and confidently hire PowerShell professionals who can automate, manage, and scale IT operations from day one.

PowerShell Interview Questions

PowerShell – Beginner (1–40)

  1. What is PowerShell and how is it different from Command Prompt?
  2. What is a PowerShell cmdlet?
  3. Explain the basic structure of a cmdlet (Verb-Noun).
  4. What is PowerShell ISE?
  5. What is a PowerShell module?
  6. How do you list all available cmdlets?
  7. What is the purpose of Get-Help?
  8. How do you update the help files in PowerShell?
  9. What is Get-Command used for?
  10. What are PowerShell providers?
  11. What does the pipeline (|) do in PowerShell?
  12. How do you assign variables in PowerShell?
  13. What is the difference between single quotes and double quotes?
  14. How do you get the PowerShell version you are using?
  15. What is the purpose of Get-Service?
  16. How do you start and stop a service?
  17. How do you list running processes?
  18. What cmdlet retrieves event logs?
  19. What does Get-ExecutionPolicy do?
  20. How do you change the execution policy?
  21. How do you create a new directory using PowerShell?
  22. How do you list all files in a folder?
  23. What is the purpose of Get-Content?
  24. How do you read a CSV file in PowerShell?
  25. How do you export data to a CSV file?
  26. How do you write output to a file?
  27. What is Write-Host used for?
  28. What is Read-Host used for?
  29. How do you create a simple PowerShell function?
  30. What is the difference between function and script?
  31. How do you run a PowerShell script?
  32. What is PowerShell Remoting?
  33. What does Get-Alias do?
  34. How do you create a custom alias?
  35. What is tab completion?
  36. How do you stop a running script?
  37. What is the purpose of the Clear-Host cmdlet?
  38. How do you view environment variables?
  39. How do you install a module from the Gallery?
  40. What is the purpose of PowerShell profiles?

PowerShell – Intermediate (1–40)

  1. What is the difference between PowerShell 5.1 and PowerShell 7?
  2. What is the Common Parameter system in PowerShell?
  3. Explain how pipeline objects work internally.
  4. What is an advanced function?
  5. What are the CmdletBinding and Parameter attributes?
  6. Explain the different parameter types (mandatory, positional, pipeline input).
  7. What is splatting in PowerShell?
  8. How do you handle errors using Try/Catch/Finally?
  9. What is the difference between Write-Host, Write-Output, and Write-Verbose?
  10. What is $ErrorActionPreference?
  11. Explain PowerShell’s object-based pipeline.
  12. What is Format-Table and Format-List?
  13. What is the difference between Where-Object and Filter parameters?
  14. What are Script Blocks?
  15. What are calculated properties in PowerShell?
  16. How do you create a scheduled task with PowerShell?
  17. What is PowerShell remoting and WinRM?
  18. How do you use Enter-PSSession and Invoke-Command?
  19. Explain the difference between synchronous and asynchronous jobs.
  20. How do you create and manage background jobs?
  21. What are runspaces?
  22. How do you sign a PowerShell script?
  23. What is the difference between AllSigned and RemoteSigned execution policies?
  24. How do you work with JSON data in PowerShell?
  25. How do you work with XML data in PowerShell?
  26. How do you use the pipeline with Select-Object?
  27. What is the purpose of Get-Member?
  28. How do you handle null values in PowerShell?
  29. What is PowerShell DSC (Desired State Configuration)?
  30. What are DSC resources?
  31. What is the difference between push and pull DSC modes?
  32. How do you use the CIM cmdlets?
  33. What is the difference between WMI and CIM?
  34. How do you compare objects in PowerShell?
  35. What is PSDrive?
  36. How do you package and publish a module?
  37. How do you secure credentials using Get-Credential?
  38. What is the SecureString type?
  39. How do you suppress output in PowerShell?
  40. What is PowerShell transcript logging?

PowerShell – Experienced (1–40)

  1. Explain the internal architecture of PowerShell.
  2. Explain how the pipeline engine works under the hood.
  3. How does PowerShell handle object serialization/deserialization in remoting?
  4. Explain the internal process of command discovery.
  5. How does PowerShell resolve command precedence (alias → function → cmdlet → external)?
  6. Explain how PowerShell compiles script blocks into MSIL.
  7. What is the AST (Abstract Syntax Tree) in PowerShell?
  8. How do you analyze PowerShell code using AST?
  9. Explain runspace pools and when to use them.
  10. How do you implement multithreading using runspaces?
  11. Compare jobs, runspaces, and thread jobs.
  12. Explain the architecture of PowerShell DSC Local Configuration Manager.
  13. How does LCM handle configuration drift?
  14. How do you write custom DSC resources?
  15. Explain Just Enough Administration (JEA).
  16. How do you design least-privilege PowerShell remoting endpoints?
  17. Explain how implicit remoting works.
  18. What are PowerShell implicit module autoloading internals?
  19. How is garbage collection handled inside PowerShell scripts?
  20. Explain performance tuning strategies for large scripts.
  21. How do you profile PowerShell scripts?
  22. What is PSSnapin and how does it differ from modules?
  23. Explain the difference between using .NET classes and cmdlets.
  24. How do you call native APIs using Add-Type and P/Invoke?
  25. How does error handling differ between terminating and non-terminating errors?
  26. Explain internal working of $PSBoundParameters.
  27. How do you optimize pipeline-heavy workloads?
  28. What is the impact of using pipelines vs foreach loops on performance?
  29. How do you implement secure credential storage using DPAPI?
  30. Explain how PowerShell security descriptors work.
  31. How do you detect and block malicious PowerShell scripts?
  32. Explain ScriptBlock logging and module logging.
  33. How does the PowerShell Get-Help system work internally?
  34. Explain advanced module manifest design.
  35. What are cross-platform limitations of PowerShell 7?
  36. How do you integrate PowerShell with CI/CD pipelines?
  37. Explain how PowerShell handles large XML/JSON payloads.
  38. How do you write event-driven scripts using Register-ObjectEvent?
  39. How do you debug PowerShell remoting issues at protocol level?
  40. Explain PowerShell’s hosting API and how PowerShell is embedded inside applications.

PowerShell Interview Questions and Answers

Beginner (Q&A)

1. What is PowerShell and how is it different from Command Prompt?

PowerShell is a task automation and configuration management framework created by Microsoft.
It consists of:

  • A command-line shell
  • A scripting language
  • A .NET-based automation engine

PowerShell is object-oriented, meaning every output is a .NET object. These objects can be passed between commands through the pipeline, allowing for complex automation workflows.

How it differs from Command Prompt (CMD):

FeaturePowerShellCommand PromptOutput.NET objectsPlain textScriptingFull scripting languageBasic batch scriptsExtensibilitySupports modules, functions, classesVery limitedIntegrationDeep integration with Windows OS, WMI, CIM, .NETVery limitedRemote managementSupports PowerShell RemotingNo native remotingAutomationEnterprise-grade automationBasic task execution

PowerShell is designed for system administrators, DevOps engineers, and automation tasks, whereas CMD is suitable only for basic command execution.

2. What is a PowerShell cmdlet?

A PowerShell cmdlet (pronounced command-let) is a lightweight, specialized .NET class that performs a specific action.
Cmdlets are the core building blocks of PowerShell.

Key characteristics:

  • They follow a Verb-Noun naming convention (e.g., Get-Process, Set-Service).
  • They accept input and produce output as objects, not plain text.
  • They are executed inside the PowerShell runtime, not as external executables.
  • They support common parameters like -Verbose, -ErrorAction, -Debug.

Cmdlets are more powerful than traditional shell commands since they work with structured data, making automation more reliable.

3. Explain the basic structure of a cmdlet (Verb-Noun).

PowerShell enforces a standard naming format:

Verb-Noun

Example:

Get-Service
Set-ExecutionPolicy
New-Item
Remove-Process

Why this structure?

  • Keeps cmdlet names consistent and predictable.
  • Makes commands discoverable using Get-Command -Verb or -Noun.
  • Ensures clarity in automation scripts.

Examples of common verbs:

  • Get – retrieve data
  • Set – modify something
  • New – create something
  • Remove – delete something
  • Start – begin execution
  • Stop – end execution

Nouns should be singular, indicating which resource the cmdlet interacts with, such as:

Process, Service, Item, User.

This structure greatly improves readability and predictability in scripting.

4. What is PowerShell ISE?

PowerShell ISE (Integrated Scripting Environment) is a graphical editor provided by Microsoft for writing, testing, and debugging PowerShell scripts.

Key features:

  • Syntax highlighting
  • Auto-completion (IntelliSense)
  • Built-in debugger (breakpoints, step-through execution)
  • Script pane and console pane integration
  • Multi-line editing
  • Snippets support
  • Ability to run selected code blocks
  • Object explorers

ISE makes script development more efficient, especially for beginners.

Although ISE is deprecated in favor of Visual Studio Code, it is still widely used on Windows systems for quick script creation and testing.

5. What is a PowerShell module?

A PowerShell module is a package that contains PowerShell cmdlets, functions, scripts, DSC resources, or other components grouped together for reuse.

Modules make it easier to:

  • Organize scripts
  • Share code
  • Load specific functionality when required
  • Build automation frameworks

Module types include:

  • Script modules (.psm1)
  • Binary modules (.dll)
  • Manifest modules (.psd1)
  • Nested modules

Modules are stored in locations such as:

  • C:\Program Files\WindowsPowerShell\Modules
  • C:\Windows\System32\WindowsPowerShell\v1.0\Modules

They are loaded automatically when a cmdlet inside them is used (module auto-loading).

6. How do you list all available cmdlets?

You use the Get-Command cmdlet to list all cmdlets available in the current PowerShell session.

Example:

Get-Command

You can filter results:

  • List only cmdlets:
Get-Command -CommandType Cmdlet

List all commands containing “Service”:

Get-Command *Service*

List commands from a specific module:

Get-Command -Module Microsoft.PowerShell.Management

Get-Command provides a comprehensive view of all executable components in PowerShell, including functions, aliases, workflows, and applications.

7. What is the purpose of Get-Help?

Get-Help displays detailed documentation for cmdlets, functions, modules, scripts, and concepts in PowerShell.

It helps users understand:

  • What the command does
  • Syntax and parameters
  • Examples
  • Usage scenarios
  • Input and output types

Example:

Get-Help Get-Process

More detailed help:

Get-Help Get-Process -Detailed

Show full examples:

Get-Help Get-Process -Examples

Get-Help is essential for learning and mastering PowerShell since all commands follow a standard documentation format.

8. How do you update the help files in PowerShell?

You use the Update-Help cmdlet.

Example:

Update-Help

This command downloads the latest help files from Microsoft and installs them locally.

If you want help for a specific module:

Update-Help -Module Microsoft.PowerShell.Management

If running with restricted permissions:

Update-Help -Force

For offline environments:

  • Download help files using Save-Help
  • Install them on target machines using Update-Help -SourcePath

Keeping help updated ensures access to the most accurate and latest documentation.

9. What is Get-Command used for?

Get-Command is used to discover all commands available in PowerShell. It is one of the most important cmdlets during learning and troubleshooting.

It shows:

  • Cmdlets
  • Functions
  • Aliases
  • Scripts
  • Modules
  • External executables

Examples:

  • List cmdlets:
Get-Command -CommandType Cmdlet

Find commands by verb:

Get-Command -Verb Get

Find commands by noun:

Get-Command -Noun Service

It is often used for discovery when you don’t know the exact command name but know what action you want to perform.

10. What are PowerShell providers?

PowerShell providers are interfaces that allow access to different data stores in a uniform way, as if they were file systems.

Providers let you navigate and manipulate items such as:

  • File system
  • Registry keys
  • Environment variables
  • Certificates
  • Variables
  • Functions
  • Alias store

For example:

  • cd HKLM:\Software → navigate registry like folders
  • Get-ChildItem Env: → list environment variables
  • Get-ChildItem Cert:\ → browse certificates

Essentially, providers abstract complex data sources into a consistent structure, enabling easier scripting and automation.

11. What does the pipeline (|) do in PowerShell?

In PowerShell, the pipeline (|) is one of the most powerful features because it passes objects, not text, from one command to another.
This is a major difference from traditional shells (like CMD or Bash), which only pass raw text.

When you use the pipeline:

  • The output of the first command is passed as input to the next command.
  • Each element (object) in the output is processed individually.
  • The receiving cmdlet can work with structured data—not strings.

Example:

Get-Process | Where-Object { $_.CPU -gt 50 }

Here:

  • Get-Process outputs process objects.
  • They are passed through the pipeline to Where-Object, which filters based on CPU usage.

Benefits of the PowerShell pipeline:

  • Handles complex automation tasks easily.
  • Works with rich .NET objects.
  • More reliable than text parsing.
  • Enables chaining and modular scripting.

12. How do you assign variables in PowerShell?

In PowerShell, variables are assigned using the dollar sign ($) followed by the variable name.

Syntax:

$variableName = value

PowerShell variables are:

  • Dynamically typed (data type changes based on value)
  • Case-insensitive ($Name and $name are same)
  • Able to store any .NET object (string, int, arrays, custom objects, etc.)

Examples:

$name = "Aman"
$age = 25
$numbers = 1,2,3,4,5
$details = Get-Service

Variables can store:

  • Strings
  • Numbers
  • Arrays
  • Hashtables
  • Objects returned by cmdlets

PowerShell automatically interprets the variable’s type based on its assigned value.

13. What is the difference between single quotes and double quotes?

In PowerShell, single quotes and double quotes work differently when handling variables and escape sequences.

Single Quotes (' ')

  • Literal strings
  • No variable expansion
  • No interpretation of escape characters

Example:

$name = "Aman"
'Hello $name'

Output:

Hello $name

Double Quotes (" ")

  • Expand variables
  • Support escape sequences like " or `n (newline)

Example:

"Hello $name"

Output:

Hello Aman

Practical use cases

  • Use single quotes when you want the text unchanged.
  • Use double quotes when you want variable values or special characters processed.

14. How do you get the PowerShell version you are using?

You can check your PowerShell version using built-in variables and cmdlets.

Most common method:

$PSVersionTable

This displays a table containing:

  • PowerShell version
  • CLR version
  • Build version
  • OS platform information
  • Edition (Core or Desktop)

Example:

$PSVersionTable.PSVersion

Alternative commands:

Get-Host

or

$host.version

PowerShell 7+ also supports:

pwsh --version

These methods help identify compatibility for scripts, modules, and features.

15. What is the purpose of Get-Service?

Get-Service retrieves information about services installed on a Windows system.

It helps administrators:

  • Check service status (Running, Stopped, Paused)
  • View service names and display names
  • Pipeline service objects to other cmdlets
  • Monitor or troubleshoot system services

Example:

Get-Service

To find a specific service:

Get-Service -Name wuauserv

To filter running services:

Get-Service | Where-Object {$_.Status -eq 'Running'}

The output is a ServiceController object, which provides detailed service information.

16. How do you start and stop a service?

PowerShell provides dedicated cmdlets to control Windows services:

Start a service

Start-Service -Name "wuauserv"

Stop a service

Stop-Service -Name "wuauserv"

Restart a service

Restart-Service -Name "wuauserv"

Check status before starting

(Get-Service -Name "wuauserv").Status

PowerShell ensures safe service control with options like:

  • -Force to stop dependent services
  • Pipelining:
Get-Service Spooler | Stop-Service

Services can also be automated in scripts for maintenance and deployment tasks.

17. How do you list running processes?

The cmdlet used is:

Get-Process

It lists all processes currently running on the system.

Common usage:

Get-Process | Sort-Object CPU -Descending

To find a process by name:

Get-Process -Name "chrome"

To list only specific properties:

Get-Process | Select-Object Name, Id, CPU, StartTime

PowerShell returns process objects, which can be filtered, sorted, or piped into other commands such as:

Stop-Process -Id 1234

Get-Process is widely used for performance monitoring, automation, and troubleshooting.

18. What cmdlet retrieves event logs?

The primary cmdlet for retrieving event logs is:

Get-EventLog

Example:

Get-EventLog -LogName Application -Newest 20

However, it is older and Windows-specific.

The modern and recommended cmdlet is:

Get-WinEvent

Why Get-WinEvent is preferred:

  • Works with both classic and modern event logs
  • Supports advanced filtering
  • Faster performance
  • Supports XML queries

Example:

Get-WinEvent -LogName Security

Filtering by event ID:

Get-WinEvent -FilterHashtable @{LogName='System'; Id=10016}

This cmdlet is essential for auditing, diagnostics, and monitoring.

19. What does Get-ExecutionPolicy do?

Get-ExecutionPolicy shows the current execution policy that controls how PowerShell handles script execution.

Example:

Get-ExecutionPolicy

Possible policies:

  • Restricted – No scripts allowed
  • AllSigned – Only signed scripts allowed
  • RemoteSigned – Local scripts allowed, downloaded scripts must be signed
  • Unrestricted – Scripts allowed, but show warnings
  • Bypass – All scripts run with no warnings
  • Undefined – No policy set

Execution policy is a security layer, not a hardened protection mechanism.

It prevents accidental execution of untrusted scripts.

20. How do you change the execution policy?

You use the Set-ExecutionPolicy cmdlet.

Basic syntax:

Set-ExecutionPolicy RemoteSigned

To force the change:

Set-ExecutionPolicy RemoteSigned -Force

To apply only to the current user:

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

Scopes include:

  • Process – Affects only current PowerShell session
  • CurrentUser – Affects only current logged-in user
  • LocalMachine – Affects all users

Example for temporary change (session only):

Set-ExecutionPolicy Bypass -Scope Process

Changing execution policy requires understanding security implications, especially when running downloaded scripts.

21. How do you create a new directory using PowerShell?

To create a new directory (folder) in PowerShell, you can use either of the following cmdlets:

1. New-Item

New-Item -ItemType Directory -Path "C:\MyFolder"

This command explicitly tells PowerShell to create a directory-type item.

2. mkdir (alias for New-Item)

mkdir C:\MyFolder

3. New-Item with recursive creation

New-Item -ItemType Directory -Path "C:\Data\Logs\2024" -Force
  • -Force ensures nested directories are created even if some exist.

Key Points

  • PowerShell treats folders as items in the FileSystem provider.
  • You can also create multiple folders through pipelining:
"One","Two","Three" | ForEach-Object { New-Item -ItemType Directory -Path "C:\Test\$_" }

This flexibility helps in automation scenarios where dynamic folder structures must be created.

22. How do you list all files in a folder?

To list files in a folder, PowerShell uses the Get-ChildItem cmdlet.

Basic usage:

Get-ChildItem -Path "C:\MyFolder"

Alias:

ls C:\MyFolder

List only files (not folders)

Get-ChildItem -Path "C:\MyFolder" -File

List all files including hidden and system files

Get-ChildItem -Path "C:\MyFolder" -Force

List files recursively

Get-ChildItem -Path "C:\MyFolder" -Recurse

Filter files by extension

Get-ChildItem "C:\MyFolder" -Filter *.txt

PowerShell returns FileInfo objects, allowing further filtering, sorting, or exporting.

23. What is the purpose of Get-Content?

Get-Content is used to read the contents of:

  • Text files
  • Log files
  • Scripts
  • Configuration files
  • CSVs (raw text)
  • Any file readable as text

Basic usage:

Get-Content -Path "C:\MyFile.txt"

What it does

  • Reads file content line by line.
  • Returns each line as a string object.
  • Supports streaming for large files (efficient memory usage).

Additional features

Read last 10 lines:

Get-Content file.txt -Tail 10

Read file in real time (like Linux tail -f):

Get-Content file.txt -Wait

Read file as a single string:

Get-Content file.txt -Raw

Get-Content is essential for log analysis, configuration management, and script automation.

24. How do you read a CSV file in PowerShell?

To read CSV files, PowerShell provides the powerful cmdlet:

Import-Csv

Example:

Import-Csv -Path "C:\data\employees.csv"

How it works

  • Reads the CSV file.
  • Converts each row into a custom PowerShell object.
  • Column headers become object properties.

Example CSV:

Name,Age,City
Aman,25,Delhi
John,30,London

PowerShell usage:

$data = Import-Csv "employees.csv"
$data[0].Name

Filtering

Import-Csv "employees.csv" | Where-Object { $_.Age -gt 28 }

Selecting columns

Import-Csv "employees.csv" | Select-Object Name,City

This makes CSV import extremely useful for data manipulation, reporting, and automation tasks.

25. How do you export data to a CSV file?

PowerShell uses the Export-Csv cmdlet to export objects into a CSV format.

Basic usage:

Get-Process | Export-Csv -Path "C:\processes.csv" -NoTypeInformation

Key parameters

  • -NoTypeInformation removes unwanted metadata.
  • -Append adds data to an existing file.
  • -Force overwrites read-only files.

Example: Export custom data

$users = @(
    [PSCustomObject]@{Name="Aman"; Age=25}
    [PSCustomObject]@{Name="John"; Age=30}
)

$users | Export-Csv "C:\users.csv" -NoTypeInformation

Export selected properties

Get-Service | Select Name,Status | Export-Csv "services.csv" -NoTypeInformation

Export-Csv is widely used for reporting, automation, inventory generation, and audits.

26. How do you write output to a file?

PowerShell supports multiple ways to write output to a file.

1. Out-File

"Hello World" | Out-File "C:\test.txt"

2. Set-Content

Set-Content -Path "C:\test.txt" -Value "Hello World"

3. Add-Content (append to existing file)

Add-Content -Path "C:\test.txt" -Value "New line added"

4. Redirect operators

"Hello" > file.txt
"Append this" >> file.txt

5. Using Tee-Object

Write to console and file at same time:

Get-Process | Tee-Object -FilePath "output.txt"

These commands allow flexible file writing depending on the automation scenario.

27. What is Write-Host used for?

Write-Host is used to display output directly to the console, bypassing the PowerShell pipeline.

Example:

Write-Host "Hello World"

Characteristics

  • Direct output — cannot be captured or piped.
  • Used for UI messages, debug text, color-coded output.

Example with color:

Write-Host "Success!" -ForegroundColor Green

When to avoid it

  • In production-grade scripts
  • When output should be logged or piped

Write-Output is usually preferred if output needs to flow through the pipeline.

28. What is Read-Host used for?

Read-Host takes input from the user during script execution.

Basic usage:

$name = Read-Host "Enter your name"

Secure input (passwords)

$password = Read-Host "Enter password" -AsSecureString

Purpose

  • Interactive scripts
  • Prompting the user for decisions
  • Collecting credentials

However, for automation, prompting is discouraged; scripts should be non-interactive.

29. How do you create a simple PowerShell function?

A PowerShell function is created using the function keyword.

Basic structure:

function SayHello {
    Write-Output "Hello!"
}

Calling the function:

SayHello

Function with parameters

function GreetUser {
    param(
        [string]$Name
    )
    Write-Output "Hello, $Name!"
}

Calling:

GreetUser -Name "Aman"

Advanced function example

function Get-Square {
    [CmdletBinding()]
    param([int]$Number)

    return ($Number * $Number)
}

Functions improve script reusability and modularity.

30. What is the difference between function and script?

A PowerShell script is a .ps1 file that contains a sequence of commands.

Example:
Backup.ps1

A function is a block of code defined inside a script or session that performs a specific task.

Key Differences

FunctionScriptReusable code blockIndependent executable fileMust be defined before calling in scriptExecuted as a single fileDoes not need a file extensionRequires .ps1Can be stored in modulesStored as script filesLoaded into memoryRun separately each time

Example scenario

  • Use a script for complete automation tasks.
  • Use a function for repeatable logic inside scripts or modules.

Analogy

  • Script = entire program
  • Function = small reusable part of the program

31. How do you run a PowerShell script?

Running a PowerShell script involves understanding execution policy, file path, and script invocation methods.

1. Run script from current directory

If your script is in the current directory:

.\scriptname.ps1

PowerShell requires .\ to prevent accidental execution of untrusted scripts.

2. Run script from another directory

C:\Scripts\Backup.ps1

3. Run with full path via PowerShell executable

powershell.exe -File "C:\Scripts\Backup.ps1"

4. Run script with parameters

.\Backup.ps1 -Path "C:\Data" -Days 7

5. Run script bypassing policy (session only)

powershell.exe -ExecutionPolicy Bypass -File script.ps1

6. Ensure execution policy allows scripts

If you get "script is disabled":

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

Important Notes

  • Scripts must use .ps1 extension.
  • If running from network paths, signing may be required.
  • PowerShell 7 uses pwsh instead of powershell.

Running scripts is a fundamental skill for automation and task scheduling.

32. What is PowerShell Remoting?

PowerShell Remoting allows you to run PowerShell commands on remote computers.

It uses WS-Management (WinRM) protocol and is essential for automation across multiple machines.

Key capabilities

  • Execute commands remotely
  • Start interactive remote sessions
  • Run scripts simultaneously on multiple systems
  • Manage servers without RDP

Two main ways to use Remoting

1. Invoke-Command

Runs a command on remote computers:

Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Service }
2. Enter-PSSession

Starts an interactive remote shell:

Enter-PSSession -ComputerName Server01

Requirements

  • WinRM enabled:
Enable-PSRemoting
  • Correct network/firewall settings
  • Users with appropriate permissions

Advantages

  • Secure communication
  • Passes objects (not text) between machines
  • Essential for cloud/DevOps automation

PowerShell Remoting is one of the most powerful features for enterprise management.

33. What does Get-Alias do?

Get-Alias displays all aliases defined in the current PowerShell session.

Example:

Get-Alias

Aliases are shortcut names for cmdlets.
Examples:

AliasCmdletlsGet-ChildItemcpCopy-ItemmvMove-ItemrmRemove-Item

Filtering by name

Get-Alias ls

Filtering by cmdlet

Get-Alias -Definition Get-Process

Aliases make PowerShell more user-friendly, especially for those familiar with Linux or CMD.

34. How do you create a custom alias?

You create a custom alias using the Set-Alias cmdlet.

Example:

Set-Alias -Name gs -Value Get-Service

Now typing:

gs

Executes:

Get-Service

Alias for your own functions

function SayHello { Write-Output "Hello!" }
Set-Alias hi SayHello

Persistent alias

Aliases defined with Set-Alias exist only for the session.
To make them permanent, add them to your PowerShell profile:

Set-Alias gs Get-Service

inside:

$PROFILE

Why create custom aliases?

  • Shorten long command names
  • Speed up frequently used tasks
  • Improve productivity in interactive shells

35. What is tab completion?

Tab completion is a PowerShell usability feature that helps you automatically complete:

  • Cmdlet names
  • Parameter names
  • Module names
  • File paths
  • Variables
  • Function names

When typing a command, pressing TAB cycles through available matches.

Examples:

Cmdlet name completion

Typing:

Get-Ser[TAB]

Completes to:

Get-Service

File path completion

cd C:\Prog[TAB]

Expands to:

C:\Program Files

Parameter completion

Get-Process -N[TAB]

Becomes:

Get-Process -Name

Benefits

  • Saves time
  • Reduces errors
  • Improves command discoverability

Tab completion is one of the best features for beginners and experts alike.

36. How do you stop a running script?

PowerShell scripts can be stopped using several methods depending on how they are running.

1. Keyboard interrupt

Press:

Ctrl + C


This immediately stops script execution.

2. Manually stop from PowerShell ISE or VS Code

  • PowerShell ISE: Click Stop button
  • VS Code: Click Stop Debugging

3. Stop a script inside the code

Use:

break

or

return

or forcefully:

throw "Stopping script!"

4. Kill a running PowerShell process

Stop-Process -Name powershell

5. Stop long running loops

Ctrl + Break

Stopping scripts is important for error handling, debugging, and safely terminating automation tasks.

37. What is the purpose of the Clear-Host cmdlet?

Clear-Host (alias: cls) clears the PowerShell console screen.

Example:

Clear-Host

What it does

  • Removes all previous command output from view
  • Provides a clean working console
  • Useful during demos, learning, presentations, or debugging

When used?

  • Before displaying new output
  • When the console becomes cluttered
  • To improve readability of scripts
  • During looping outputs or long automation tasks

It's a simple but helpful cmdlet for maintaining a clean workspace.

38. How do you view environment variables?

PowerShell accesses environment variables through the Env: provider.

1. List all environment variables

Get-ChildItem Env:

2. View specific variable

$Env:PATH

3. Set a new environment variable

$Env:MyVariable = "TestValue"

4. Remove an environment variable

Remove-Item Env:MyVariable

Filtering

Get-ChildItem Env: | Where-Object { $_.Name -like "*PATH*" }

Environment variables are used for configuring application paths, credentials, system settings, and automation tasks.

39. How do you install a module from the Gallery?

PowerShell modules can be installed from the PowerShell Gallery using Install-Module.

Example:

Install-Module -Name Az

Install with admin rights

Install-Module -Name PSReadLine -Scope AllUsers

Install without admin rights

Install-Module -Name PSReadLine -Scope CurrentUser

Update a module

Update-Module -Name Az

Find available modules

Find-Module -Name *Azure*

Prerequisite

PowerShellGet module must be installed and configured.

Module installation allows extending PowerShell functionality with:

  • Cloud tools
  • Administration modules
  • Automation toolkits
  • Security modules

40. What is the purpose of PowerShell profiles?

A PowerShell profile is a startup script that runs every time a new PowerShell session opens.

It allows you to personalize and configure your environment.

View profile path:

$PROFILE

Common purposes

  • Define aliases
  • Load custom functions
  • Set environment variables
  • Customize the prompt
  • Import modules automatically
  • Set default directory
  • Automate session startup tasks

Example profile content

Set-Alias ll Get-ChildItem
Import-Module Az
function Hello { Write-Output "Welcome, Aman!" }

Profile types

  • Current user, current host
  • All users, current host
  • Current user, all hosts
  • All users, all hosts

Profiles are extremely useful for building a productive and personalized automation environment.

Intermediate (Q&A)

1. What is the difference between PowerShell 5.1 and PowerShell 7?

PowerShell 5.1 and PowerShell 7 differ significantly in platform support, performance, architecture, and capabilities.

Platform

  • PowerShell 5.1 is Windows-only and built on the full .NET Framework.
  • PowerShell 7 is cross-platform (Windows, Linux, macOS) and built on .NET Core / .NET 7+.

Performance

  • PowerShell 7 is much faster due to:
    • .NET Core improvements
    • Pipeline parallelization
    • Reduced startup overhead

New Features in PowerShell 7

  1. Parallel pipelines with ForEach-Object -Parallel
1..10 | ForEach-Object -Parallel { $_ * 2 }

Ternary conditional operator

$result = $age -gt 18 ? "Adult" : "Minor"

Null-coalescing operator

$message = $value ?? "DefaultValue"
  1. Improved error handling with ConciseView
  2. Automatic compatibility module loading (WindowsCompatibility module)
  3. SSH-based remoting support

Backward Compatibility

  • PowerShell 5.1 runs older Windows modules natively.
  • PowerShell 7 uses WindowsCompatibility to import older modules.

Lifecycle

  • PowerShell 7 is actively developed.
  • PowerShell 5.1 receives only security fixes.

Summary:
PowerShell 7 is faster, cross-platform, modern, and more powerful, while PowerShell 5.1 remains essential for legacy Windows modules.

2. What is the Common Parameter system in PowerShell?

Common parameters are automatically available in almost all PowerShell cmdlets, functions, and scripts.

They allow consistency across commands and provide advanced control for:

  • Output behavior
  • Debugging
  • Error handling
  • Logging
  • Verbosity

Most important common parameters

ParameterPurpose-VerboseShows detailed internal operation messages-DebugPrompts for debug information-ErrorActionControls error behavior (Continue, Stop, Silence, Ignore)-ErrorVariableStores errors in a variable-OutVariableStores output in a variable-OutBufferControls paging output-WarningActionControls warnings

Example:

Get-Service -Verbose

Common parameters are implemented via PowerShell’s CmdletBinding attribute and inherited by most commands.

3. Explain how pipeline objects work internally.

PowerShell’s pipeline does not pass plain text—it passes .NET objects.

Pipeline Stages

  1. Command 1 produces objects
Get-Process
  • Produces Process objects.
  • Objects are streamed (one at a time) into the next command.
  • Command 2 receives each object via parameter binding
  • Where-Object { $_.CPU -gt 10 }
    
    1. PowerShell binder maps object properties to parameters (by name or by value).

    Two types of bindings

    • ByValue: Direct type match
    • ByPropertyName: Property name matches parameter name

    Example:

    Get-Service | Stop-Service
    

    Here, Get-Service outputs a ServiceController object.
    Stop-Service accepts InputObject, so pipeline binding works.

    Key internal concepts

    • Pipeline processes one object at a time, reducing memory usage.
    • Each object is passed through multiple pipeline commands until it exits the pipeline.
    • ForEach-Object uses script blocks to process each item.

    Why pipeline is powerful

    • Structured object flow
    • Efficient resource usage
    • Clear, readable commands
    • Complex transformations with minimal code

    4. What is an advanced function?

    An advanced function is a PowerShell function that behaves like a full cmdlet.

    It includes:

    • CmdletBinding attribute
    • Rich parameter support
    • Common parameters
    • Pipeline input
    • Parameter validation

    Example:

    function Get-UserInfo {
        [CmdletBinding()]
        param(
            [Parameter(Mandatory)]
            [string]$Name
        )
        Write-Output "User: $Name"
    }
    

    Advantages of advanced functions

    • Support for -Verbose, -Debug, -ErrorAction
    • Accept pipeline input
    • Parameter validation (ValidateSet, ValidateRange)
    • Cmdlet-like structure
    • Automatic help documentation support

    Advanced functions are building blocks for professional modules.

    5. What are the CmdletBinding and Parameter attributes?

    CmdletBinding

    Enables cmdlet-like behavior in functions.

    Example:

    [CmdletBinding()]
    

    What it enables:

    • Common parameters
    • Advanced parameter binding
    • Pipeline support
    • Verbose/debug logging
    • Remoting compatibility

    Parameter Attribute

    Used to define metadata for parameters.

    Example:

    [Parameter(Mandatory, ValueFromPipeline)]
    [string]$Name
    

    Properties of Parameter Attribute:

    • Mandatory – requires user input
    • Position – positional argument index
    • ValueFromPipeline – accepts pipeline input by value
    • ValueFromPipelineByPropertyName – property matching
    • HelpMessage – help prompts

    These attributes make functions powerful and professional-grade.

    6. Explain the different parameter types (mandatory, positional, pipeline input).

    PowerShell parameters can be configured to behave in multiple ways.

    1. Mandatory Parameters

    Require user input.

    param(
        [Parameter(Mandatory)]
        $Name
    )
    

    If not supplied, PowerShell prompts the user.

    2. Positional Parameters

    Users don't need to type the parameter name.

    Get-Process chrome
    

    Instead of:

    Get-Process -Name chrome
    

    You define a positional index:

    [Parameter(Position=0)]
    

    3. Pipeline Input Parameters

    a. ValueFromPipeline

    Accepts entire objects.

    [Parameter(ValueFromPipeline)]
    $InputObject
    

    Example:

    Get-Service | Stop-Service
    
    b. ValueFromPipelineByPropertyName

    Property matches parameter name.

    [Parameter(ValueFromPipelineByPropertyName)]
    [string]$Name
    

    Matches when object contains .Name.

    These parameter types control how flexible and user-friendly functions and cmdlets can be.

    7. What is splatting in PowerShell?

    Splatting allows you to pass a set of parameters to a cmdlet/function using a hashtable or an array, instead of typing each parameter manually.

    Hashtable splatting (named parameters)

    $params = @{
        Name = "Aman"
        Age = 25
        City = "Delhi"
    }
    
    New-User @params
    

    Array splatting (positional parameters)

    $args = "Aman", 25, "Delhi"
    New-User @args
    

    Benefits of splatting

    • Cleaner code
    • Easier to read
    • Easier to build dynamic parameters
    • Reduces typing errors

    Splatting is especially useful in complex scripts and automation frameworks.

    8. How do you handle errors using Try/Catch/Finally?

    PowerShell supports structured error handling similar to other programming languages.

    Basic structure

    try {
        # Code that may fail
    }
    catch {
        # Handling error
    }
    finally {
        # Always runs
    }
    

    Example

    try {
        Get-Item "C:\missingfile.txt" -ErrorAction Stop
    }
    catch {
        Write-Output "File not found!"
    }
    finally {
        Write-Output "Operation complete."
    }
    

    Key points

    • Must use -ErrorAction Stop to convert non-terminating errors into terminating ones.
    • Catch can filter specific exceptions:
    catch [System.IO.FileNotFoundException]
    
    • Finally always executes regardless of success or failure.

    Try/Catch/Finally creates robust, fault-tolerant scripts.

    9. What is the difference between Write-Host, Write-Output, and Write-Verbose?

    Write-Host

    • Writes directly to the console.
    • Does NOT return objects to the pipeline.
    • Should be used only for UI output.
    Write-Host "Hello" -ForegroundColor Yellow
    

    Write-Output

    • Sends output to the pipeline.
    • Can be captured, stored, redirected.
    Write-Output "Hello"
    

    Write-Verbose

    • Sends detailed debug-style information.
    • Only visible if the user provides -Verbose.
    Write-Verbose "Processing file..."
    

    Calling:

    Get-Data -Verbose
    

    Summary Table

    CmdletGoes to PipelineRequires SwitchUse CaseWrite-Host❌ No❌Console UIWrite-Output✔ Yes❌Actual script outputWrite-Verbose❌ No✔ Yes (-Verbose)Debugging, logging

    10. What is $ErrorActionPreference?

    $ErrorActionPreference controls how PowerShell handles non-terminating errors.

    Possible Values

    ValueMeaningContinue (default)Show error, continue executionStopConvert all errors into terminating errorsSilentlyContinueSuppress error messagesIgnoreIgnore completely (no error logged)InquireAsk user what to doSuspendUsed in workflows

    Example

    $ErrorActionPreference = "Stop"
    
    Get-Item "C:\nofile.txt"
    

    Now the script halts on error.

    Per-command override

    Get-Item "C:\nofile.txt" -ErrorAction SilentlyContinue
    

    $ErrorActionPreference is essential for controlling script behavior in error-prone environments.

    11. Explain PowerShell’s object-based pipeline.

    PowerShell’s pipeline is fundamentally different from traditional shells (like CMD or Bash). Instead of passing text between commands, PowerShell passes rich .NET objects.

    How it works

    1. A cmdlet produces objects
      Example:
    Get-Process
    
    1. This outputs System.Diagnostics.Process objects.
    2. The pipeline streams objects one at a time to the next command.
      • Reduces memory usage.
      • Allows real-time processing.
    3. The receiving cmdlet binds parameters via advanced pipeline binding:
      • ByValue (matching object type)
      • ByPropertyName (matching property name)
    4. Each cmdlet operates on entire objects, not raw text.

    Benefits

    • High reliability (no fragile text parsing)
    • Better error handling
    • Strong typing
    • Fine-grained automation
    • Easier data manipulation

    Example

    Get-Service | Where-Object { $_.Status -eq "Running" } | Select-Object Name,Status
    

    Each stage receives structured objects, enabling powerful filtering, transformation, and reporting.

    12. What is Format-Table and Format-List?

    PowerShell includes formatting cmdlets used to control how output appears on the screen.

    Format-Table (FT)

    Displays data in a row-and-column table.

    Example:

    Get-Process | Format-Table Name, CPU, Id
    

    Useful for:

    • Comparing multiple objects side-by-side
    • Tabular views (like output of Get-Process)
    • Compact summaries

    Format-List (FL)

    Displays each object in a property-per-line format.

    Example:

    Get-Service | Format-List *
    

    Useful when:

    • Objects have many properties
    • Detailed data is needed

    Key rule: “Format cmdlets should be used only at the end of the pipeline.”

    Wrong:

    Get-Service | Format-Table | Export-Csv
    

    Format cmdlets produce formatting instructions, not raw objects—so they break downstream commands.

    Correct:

    Get-Service | Select Name,Status | Export-Csv file.csv
    

    13. What is the difference between Where-Object and Filter parameters?

    Both are used for filtering, but they differ in performance and how they execute.

    Where-Object

    Executed after the cmdlet has retrieved all objects.

    Syntax:

    Get-Process | Where-Object { $_.CPU -gt 10 }
    

    Characteristics:

    • Operates in the pipeline.
    • Slower for large datasets.
    • Flexible and can evaluate any expression.

    Filter parameters

    Executed before objects enter the pipeline.

    Example:

    Get-ADUser -Filter { Name -like "*John*" }
    Get-ChildItem -Filter *.txt
    

    Characteristics:

    • Filtering done at the source
    • Much faster
    • Reduces data returned

    When to use what?

    Use CaseRecommendationLarge data setsFilter parameterNeed complex logicWhere-ObjectData source supports filtering (AD, FileSystem)Filter parameterScripted filtering in pipelineWhere-Object

    Where-Object = flexible
    Filter parameter = faster

    14. What are Script Blocks?

    A script block is a block of executable code enclosed in {}.

    Example:

    { Write-Host "Hello" }
    

    Script blocks are first-class objects, meaning they can be:

    • Stored in variables
    • Executed dynamically
    • Passed to cmdlets
    • Used in loops
    • Used in event handling

    Execute a script block

    $block = { param($x) $x * 2 }
    & $block 10
    

    Common usage

    • In Where-Object:
    Where-Object { $_.Status -eq "Running" }
    

    In ForEach-Object:

    ForEach-Object { $_.Name }
    
    • In Try/Catch blocks
    • Creating dynamic code
    • Remoting (Invoke-Command)

    Script blocks provide PowerShell with high flexibility and dynamic execution capabilities.

    15. What are calculated properties in PowerShell?

    Calculated properties allow you to create new dynamic properties when using Select-Object or Format cmdlets.

    Syntax:

    @{Name='NewProperty'; Expression={ <script block> }}
    

    Example 1: Calculate memory in MB

    Get-Process | Select-Object Name,
        @{Name='MemoryMB'; Expression = { $_.WorkingSet / 1MB }}
    

    Example 2: Full name from first and last

    Get-ADUser -Filter * | Select-Object 
        @{Name='FullName'; Expression={ "$($_.GivenName) $($_.Surname)" }}
    

    Example 3: Status label

    Get-Service | Select Name,
        @{Name='StatusLabel'; Expression={ if ($_.Status -eq 'Running') {'Active'} else {'Inactive'} }}
    

    Calculated properties are incredibly powerful for reporting, data shaping, and generating custom output.

    16. How do you create a scheduled task with PowerShell?

    PowerShell provides cmdlets from the ScheduledTasks module.

    Step 1: Create an action

    $action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\Scripts\Backup.ps1"
    

    Step 2: Create a trigger

    $trigger = New-ScheduledTaskTrigger -Daily -At 3am
    

    Step 3: Register the scheduled task

    Register-ScheduledTask -TaskName "DailyBackup" -Action $action -Trigger $trigger -Description "Daily backup at 3am"
    

    Run as SYSTEM

    Register-ScheduledTask -TaskName "MyTask" -Action $action -Trigger $trigger -User "SYSTEM"
    

    View tasks

    Get-ScheduledTask
    

    Run immediately

    Start-ScheduledTask -TaskName "DailyBackup"
    

    This allows automation of recurring maintenance tasks.

    17. What is PowerShell remoting and WinRM?

    PowerShell Remoting enables executing commands/scripts on remote computers.

    It is built on the WinRM (Windows Remote Management) protocol, which uses:

    • WS-Management
    • HTTP/HTTPS
    • Secure encrypted communication

    Features

    • Remote interactive sessions
    • Remote execution of scripts
    • Parallel execution on multiple machines
    • Object-based data transfer

    Enable Remoting

    Enable-PSRemoting -Force
    

    WinRM responsibilities

    • Authentication (Kerberos, NTLM, CredSSP)
    • Session management
    • Encryption
    • Protocol handling

    PowerShell Remoting is essential for enterprise administration and automation across large environments.

    18. How do you use Enter-PSSession and Invoke-Command?

    Both are used for remoting, but serve different purposes.

    Enter-PSSession

    Creates an interactive remote session.

    Enter-PSSession -ComputerName Server01
    

    Inside the session, you work as if you are on the remote machine.

    Exit using:

    Exit-PSSession
    

    Invoke-Command

    Runs a script block non-interactively on one or many remote systems.

    Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Service }
    

    Run a script on multiple servers

    Invoke-Command -ComputerName Server01, Server02, Server03 -ScriptBlock { hostname }
    

    Pass local variables to remote machine

    $Name = "Test"
    Invoke-Command -ComputerName Server01 -ScriptBlock { param($x) Write-Output $x } -ArgumentList $Name
    

    Persistent Sessions

    $s = New-PSSession -ComputerName Server01
    Invoke-Command -Session $s -ScriptBlock { Get-Process }
    Remove-PSSession $s
    

    19. Explain the difference between synchronous and asynchronous jobs.

    PowerShell supports two execution models:

    Synchronous Execution

    • The command runs in the same session.
    • PowerShell waits for it to finish before moving to the next line.
    • Default behavior.

    Example:

    Get-Process
    

    Advantages

    • Simpler
    • Direct output
    • Good for short tasks

    Asynchronous Execution (Jobs)

    • Command runs in the background.
    • The prompt returns immediately.
    • You collect results later.

    Example:

    Start-Job -ScriptBlock { Get-Process }
    

    Advantages

    • Long-running tasks
    • Parallel execution
    • Don’t block the console

    Summary Table

    FeatureSynchronousAsynchronousBlockingYesNoOutputImmediateRetrieved laterBest forShort tasksLong-running tasksExecutionSame sessionSeparate process/runspace

    20. How do you create and manage background jobs?

    PowerShell provides multiple job types:

    • Background jobs
    • Thread jobs
    • PSSession jobs
    • Scheduled jobs

    Here’s how to manage standard background jobs.

    1. Create a background job

    Start-Job -ScriptBlock { Get-Process }
    

    2. Check job status

    Get-Job
    

    3. Receive job output

    Receive-Job -Id 1
    

    Receive without removing

    Receive-Job -Id 1 -Keep
    

    4. Stop a job

    Stop-Job -Id 1
    

    5. Remove a job

    Remove-Job -Id 1
    

    6. Wait for job to complete

    Wait-Job -Id 1
    

    7. Run multiple background jobs

    1..5 | ForEach-Object {
        Start-Job -ScriptBlock { Start-Sleep -Seconds 5; $_ }
    }
    

    8. Using Thread Jobs (faster and lighter)

    Start-ThreadJob -ScriptBlock { Get-Date }
    

    Background jobs are essential for parallelization, large-scale automation, and long-running tasks.

    21. What are runspaces?

    A runspace is the underlying PowerShell execution environment where PowerShell commands are run.
    Every PowerShell session consists of at least one runspace, but advanced automation scenarios often require multiple runspaces for parallel execution.

    Why runspaces exist

    • PowerShell runs on top of the .NET runtime.
    • A runspace represents the PowerShell engine instance inside a process.
    • It contains:
      • Pipeline
      • Variables
      • Modules
      • Functions
      • Language mode
      • Execution context

    How runspaces differ from jobs

    FeatureRunspacesJobsSpeedVery fast (in-memory threads)Slower (child PowerShell process)Resource usageLow (threads)Higher (process-per-job)ComplexityHigherLower

    When runspaces are used

    • High-performance automation
    • Multi-threaded scripts
    • GUI applications with PowerShell (WPF/WinForms)
    • Background operations inside modules
    • Tools requiring concurrency (scanning, monitoring)

    Example of creating a simple runspace

    $runspace = [runspacefactory]::CreateRunspace()
    $runspace.Open()
    

    Runspaces give developers fine-grained control and better performance than jobs.

    22. How do you sign a PowerShell script?

    Signing a script ensures that it is trusted and has not been modified, especially under stricter execution policies.

    Step 1: Get or create a code-signing certificate

    Use a trusted CA or create a test certificate:

    New-SelfSignedCertificate -Type CodeSigningCert -Subject "CN=MyCodeSigning"
    

    Step 2: Export certificate to store

    Typically stored in Cert:\CurrentUser\My.

    Step 3: Sign the script

    Set-AuthenticodeSignature -FilePath "C:\Scripts\Backup.ps1" -Certificate $cert
    

    Set-AuthenticodeSignature -FilePath "C:\Scripts\Backup.ps1" -Certificate $cert

    Set-AuthenticodeSignature -FilePath "C:\Scripts\Backup.ps1" -Certificate $cert
    

    Step 4: Verify the signature

    Get-AuthenticodeSignature C:\Scripts\Backup.ps1
    

    Why signing is important

    • Required for AllSigned policy.
    • Prevents tampering.
    • Ensures compliance/security.
    • Allows safe distribution across enterprises.

    Script signing is critical in secure and enterprise-based PowerShell environments.

    23. What is the difference between AllSigned and RemoteSigned execution policies?

    PowerShell execution policies determine how scripts are allowed to run.

    AllSigned

    • All scripts must be signed, regardless of origin.
    • Even local scripts require a trusted signature.
    • Helps ensure no script can run unless trusted.

    Ideal for:

    • Enterprise environments
    • High compliance systems
    • Secure servers

    RemoteSigned

    • Scripts downloaded from the internet must be signed.
    • Local scripts do not need to be signed.
    • Includes email attachments, browser downloads, files tagged with Zone.Identifier.

    Ideal for:

    • Developers
    • Admins writing their own scripts
    • Less restrictive environments

    Comparison Table

    PolicyLocal ScriptsInternet ScriptsSecurityAllSignedMust be signedMust be signedHighestRemoteSignedAllowed unsignedMust be signedMedium

    24. How do you work with JSON data in PowerShell?

    PowerShell provides two primary cmdlets for working with JSON:

    • ConvertFrom-Json → JSON → PowerShell object
    • ConvertTo-Json → PowerShell object → JSON

    Convert JSON to PowerShell object

    $json = Get-Content "data.json" -Raw
    $data = $json | ConvertFrom-Json
    $data.Name
    $data.Address.City
    

    The result is a custom object with properties matching the JSON keys.

    Convert object to JSON

    $object | ConvertTo-Json -Depth 5
    

    Depth is important for nested objects.

    Create JSON and save it

    $person = [PSCustomObject]@{
        Name = "Aman"
        Age = 25
    }
    $person | ConvertTo-Json | Set-Content "person.json"
    

    Common uses

    • Config files
    • APIs
    • Cloud automation (Azure, AWS)
    • Infrastructure-as-code

    JSON handling is easy and powerful in PowerShell due to native serialization support.

    25. How do you work with XML data in PowerShell?

    PowerShell can treat XML as a typed .NET XML document, making navigation and manipulation very easy.

    Load XML

    [xml]$xml = Get-Content "config.xml"
    

    Access elements

    $xml.settings.database.server
    

    Modify XML

    $xml.settings.database.server = "NewServer"
    $xml.Save("config.xml")
    

    Create XML

    $xml = New-Object System.Xml.XmlDocument
    $xml.LoadXml("<root><name>Aman</name></root>")
    

    XPath queries

    $xml.SelectNodes("//server")
    $xml.SelectSingleNode("//database/name")
    

    Convert object to XML

    $xml = $object | ConvertTo-Xml
    

    XML is widely used in:

    • Config files
    • DSC configurations
    • Legacy systems
    • Web services

    26. How do you use the pipeline with Select-Object?

    Select-Object is used to select properties or create calculated ones from pipeline objects.

    Select specific properties

    Get-Process | Select-Object Name, Id, CPU
    

    Select first N items

    Get-Service | Select-Object -First 5
    

    Use calculated properties

    Get-Process | Select-Object Name,
        @{Name="MemoryMB"; Expression={ $_.WorkingSet / 1MB }}
    

    Select unique values

    Get-ChildItem | Select-Object Extension -Unique
    

    Pass objects to next command

    Select-Object does not break objects (unlike Format-Table), so further processing is allowed:

    Get-Process | Select Name, Id | Export-Csv file.csv
    

    27. What is the purpose of Get-Member?

    Get-Member reveals the type, properties, and methods of any PowerShell object.

    Basic usage

    Get-Process | Get-Member
    

    Shows:

    • Object type (e.g., System.Diagnostics.Process)
    • Properties (Name, CPU, Id, etc.)
    • Methods (Kill(), Refresh(), etc.)
    • Script properties
    • Note properties

    Inspect a single object

    (Get-Item C:\test.txt) | Get-Member
    

    Filter members

    Get-Service | Get-Member -MemberType Property
    

    Why Get-Member is powerful

    • Helps discover object structure
    • Enables custom formatting
    • Essential for scripting
    • Needed for calculated properties

    It is one of PowerShell’s most important learning and discovery tools.

    28. How do you handle null values in PowerShell?

    Handling null values is essential for writing safe scripts.

    Check for null

    if ($value -eq $null) { "Value is null" }
    

    Null coalescing operator (PowerShell 7+)

    $result = $value ?? "Default Value"
    

    Avoid null reference errors

    $value?.Property
    

    Set default if empty or null

    if ([string]::IsNullOrEmpty($value)) { $value = "Default" }
    

    Filter null results

    Filter null results

    Use try/catch for null operations

    try { $value.Property } catch { "Error due to null" }
    

    Null handling prevents runtime errors and improves script reliability.

    29. What is PowerShell DSC (Desired State Configuration)?

    DSC is a configuration management platform in PowerShell used to define and maintain the desired state of systems.

    Instead of writing scripts that describe how to configure a system, DSC describes what the final state should be.

    DSC consists of:

    1. Configurations (declarative code)
    2. Resources (implement configuration logic)
    3. LCM (Local Configuration Manager) (execution engine)

    Example DSC configuration

    Configuration WebConfig {
        Node "Server01" {
            WindowsFeature IIS {
                Name = "Web-Server"
                Ensure = "Present"
            }
        }
    }
    WebConfig
    Start-DscConfiguration WebConfig -Wait -Verbose
    

    Benefits

    • Declarative
    • Idempotent (always reaches desired state)
    • Self-healing
    • Scalable across thousands of machines
    • Cloud and on-prem automation

    DSC is widely used by DevOps, administrators, and configuration engineers.

    30. What are DSC resources?

    DSC resources are the building blocks that define how DSC enforces configuration.

    Examples of built-in DSC resources

    • File → manage files/folders
    • Service → manage Windows services
    • Package → install software
    • Registry → manage registry keys
    • WindowsFeature → install server roles

    Structure of a DSC resource

    A DSC resource typically includes:

    • Schema MOF file
    • PowerShell module
    • Get/Set/Test functions

    What they do

    • Test-TargetResource → Check if system is in desired state
    • Set-TargetResource → Apply configuration
    • Get-TargetResource → Retrieve current state

    Custom DSC resources

    Admins can create their own resources for:

    • Custom applications
    • APIs
    • Complex deployments

    DSC resources provide the actual automation logic behind the declarative configuration model.

    31. What is the difference between push and pull DSC modes?

    PowerShell DSC supports two primary modes for delivering configuration to target nodes:

    1. Push Mode

    In push mode, the administrator manually sends the DSC configuration to a target node.

    Command:

    Start-DscConfiguration -Path "C:\MyDSC" -ComputerName Server01 -Wait -Verbose
    
    Characteristics
    • On-demand execution
    • Administrator-controlled
    • No DSC server required
    • Good for small environments and ad-hoc deployments
    Pros
    • Simple to use
    • No infrastructure dependency
    • Good for testing and lab work
    Cons
    • Not scalable for large enterprise environments
    • Manual, not automated

    2. Pull Mode

    In pull mode, nodes retrieve configuration from a DSC Pull Server when:

    • They check in periodically
    • Their configuration checksum changes
    • Their desired state drifts
    Characteristics
    • Server-client architecture
    • Uses SMB or HTTP/HTTPS
    • Nodes enforce state automatically
    Pros
    • Highly scalable
    • Automated configuration drift correction
    • Centralized configuration storage
    Cons
    • Requires configuring a pull server
    • MORE setup complexity

    Comparison Table

    FeaturePush ModePull ModeDeploymentManualAutomatedScaleSmallLarge enterpriseInfrastructureNone requiredPull server neededDrift correctionNoYesBest forLabs, testingProduction, large fleets

    Pull mode is the foundation of enterprise configuration management.

    32. How do you use the CIM cmdlets?

    CIM cmdlets allow communication with remote systems using WS-Management (WinRM) instead of the older DCOM protocol used by WMI.

    Key CIM cmdlets

    • Get-CimInstance
    • New-CimSession
    • Invoke-CimMethod
    • Set-CimInstance
    • Remove-CimInstance

    Example: Get system information

    Get-CimInstance -ClassName Win32_OperatingSystem
    

    Create a remote CIM session

    $session = New-CimSession -ComputerName "Server01"
    

    Use it:

    Get-CimInstance -CimSession $session -ClassName Win32_Service
    

    Invoke a CIM method

    Invoke-CimMethod -CimSession $session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine="notepad.exe"}
    

    Why use CIM instead of WMI?

    • Faster
    • More stable
    • Cross-platform
    • Works better with remoting

    CIM is the modern approach for system-level management in PowerShell.

    33. What is the difference between WMI and CIM?

    WMI and CIM both describe system management information, but they differ in technology and standards.

    WMI (Windows Management Instrumentation)

    • Windows-only
    • Uses DCOM protocol
    • Older technology
    • PowerShell command: Get-WmiObject

    CIM (Common Information Model)

    • Industry standard (DMTF)
    • Works with WS-Management (WinRM)
    • Cross-platform
    • PowerShell commands: CIM cmdlets (Get-CimInstance, etc.)

    Technical Comparison Table

    FeatureWMICIMProtocolDCOMWS-ManCross-platformNoYesPerformanceSlowerFasterSecurityOlder, less secureModern, encryptedPowerShell cmdletsLegacyRecommended

    Recommendation

    • Use CIM cmdlets for modern scripts.
    • Use WMI only where CIM is not supported.

    34. How do you compare objects in PowerShell?

    PowerShell provides multiple methods for object comparison.

    1. Compare-Object

    Compares two sets of objects.

    Example:

    Compare-Object -ReferenceObject $old -DifferenceObject $new
    

    Output includes:

    • InputObject
    • SideIndicator (<= or =>)

    2. Equality operators

    $a -eq $b
    $a -ne $b
    $a -gt $b
    $a -lt $b
    

    Works on:

    • Numbers
    • Strings
    • Objects with comparison behavior

    3. Sequence comparison

    $set1 = 1,2,3
    $set2 = 1,2,4
    Compare-Object $set1 $set2
    

    4. Compare object properties

    $process1.Name -eq $process2.Name
    

    5. Advanced comparison using Sort-Object -Unique

    $items | Sort-Object -Unique
    

    Object comparison in PowerShell is rich and supports structured data deeply.

    35. What is PSDrive?

    A PSDrive is a PowerShell abstraction that allows accessing different data stores using a filesystem-like interface.

    Examples of PSDrives:

    PSDriveProviderPurposeC:FileSystemFiles and foldersHKLM:RegistryRegistry hiveEnv:EnvironmentEnvironment variablesCert:CertificatesCertificate storeFunction:Function providerFunctions in memoryVariable:Variable providerPowerShell variables

    List all PSDrives

    Get-PSDrive
    

    Navigate like a file system

    cd Env:
    Get-ChildItem Env:
    cd HKLM:\Software
    

    Create a custom PSDrive

    New-PSDrive -Name MyData -PSProvider FileSystem -Root "C:\Data"
    

    PSDrives provide a unified navigation experience across data sources.

    36. How do you package and publish a module?

    PowerShell modules allow reusability and distribution of functions, scripts, and cmdlets.

    Step 1: Create a folder with your module name

    MyModule\
      MyModule.psm1
      MyModule.psd1  (optional manifest)
    

    Step 2: Add functions to the .psm1

    function Get-Hello {
        "Hello World"
    }
    

    Step 3: Create a module manifest

    New-ModuleManifest -Path "MyModule\MyModule.psd1" -RootModule "MyModule.psm1"
    

    Step 4: Test the module

    Import-Module .\MyModule
    Get-Hello
    

    Step 5: Publish module to PowerShell Gallery

    Prerequisites:

    Install-Module PowerShellGet
    Register-PSRepository
    

    Publish:

    Publish-Module -Name MyModule -NuGetApiKey <YourAPIKey>
    

    Step 6: Install module from Gallery

    Install-Module MyModule
    

    Modules are the backbone of scalable PowerShell development.

    37. How do you secure credentials using Get-Credential?

    Get-Credential allows users to securely input credentials.

    Prompt for credentials

    $cred = Get-Credential
    

    Prompts a GUI window with:

    • Username field
    • Password field (secure)

    Use credentials

    Invoke-Command -ComputerName Server01 -Credential $cred -ScriptBlock { hostname }
    

    Why it's secure

    • Password stored as SecureString
    • Username/password never appear in plain text
    • Reduces accidental credential exposure

    Convert SecureString to encrypted file (optional)

    $cred.Password | ConvertFrom-SecureString | Set-Content "password.txt"
    

    Credentials should always be handled securely in automation scripts.

    38. What is the SecureString type?

    SecureString is a .NET type designed to store encrypted, in-memory strings, typically for passwords or sensitive data.

    Characteristics

    • Encrypted in memory
    • Not readable as plain text
    • Can be converted to encrypted text for disk storage
    • Used by many cmdlets accepting credentials

    Create a SecureString manually

    Read-Host "Enter password" -AsSecureString
    

    Convert SecureString to plain text (not recommended)

    $ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString)
    $text = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr)
    

    SecureString improves security by ensuring sensitive data is protected.

    39. How do you suppress output in PowerShell?

    PowerShell provides several methods to hide or suppress output.

    1. Redirect to $null

    Get-Process > $null
    

    2. Use Out-Null

    Get-Process | Out-Null
    

    3. Assign output to a variable

    $x = Get-Process
    

    4. Use [void] cast

    [void](Get-Process)
    

    5. Use SilentlyContinue with error-producing commands

    Remove-Item file.txt -ErrorAction SilentlyContinue
    

    Output suppression is useful for clean scripts and automation.

    40. What is PowerShell transcript logging?

    Transcript logging records all activity in a PowerShell session, including:

    • Commands executed
    • Output
    • Errors
    • Timestamps
    • User identity

    This is extremely useful for:

    • Auditing
    • Compliance
    • Security monitoring
    • Debugging
    • Training/documentation

    Start a transcript

    Start-Transcript -Path "C:\Logs\session.log"
    

    Stop a transcript

    Stop-Transcript
    

    Transcript Features

    • Records everything printed to console
    • Cannot be altered by users during capture
    • Works in Windows PowerShell and PowerShell 7

    Transcript logs support cybersecurity policies and traceability in enterprise environments.

    Experienced (Q&A)

    1. Explain the internal architecture of PowerShell.

    PowerShell’s architecture consists of several tightly integrated layers, each responsible for translating user commands into executable .NET operations.

    1. Hosting Layer

    • PowerShell is a hosted engine.
    • Hosts include:
      • pwsh.exe / powershell.exe
      • PowerShell ISE
      • VS Code terminal
      • Custom .NET applications using PowerShell SDK
    • The host provides UI, prompt, input/output handling.

    2. PowerShell Engine

    The core execution engine handles:

    • Parsing
    • Tokenizing
    • AST generation
    • Compilation to MSIL
    • Pipeline processing
    • Command invocation

    3. Language Parser

    • Lexical analysis → tokens
    • Parsing → AST
    • AST → bound semantic model
    • ScriptBlock creation

    4. Binding and Command Resolution

    PowerShell dynamically resolves commands via:

    1. Alias
    2. Function
    3. Script
    4. Cmdlet
    5. External programs
    6. Provider paths

    5. Runspace

    • Execution context where commands run.
    • Contains:
      • SessionState
      • Modules
      • Providers
      • Variables
      • Pipeline threads

    6. Providers

    Virtualize data stores as drives (FileSystem, Registry, Cert, Env, etc).

    7. .NET CLR Integration

    PowerShell is built on top of the .NET runtime:

    • Uses .NET objects everywhere
    • Reflects over .NET classes
    • Calls .NET methods and properties dynamically

    8. Remoting System

    • Based on WinRM (WS-Man)
    • Uses object serialization (CLIXML) to transfer objects

    9. Extensive Module System

    Modules encapsulate:

    • Cmdlets (C#)
    • Functions (PowerShell)
    • Providers
    • DSC resources

    PowerShell’s architecture is a hybrid of a shell, a dynamic language, and a .NET automation engine, making it extremely powerful and extensible.

    2. Explain how the pipeline engine works under the hood.

    PowerShell's pipeline is a streaming object pipeline, not a text pipeline like Bash.

    Pipeline Internals

    1. Command 1 produces .NET objects
      • e.g., Get-Process outputs System.Diagnostics.Process
    2. Pipeline processor streams objects one at a time
      • Very efficient, avoids full collection creation
    3. Object Binder resolves pipe parameter binding:
      • ByValue: type matches expected parameter type
      • ByPropertyName: matching property names bind automatically
    4. Each pipeline component runs in a separate pipeline segment
      Internally represented by:
      • PipelineProcessor
      • CommandProcessorBase
      • CmdletParameterBinder
    5. Execution Flow
      • BeginProcessing()
      • ProcessRecord() → called once per piped object
      • EndProcessing()

    Example:

    Get-Process | Where-Object { $_.CPU -gt 20 }
    

    Key Features

    • Streaming reduces memory usage.
    • Type rich pipeline means minimal parsing.
    • Supports complex transformations and multistage processing.

    This architecture allows PowerShell to scale from small scripts to enterprise automation pipelines.

    3. How does PowerShell handle object serialization/deserialization in remoting?

    PowerShell Remoting uses CLIXML (Command Line Interface XML) to serialize .NET objects.

    Serialization Process (Sending Side)

    1. Object is inspected using reflection.
    2. Serializable properties are extracted.
    3. Object metadata (TypeName, properties) is converted to CLIXML.
    4. XML is transmitted over WinRM (WS-Man protocol).

    Deserialization Process (Receiving Side)

    1. Incoming CLIXML is parsed.
    2. PowerShell creates a deserialized PSObject.
    3. Methods and complex logic are removed for safety.
    4. Properties remain available, but methods do not execute.
    5. Type is replaced with Deserialized.<typename>.

    Example:

    Get-Process -ComputerName Server01
    

    Returns deserialized process objects (methods unavailable).

    Why use CLIXML?

    • Ensures safety (no executable code via remoting)
    • Cross-version compatibility
    • Lightweight
    • Native PowerShell serialization standard

    Deserialization guarantees secure, consistent remoting across environments.

    4. Explain the internal process of command discovery.

    PowerShell identifies and resolves commands using a specific ordered process.

    Command Discovery Order

    1. Alias
    2. Function
    3. Workflow
    4. Cmdlet
    5. Executable files
    6. Scripts in PATH
    7. Provider commands (paths)

    Internal Process

    1. Parser identifies potential command tokens.
    2. Lookup order:
      • SessionState.Alias
      • SessionState.Functions
      • Script or module private scope
      • Loaded modules
      • Cmdlet tables
      • PATH executable lookup
    3. If ambiguous → PowerShell throws "AmbiguousName" error.
    4. If multiple commands exist across modules:
      • Most recently loaded module wins
      • Can use fully qualified syntax:
    ModuleName\Get-User
    
    1. Discovery results cached for performance.

    This system makes PowerShell flexible but sometimes confusing if aliases or functions shadow cmdlets.

    5. How does PowerShell resolve command precedence (alias → function → cmdlet → external)?

    PowerShell resolves commands using a strict hierarchy:

    1. Alias
      • Fastest resolution
      • E.g., ls = alias for Get-ChildItem
    2. Function
      • Overrides cmdlets with same name
      • Local function takes precedence over global
    3. Cmdlet
      • Native PowerShell commands implemented in .NET
    4. External Commands
      • EXE, COM, BAT, CMD
      • Only used if not found earlier

    Example

    If a function is named Get-Process, it overrides the built-in cmdlet.

    You can still call the real cmdlet using:

    Get-Command Get-Process -CommandType Cmdlet
    

    Or fully-qualified syntax:

    Microsoft.PowerShell.Management\Get-Process
    

    This order provides flexibility and extensibility but requires careful naming in modules.

    6. Explain how PowerShell compiles script blocks into MSIL.

    PowerShell script execution pipeline:

    1. Parser converts script into AST.
    2. AST is transformed into a ScriptBlock object.
    3. ScriptBlock is compiled into DynamicMethod using ILGenerator.
    4. Resulting Microsoft Intermediate Language (MSIL) executes inside the CLR.
    5. For loops and pipelines produce optimized IL structures.

    Compiled Code Cache

    PowerShell caches compiled script blocks for reuse:

    • Improves performance
    • Supports runspaces efficiently

    Example

    $sb = { param($x) $x + 10 }
    

    Internally:

    • AST → ScriptBlock
    • Bound semantic model created
    • IL emitted dynamically
    • CLR executes code

    This dynamic compilation is what gives PowerShell high performance despite being a scripting language.

    7. What is the AST (Abstract Syntax Tree) in PowerShell?

    AST is a hierarchical representation of PowerShell code created during parsing.

    Purpose of AST

    • Represents program structure
    • Enables code analysis and static checks
    • Supports refactoring
    • Allows security scanning
    • Enables custom compilers/analyzers

    Example

    For this script:

    Get-Process | Where-Object { $_.CPU -gt 10 }
    

    PowerShell creates an AST tree with nodes like:

    • PipelineAst
    • CommandAst
    • ScriptBlockAst
    • BinaryExpressionAst

    AST nodes are immutable and represent the entire script structure.

    8. How do you analyze PowerShell code using AST?

    AST-based analysis allows deep inspection of PowerShell scripts.

    Get AST from a script

    $ast = [System.Management.Automation.Language.Parser]::ParseFile("script.ps1", [ref]$null, [ref]$null)
    

    Find all command names

    $ast.FindAll({ $args[0] -is [System.Management.Automation.Language.CommandAst] }, $true)
    

    Find all variable references

    $ast.FindAll({ $_ -is [System.Management.Automation.Language.VariableExpressionAst] }, $true)
    

    Use cases

    • Security scanning (detect Invoke-Expression, encoded commands)
    • Code quality checks
    • Refactoring tools
    • Autocomplete engines
    • Custom static analyzers

    AST analysis is crucial for writing secure, scalable PowerShell tooling.

    9. Explain runspace pools and when to use them.

    A runspace pool is a collection of pre-created runspaces (PowerShell execution environments) that can be reused for high-performance parallel operations.

    Why runspace pools?

    • Creating runspaces is expensive.
    • A pool allows reuse → significantly increases performance.
    • Useful for multi-threaded PowerShell automation.

    Example use cases

    • Scanning thousands of servers
    • Parallel API calls
    • Processing massive datasets
    • Building high-performance PowerShell modules

    Basic example

    $pool = [runspacefactory]::CreateRunspacePool(1, 10)
    $pool.Open()
    

    Now each job can use a runspace from the pool.

    Benefits

    • Faster than PowerShell jobs
    • Lower memory footprint
    • Highly scalable

    Runspace pools are a foundational concept for building high-performance automation frameworks.

    10. How do you implement multithreading using runspaces?

    Runspaces allow high-performance multithreading by running multiple pipelines in parallel.

    Step-by-step approach

    1. Create a runspace pool

    $pool = [runspacefactory]::CreateRunspacePool(1, 10)
    $pool.Open()
    

    2. Create PowerShell instance

    $ps = [powershell]::Create()
    $ps.RunspacePool = $pool
    

    3. Add the script block

    $ps.AddScript({ param($n) "Processing $n"; Start-Sleep 1 })
    

    4. Add arguments

    $ps.AddArgument(5)
    

    5. Begin async execution

    $handle = $ps.BeginInvoke()
    

    6. Collect results

    $result = $ps.EndInvoke($handle)
    

    Why runspaces for multithreading?

    • 20× faster than Start-Job
    • Each runspace is a lightweight CLR thread
    • Lower overhead
    • Ideal for:
      • Parallel loops
      • Large-scale automation
      • Real-time dashboards
      • PowerShell-based microservices

    Runspaces give PowerShell performance comparable to C# async/parallel programming while keeping scriptability.

    WeCP Team
    Team @WeCP
    WeCP is a leading talent assessment platform that helps companies streamline their recruitment and L&D process by evaluating candidates' skills through tailored assessments