fbpx

Top 100 PowerShell Interview Questions and Answers

Top 100 PowerShell Interview Questions and Answers

Contents show

1. What is PowerShell?

Answer:
PowerShell is a task automation framework from Microsoft. It combines a command-line shell and a scripting language, built on the .NET Framework. It helps automate administrative tasks on both local and remote Windows systems.

Reference


2. How do you execute a PowerShell script?

Answer:
To execute a PowerShell script, navigate to the script’s directory and run:

.\script-name.ps1

Ensure that the execution policy allows the script to run.

Reference


3. How do you set execution policy in PowerShell?

Answer:
Use the Set-ExecutionPolicy cmdlet. Example:

Set-ExecutionPolicy RemoteSigned

This allows scripts downloaded from the internet to run if they’re signed by a trusted publisher.

Reference


4. What are cmdlets?

Answer:
Cmdlets (pronounced “command-lets”) are lightweight PowerShell scripts that perform a specific function. Example:

Get-ChildItem

This cmdlet lists items in a directory.

Reference


5. How do you filter results in PowerShell?

Answer:
Use the Where-Object cmdlet. Example:

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

This filters processes with CPU usage greater than 100.

Reference


6. How can you get help on a cmdlet?

Answer:
Use the Get-Help cmdlet. Example:

Get-Help Get-Process

This provides detailed help for the Get-Process cmdlet.

Reference


7. What is the difference between a function and a cmdlet?

Answer:
Functions are scripts that return a value, while cmdlets are compiled commands. Cmdlets typically offer better performance and are written in a .NET programming language.

Reference


8. How do you declare a variable in PowerShell?

Answer:
Variables in PowerShell are prefixed with $. Example:

$myVariable = "Hello, PowerShell!"

This creates a variable named myVariable with the given string.

Reference


9. What’s the difference between $null and "" (empty string) in PowerShell?

Answer:
In PowerShell, $null represents an absence of value, while "" is an empty string value. They’re not the same and have different implications in condition evaluations.

Reference


10. How do you concatenate strings in PowerShell?

Answer:
Strings can be concatenated using +. Example:

$greeting = "Hello, " + "PowerShell!"

This combines the two strings into one.

Reference


11. How do you iterate over an array in PowerShell?

Answer:
Use a foreach loop. Example:

$array = 1,2,3
foreach ($item in $array) {
    Write-Host $item
}

This prints each number in the array.

Reference


12. What is a hashtable in PowerShell?

Answer:
A hashtable is a key-value paired collection. Example:

$hashtable = @{
    Key1 = 'Value1'
    Key2 = 'Value2'
}

Retrieve values using $hashtable["Key1"].

Reference


13. How do you handle exceptions in PowerShell?

Answer:
Use try-catch blocks. Example:

try {
    # code that might throw an error
}
catch {
    # handle

 error
}

This catches and handles exceptions.

Reference


14. What is a PSSession?

Answer:
A PSSession is a persistent connection to a remote computer. It allows multiple commands to be executed in a single session, improving efficiency.

Reference


15. How do you import a module in PowerShell?

Answer:
Use the Import-Module cmdlet. Example:

Import-Module ActiveDirectory

This imports the Active Directory module.

Reference


16. How do you get a list of all installed modules?

Answer:
Use the Get-Module -ListAvailable command. It lists all the modules installed on the system.

Reference


17. How can you execute PowerShell commands on a remote computer?

Answer:
Use the Invoke-Command cmdlet. Example:

Invoke-Command -ComputerName RemotePC -ScriptBlock {Get-Process}

This gets the processes on a remote computer named RemotePC.

Reference


18. What is the difference between Export-Csv and ConvertTo-Csv?

Answer:
Export-Csv saves the object data in a CSV file, while ConvertTo-Csv converts the object data to CSV format and returns it as string data without saving.

Reference


19. How do you create a custom object in PowerShell?

Answer:
Use New-Object or the PSCustomObject type accelerator. Example:

$customObject = [PSCustomObject]@{
    Name = "John"
    Age = 30
}

Reference


20. How can you filter and select specific properties of an object?

Answer:
Use the Select-Object cmdlet. Example:

Get-Process | Select-Object ProcessName, CPU

This selects only the ProcessName and CPU properties.

Reference


21. How do you get the history of commands executed in the session?

Answer:
Use the Get-History cmdlet. It displays the command history for the current session.

Reference


22. How can you run background jobs in PowerShell?

Answer:
Use the Start-Job cmdlet. Example:

Start-Job -ScriptBlock {Get-Process}

This starts a background job to get processes.

Reference


23. How do you pass arguments to a PowerShell script?

Answer:
Use the param keyword in the script. In the command-line, provide values after the script name. Example inside script:

param($arg1, $arg2)

Run as: .\script.ps1 value1 value2.

Reference


24. How do you stop a running command or script in PowerShell?

Answer:
Press Ctrl + C to terminate the running command or script.

Reference


25. What is pipelining in PowerShell?

Answer:
Pipelining allows the output of one cmdlet to be used as the input for another, without intermediate variables. It’s done using the | operator. Example:

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

Reference


26. How do you retrieve the exit code of the last command?

Answer:
Use the $? variable. It returns True if the last operation was successful and False otherwise.

Reference


27. How can you suppress the output of a command?

Answer:
To suppress the output, redirect it to $null. Example:

Get-Process > $null

Reference


28. How do you compare two strings in PowerShell?

Answer:
Use the -eq operator for equality check and -like for wildcard comparisons. Example:

if ($string1 -eq $string2) { # actions }

Reference


29. How do you get the current date and time in PowerShell?

Answer:
Use the Get-Date cmdlet. It retrieves the current date and time.

Reference


30. How do you sleep or delay script execution?

Answer:
Use the Start-Sleep cmdlet. Example:

Start-Sleep -Seconds 5

This halts script execution for 5 seconds.

Reference


31. How can you find the PowerShell version you’re using?

Answer:
Use the $PSVersionTable variable and check the PSVersion property. Example:

$PSVersionTable.PSVersion

This provides the version of the currently running PowerShell.

Reference


32. How do you retrieve environment variables in PowerShell?

Answer:
Access environment variables using the $env: prefix. Example:

$env:COMPUTERNAME

This gets the computer’s name.

Reference


33. What is a profile in PowerShell?

Answer:
A PowerShell profile is a script that runs whenever PowerShell starts, initializing settings, functions, variables, and more.

Reference


34. How do you create a function in PowerShell?

Answer:
Functions are declared using the function keyword. Example:

function Greet($name) {
    "Hello, $name"
}

This function greets the passed name.

Reference


35. How do you run a command as an administrator in PowerShell?

Answer:
To run a command as an administrator, right-click the PowerShell icon and select ‘Run as administrator’. Alternatively, use Start-Process cmdlet with -Verb RunAs.

Reference


36. What is the difference between ForEach and ForEach-Object?

Answer:
ForEach is a loop construct, while ForEach-Object is a cmdlet for processing items in a pipeline. ForEach might be faster in some cases but doesn’t support pipelining.

Reference


37. How can you save the output of a command to a file?

Answer:
Redirect the output using > or Out-File. Example:

Get-Process > processes.txt

This saves the list of processes to a text file.

Reference


38. How do you create a new alias in PowerShell?

Answer:
Use the New-Alias cmdlet. Example:

New-Alias -Name "np" -Value "notepad.exe"

This creates an alias np for Notepad.

Reference


39. How can you find which cmdlets belong to a module?

Answer:
Use the Get-Command cmdlet. Example:

Get-Command -Module ActiveDirectory

This lists all cmdlets in the ActiveDirectory module.

Reference


40. How do you reload a module after making changes to it?

Answer:
Use the Import-Module cmdlet with the -Force parameter. Example:

Import-Module MyModule -Force

This re-imports the module, reloading any changes.

Reference


41. What is a DSC in PowerShell?

Answer:
DSC (Desired State Configuration) is a declarative language in PowerShell that automates configuration management and deployment of resources.

Reference


42. How can you retrieve the last command that was executed?

Answer:
Use the Get-History cmdlet with Select-Object. Example:

Get-History | Select-Object -Last 1

This returns the last command from the history.

Reference


43. How can you sort objects in PowerShell?

Answer:
Use the Sort-Object cmdlet. Example:

Get-Process | Sort-Object CPU

This sorts processes by CPU usage.

Reference


44. How can you merge multiple objects into a single object in PowerShell?

Answer:
Use the Add-Member cmdlet. You can add members (properties/methods/events) to an object to consolidate data.

Reference


45. How can you retrieve a unique set of objects from an array?

Answer:
Use the Get-Unique cmdlet. Example:

$array | Sort-Object | Get-Unique

This returns unique items from the array.

Reference


46. How do you pass multiple arguments to a function or cmdlet?

Answer:
Parameters are passed using spaces. If a cmdlet or function accepts named parameters, you can specify them using -ParameterName followed by the value.

Reference


47. How do you load a .NET assembly in PowerShell?

Answer:
Use the Add-Type cmdlet. Example:

Add-Type -AssemblyName "System.Text.RegularExpressions"

This loads the specified .NET assembly.

Reference


48. How can you check if a cmdlet exists in PowerShell?

Answer:
Use the Get-Command cmdlet. If the cmdlet exists, it will return information about it; otherwise, it will throw an error.

Reference


49. How do you comment code in PowerShell?

Answer:
Use the # symbol for single-line comments. For multi-line comments, wrap the content between <# and #>.

Reference


50. What are providers in PowerShell?

Answer:
Providers enable access to data stores, like the registry and file system, in a consistent way. They appear as drives and can be accessed with cmdlets.

Reference


51. How can you remove a variable in PowerShell?

Answer:
Use the Remove-Variable cmdlet. Example:

Remove-Variable -Name myVariable

This deletes the variable named myVariable.

Reference


52. What is the difference between $global and $script scopes in PowerShell?

Answer:
$global refers to variables available across the entire PowerShell session. $script refers to variables available within the scope of the running script only.

Reference


53. How do you convert a string to an integer type in PowerShell?

Answer:
Cast the string to an integer. Example:

[int]$integerValue = "123"

This converts the string “123” to an integer.

Reference


54. What is the purpose of the $_ variable in PowerShell?

Answer:
$_ is the current object in the pipeline. It’s commonly used in scripts and functions to represent the current item being processed.

Reference


55. How can you split a string into an array based on a delimiter in PowerShell?

Answer:
Use the -split operator. Example:

$splitArray = "PowerShell-Is-Awesome" -split "-"

This splits the string into an array using “-” as the delimiter.

Reference


56. How can you join an array of strings into a single string in PowerShell?

Answer:
Use the -join operator. Example:

$joinedString = @("PowerShell", "Is", "Awesome") -join " "

This joins the array into a single string with spaces.

Reference


57. How can you execute a SQL query from PowerShell?

Answer:
Leverage .NET’s System.Data.SqlClient namespace. Example:

$connectionString = "Data Source=server;Initial Catalog=database;Integrated Security=True"
$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString
$command = $connection.CreateCommand()
$command.CommandText = "SELECT * FROM table"
$connection.Open()
$reader = $command.ExecuteReader()
while ($reader.Read()) { Write-Host $reader["ColumnName"] }
$connection.Close()

Reference


58. How can you download a file from the web using PowerShell?

Answer:
Use the Invoke-WebRequest cmdlet. Example:

Invoke-WebRequest -Uri "http://example.com/file.zip" -OutFile "C:\path\to\save\file.zip"

This downloads the file and saves it to the specified location.

Reference


59. How do you measure the time taken to execute a command in PowerShell?

Answer:
Use the Measure-Command cmdlet. Example:

Measure-Command { Get-Process }

This measures the time taken to execute the Get-Process cmdlet.

Reference


60. What’s the difference between Write-Host and Write-Output?

Answer:
Write-Host sends output directly to the console. Write-Output sends data to the pipeline. While both might seem similar, Write-Output is preferable when further processing of the output is needed.

Reference



61. How can you list all the services on a machine using PowerShell?

Answer:
Use the Get-Service cmdlet. Example:

Get-Service

This lists all the services on the current machine.

Reference


62. How can you find the status of a specific service?

Answer:
Use the Get-Service cmdlet with the service name. Example:

Get-Service -Name "wuauserv"

This retrieves the status of the Windows Update service.

Reference


63. How do you start or stop a service in PowerShell?

Answer:
Use the Start-Service or Stop-Service cmdlets. Example:

Start-Service -Name "wuauserv"
Stop-Service -Name "wuauserv"

This starts or stops the Windows Update service, respectively.

Reference


64. How can you retrieve the disk space of a system using PowerShell?

Answer:
Use the Get-PSDrive cmdlet. Example:

Get-PSDrive -Name C

This gets details, including free and used space, of the C drive.

Reference


65. How can you get the IP address of a system using PowerShell?

Answer:
Use the Get-NetIPAddress cmdlet. Example:

Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -ne "Loopback" }

This fetches the IPv4 address, excluding loopback addresses.

Reference


66. How do you find the current user logged in using PowerShell?

Answer:
Use the $env:USERNAME variable. Example:

$env:USERNAME

This retrieves the username of the currently logged-in user.

Reference


67. How do you append content to a file in PowerShell?

Answer:
Use the Add-Content cmdlet. Example:

Add-Content -Path "C:\path\to\file.txt" -Value "New content"

This appends “New content” to the specified file.

Reference


68. How can you execute a batch script or external program from PowerShell?

Answer:
Use the Start-Process cmdlet. Example:

Start-Process -FilePath "C:\path\to\script.bat"

This runs the specified batch script or program.

Reference


69. How can you run a PowerShell script from the command prompt?

Answer:
Invoke the PowerShell executable with the script path. Example:

powershell.exe -ExecutionPolicy Bypass -File "C:\path\to\script.ps1"

This runs the script while bypassing the execution policy.

Reference


70. What’s the difference between ForEach and Parallel in the ForEach-Object cmdlet?

Answer:
ForEach processes each item sequentially, while Parallel processes items concurrently. Parallel can improve performance for independent, time-consuming operations.

Reference



71. How do you list all installed modules in PowerShell?

Answer:
Use the Get-Module cmdlet with the -ListAvailable parameter. Example:

Get-Module -ListAvailable

This lists all modules that are installed and available on the system.

Reference


72. What is a cmdlet in PowerShell?

Answer:
A cmdlet (pronounced “command-let”) is a lightweight command used in the PowerShell environment. Cmdlets are .NET classes implementing a particular operation and follow a verb-noun naming convention.

Reference


73. How can you run a PowerShell script with parameters?

Answer:
You can define parameters in a script using the param keyword and pass them when invoking the script. Example:

param($param1, $param2)

Invoke with:

.\script.ps1 -param1 "value1" -param2 "value2"

Reference


74. How do you filter objects in PowerShell?

Answer:
Use the Where-Object cmdlet. Example:

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

This retrieves processes with CPU usage greater than 100.

Reference


75. How do you retrieve members (properties/methods) of an object?

Answer:
Use the Get-Member cmdlet. Example:

Get-Process | Get-Member

This lists members of the process object.

Reference


76. What is a manifest in PowerShell?

Answer:
A module manifest is a .psd1 file that contains metadata about a module, like its version, author, and required modules. It defines how the module behaves.

Reference


77. How can you import functions from another PowerShell script?

Answer:
Use the dot sourcing technique. Example:

. .\path\to\script.ps1

This runs the script in the current scope, making its functions and variables available.

Reference


78. What’s the difference between Export-CSV and ConvertTo-CSV?

Answer:
Export-CSV saves object data directly to a file. ConvertTo-CSV converts object data to CSV format but returns it as strings rather than saving to a file.

Reference


79. How do you handle errors in PowerShell?

Answer:
Use try, catch, and finally blocks. Example:

try {
    # potentially error-causing code
}
catch {
    # error handling code
}
finally {
    # cleanup code
}

This structure helps manage and respond to errors.

Reference


80. How can you execute a piece of code repeatedly using a timer?

Answer:
Use a while loop with the Start-Sleep cmdlet for timing. Example:

while ($true) {
    # code to execute
    Start-Sleep -Seconds 10
}

This runs the code every 10 seconds indefinitely.

Reference



81. What is the $_ symbol in PowerShell?

Answer:
$_ is an automatic variable that represents the current object in the pipeline or the current item in a loop.

Reference


82. How can you create a custom object in PowerShell?

Answer:
Use the New-Object cmdlet with the PSCustomObject type. Example:

$newObj = New-Object -TypeName PSObject -Property @{
    Name = "John"
    Age = 30
}

This creates a custom object with Name and Age properties.

Reference


83. How can you compare two objects in PowerShell?

Answer:
Use the Compare-Object cmdlet. Example:

$object1 = 1, 2, 3
$object2 = 2, 3, 4
Compare-Object -ReferenceObject $object1 -DifferenceObject $object2

This will highlight the differences between the two objects.

Reference


84. How can you run a remote PowerShell session?

Answer:
Use the Enter-PSSession cmdlet. Example:

Enter-PSSession -ComputerName Server01

This initiates a remote session to Server01.

Reference


85. How do you read content from a file in PowerShell?

Answer:
Use the Get-Content cmdlet. Example:

$content = Get-Content -Path "C:\path\to\file.txt"

This reads the content of the specified file.

Reference


86. How can you run a job in the background in PowerShell?

Answer:
Use the Start-Job cmdlet. Example:

Start-Job -ScriptBlock { Get-Process }

This starts a background job that retrieves process information.

Reference


87. How can you check for the existence of a key in a hashtable?

Answer:
Check if the key is in the Keys property of the hashtable. Example:

$hash = @{ "key1" = "value1"; "key2" = "value2" }
$hash.ContainsKey("key1")

This checks for the existence of “key1”.

Reference


88. How can you list all environment variables in PowerShell?

Answer:
Use the $env: drive. Example:

Get-ChildItem env:

This lists all environment variables and their values.

Reference


89. How can you create a symbolic link in PowerShell?

Answer:
Use the New-Item cmdlet with the -ItemType parameter set to “SymbolicLink”. Example:

New-Item -Path "C:\path\to\link" -ItemType SymbolicLink -Value "C:\path\to\target"

This creates a symbolic link pointing to the target.

Reference


90. How can you find the type of a variable?

Answer:
Use the GetType method on the object. Example:

$variable = "PowerShell"
$variable.GetType().FullName

This returns the type of the variable.

Reference



91. How can you create a function in PowerShell?

Answer:
Use the function keyword. Example:

function Add-Numbers {
    param($a, $b)
    return $a + $b
}

This defines a function named Add-Numbers that returns the sum of two parameters.

Reference


92. How can you return multiple values from a function?

Answer:
Return an array or a custom object. Example:

function Get-Data {
    return @('Data1', 'Data2', 'Data3')
}

This function returns an array with three string values.

Reference


93. How can you sort objects based on a property in PowerShell?

Answer:
Use the Sort-Object cmdlet. Example:

Get-Process | Sort-Object CPU -Descending

This sorts processes based on the CPU property in descending order.

Reference


94. How can you update all modules installed in PowerShell?

Answer:
Use the Update-Module cmdlet. Example:

Get-Module -ListAvailable | Update-Module

This fetches all available modules and updates them.

Reference


95. How can you get a unique list of items from an array?

Answer:
Use the Select-Object cmdlet with the -Unique parameter. Example:

$array = 1, 2, 2, 3, 3, 3
$array | Select-Object -Unique

This returns a list with unique numbers: 1, 2, and 3.

Reference


96. How do you check the PowerShell version?

Answer:
Use the $PSVersionTable.PSVersion automatic variable. Example:

$PSVersionTable.PSVersion

This returns the version of the currently running PowerShell instance.

Reference


97. How can you catch specific exceptions in a try-catch block?

Answer:
Specify the exception type in the catch block. Example:

try {
    # Code that may throw an exception
}
catch [System.IO.FileNotFoundException] {
    # Handle file not found exception
}
catch {
    # Handle all other exceptions
}

This captures and handles specific exceptions.

Reference


98. How can you find the methods of an object?

Answer:
Use the Get-Member cmdlet with the -MemberType parameter. Example:

$variable = "PowerShell"
$variable | Get-Member -MemberType Method

This lists all methods associated with the string object.

Reference


99. How do you clone an object in PowerShell?

Answer:
Use the Clone method if available, or use serialization techniques. Example using serialization:

$original = [PSCustomObject]@{ Name = "John"; Age = 30 }
$clone = $original | ConvertTo-Json | ConvertFrom-Json

This creates a clone of the $original object.

Reference


100. How can you prevent a script from executing unintended commands?

Answer:
Use the -WhatIf parameter, which simulates the execution of a cmdlet without actually changing any data.

Reference