Top 50 interview question and answers for PowerShell

PowerShell may be a cross-platform task automation answer created of a command-line shell, a scripting language, and a configuration management framework. PowerShell runs on Windows, Linux, and macOS.

what is powershell

PowerShell could be a fashionable command shell that {features} the most effective features of alternative fashionable shells. Not like most shells that solely settle for and come back text, PowerShell accepts and returns .NET objects. The shell includes the subsequent features:

PowerShell may be a trendy command shell that has} the most effective features of alternative common shells. Not like most shells that solely settle for and come back text, PowerShell accepts and returns .NET objects. The shell includes the subsequent features:

  • Robust command-line history
  • Tab completion and command prediction (See about_PSReadLine)
  • Supports command and parameter aliases
  • Pipeline for chaining commands
  • In-console help system, similar to UNIX man pages

Scripting language

What is scripting language

As a scripting language, PowerShell is usually used for automating the management of systems. It’s additionally wont to build, test, and deploy solutions, usually in CI/CD environments. PowerShell is made on the .NET Common Language Runtime (CLR). All inputs and outputs square measure .NET objects. No have to be compelled to break down text output to extract data from output. The PowerShell scripting language includes the subsequent features:

  • Extensible through functions, classes, scripts, and modules
  • Extensible format system for simple output
  • Extensible sort system for making dynamic varieties
  • Built-in support for common knowledge formats like CSV, JSON, and XML

Interview question and answers for PowerShell

  1. What is PowerShell?

PowerShell is an extedable command and a scripting language for Windows.

2. What are the key characteristics of PowerShell?

It is development stage technology implemented so that the cloud provides the services globally as per the user requirements. It provides a method to access several servers worldwide.

  • The key characteristics of PowerShell are:
  • It is object-based and not text based.
  • Commands are able to be modified to suit a particular task.
  • It is a command line interpreter and scripting environment.

3. What does variables holds in PowerShell?

Variables in PowerShell contains strings, integers and objects. There is no special variables as it is pre-defined with PowerShell

4. What are the significance of brackets in PowerShell?

Curved Parentheses Brackets (): Curved parentheses brackets are meant for compulsory arguments.

Braces Brackets {}: They are employed in blocked statements

Square Brackets []: They define optional items, and it is not frequently used

5. What do you mean by cmdlet’s?

Cmdlet’s are written in .net language as simple build in commands like C# or VB introduced by Windows PowerShell

6. Explain what is PowerShell Loop?

PowerShell loop helps to automate the repetitive task is function is called PowerShell loop. By this you can execute for each loop, while loop and Do While loop.

7. Explain how can you create PowerShell scripts for deploying components in SharePoint?

After creating a web part using VS 2010, we can deploy it using cntrl+f5, then to activate the web part characteristic you can write a PowerShell script (.ps1) and perform it after deployment

8. Explain why PowerShell pipeline is used for?

Two statements are joined using PowerShell pipeline where the input of second statement becomes the output of one statement

9. Explain what is PowerShell get-command?

PowerShell get-command is used to get other cmdlets, suppose you are looking for cmdlet between letter L and R then your PowerShell get-command will be like # PowerShell Get – Command Range Clear-Host Get-Command [L–R]*

10. What are the three ways that PowerShell uses to ‘Select’?

  • The most common way is Wmiobject uses ‘-query’ to introduce a classic ‘Select * from’ a phrase.
  • The second context is Select-String.
  • Third way is Select Object

11. What is the function of Get-Service Status in PowerShell?

The cmdlets of windows enable you to filter the window services. PowerShell can list which services are ‘Running’ and which are ‘Stopped’ by scripting with windows.

12. Explain what PowerShell Scripting is?

PowerShell file contains a series of PowerShell commands. Each command will appearing on a separate line. To use a text file as a PowerShell script, filename should have.PS1 extension.

  • To run a script we need
  • Type the commands in a text editor
  • Save the file with .ps1 extension
  • Execute the file in PowerShell.

13. What is the use of hash table in PowerShell?

A hash table is also referred as dictionary. It is an array that allows you to store data in a “key-value” pair association. The “key” and “value” can be of any data and length. To declare a hash table you have to use @ followed by curly braces.

14. Explain what is the use of Array in PowerShell?

Array in PowerShell is used to run script against remote computers. If we create a variable and assign the array by this we can create array. Array is represented by “@”symbol, they are represented as hash table but not followed by curly braces.

For example,
 $arrmachine = @ (“machine1”, “machine2”, “machine3”)

15. Mention what is the command that can be used to get all child folders in a specific folder?

Use parameter recurse in the code to get all child folders in a specific folder.

Get-ChildItem C:\Scripts –recurse

16. Explain how you can convert the object into HTML?

  • To convert the object into HTML
  • Get-Process
  • Sort-object– property CPU –descending.
  • Convert to – HTML.
  • Out-file “process.html”.

17. Explain how you can rename a variable?

To rename a variable,Rename-Item-Path Env: My Variable –New Name MyRenamedVar

18. Explain what is the function of $input variable?

The function of $input variable is to access data coming from the pipeline

19. What is the code to find the name of the installed application on the current computer?

Get-WmiObject-Class Win32_Product- ComputerName. l Format-wide-column1

20. Explain how you can find in PowerShell that all the sql services are on one server?

There are two ways to do this

get-wmiobject win32_service l where-object {$_name-like “*sql*”}
get-service sql*

21. Explain with an example how you can map a network drive in PowerShell?

To map a network drive in PowerShell you have to use the command like

# PowerShell Map Network Drive

$Net = $( New - Object – ComObject Wscript.Network )
$Net.MapNetworkDrive( "S:", \\expert\guru99 )

In here the drive letter is “S:” and the Network share is called ‘expert’ on a computer called ‘guru99.’

22. Mention what are the three ways that PowerShell uses to ‘Select’?

The most common way is in a WMI Query Language (WQL) statement. In this technique Wmiobject uses ‘-query’ to introduce a classic ‘Select * from’ a phrase

The second context for ‘Select’ in PowerShell is Select-String. This cmdlet checks for a word, phrase or any pattern match

Another way is Select Object

23. What is the function for Get-Service status in PowerShell?

The cmdlet of windows enables you to filter the window services.  PowerShell can list which services are ‘Running’ and which are ‘Stopped’ by scripting with windows.

24. Explain what PowerShell Scripting is?

PowerShell file contains a series of PowerShell commands with each command appearing on a separate line. To use a text file as a PowerShell script, its filename should have.PS1 extension. To run a script you need

Type the commands in a text editor

Save the file with .ps1 extension

Execute the file in PowerShell

25. What is the use of hash table in PowerShell?

A hash table is also referred as dictionary. It is an array that allows you to store data in a “key-value” pair association. The “key” and “value” can be of any data and length.  To declare a hash table you have to use @ followed by curly braces.

26. Explain what is the use of Array in PowerShell?

The use of Array in PowerShell is to run a script against remote computers.  In order to create an array, you have to create a variable and assign the array.  Arrays are represented by “@”symbol, they are represented as hashtable but not followed by curly braces.

For example,
 $arrmachine = @ ( “machine1” , “machine2” , “machine3”)

26. Mention what is the command that can be used to get all child folders in a specific folder?

To get all child folders in a specific folder, you have to use parameter recurse in the code.

Get-ChildItem C:\Scripts –recurse

27. Explain how you can convert the object into HTML?

To convert the object into HTML

Get-Process l Sort-object – property CPU –descending l convert to – HTML l Out-file “process.html”

28. Explain how you can rename a variable?

To rename a variable,

Rename-Item- Path Env: MyVariable –NewName MyRenamedVar

29. Explain what is the function of $input variable?

The $input variable enables a function to access data coming from the pipeline

30. What is the code to find the name of the installed application on the current computer?

Get-WmiObject-Class Win32_Product- ComputerName . l Format-wide-column1

31. Explain how you can find in PowerShell that all the sql services are on one server?

There are two ways to do this

get-wmiobject win32_service l where-object {$_.name-like “*sql*”}
get-service sql*

32. What is a hash table in PowerShell?

The hash table in PowerShell is also called as a dictionary or an associative array. It is a compact data structure which is used to store each value by using a key. For every hash table, there is an object of a hash table in the PowerShell.

Following box describes the syntax of hash table:

$variable_name = @{ <key1> = <value1> ; < key2> = <value2> ; ..... ; < keyN> = <valueN>;}    

33. Name the different type of PowerShell operators?

Following are the different types of operators in PowerShell:

  • Arithmetic Operator
  • Assignment Operator
  • Comparison Operators
  • Logical Operators
  • Redirection Operators
  • Split and Join Operators

34. Explain the Comparison operator in PowerShell?

Comparison Operators are used in PowerShell for comparing the values. Following are four types of comparison operators:

  • Equality Comparison Operator
  • Match Comparison Operator
  • Containment Comparison Operator
  • Replace Comparison Operator

35. What are cmdlets in PowerShell?

The cmdlets are the commands which are written in a .net language like VB or C# introduced by the Windows PowerShell. The cmdlets return the object of Microsoft .NET framework to the next commands in the pipeline. The PowerShell cmdlets follow the verb-noun pattern, such as get-help, set-Item.

36. What is a loop in PowerShell?

When you need to execute the block of commands or statements several times in PowerShell, use the concept of loops.

Following are the several types of Loops in PowerShell:

  • While loop
  • Do-While
  • For loop
  • ForEach loop

37. Explain the different types of loops in PowerShell?

While loop: This loop is also called an entry-controlled loop. It executes the commands in a block sequentially, when the given condition evaluates to True. The following box describes the syntax of while loop:

while(test_expression)   

{    
     Statement-1    
     Statement-2    
     Statement-N    
}  

For loop: In this loop, the commands or statements in a block are executed one by one, if the condition returns a True value, otherwise the loop terminates. Following box describes the syntax of For loop:

for (<Initialization>; <Condition or Test_expression>; <Repeat>)   

{    
     Statement-1    
     Statement-2    
     Statement-N    
}  

Do-While and Do-Until loop:

Do-while: This loop is called an exit-controlled loop. This loop executes a block of commands at least once because the condition is checked after the block. In this loop, if the condition is True, then the commands in the block are executed. Otherwise, the loop terminates. The following box describes the syntax of Do-while loop:

Do   

{    
        Statement-1    
        Statement-2    
        Statement-N     
} while( test_expression)  

Do-Until: This loop is also called an exit-controlled loop. This loop also executes a block of commands at least once because the condition is checked after the block. In this loop, if the condition is False, then the commands in the block are executed. Otherwise, the loop terminates. The following box describes the syntax of Do-Until loop:

Do    
{    
        Statement-1    
        Statement-2    
        Statement-N     
} until( test_expression)  

ForEach loop: This loop is used in PowerShell to access the array or a collection of objects, numbers, strings, etc. Following box describes the syntax of ForEach loop:

Foreach($<item> in $<collection>)    
   {    
         Statement-1    
         Statement-2    
         Statement-N    
    } 

38. Name the command which is used to copy a file, registry key, or folder?

Copy-Item is a command which is used to copy the files or folders in a file system drive and the registry keys in the registry drive.

39. Name the type of format commands which are used to format the data.

  • Format-List
  • Format-Table
  • Format-Wide
  • Format-Custom

40. How to rename a variable?

Following example describes how to rename a variable:

PS C:\> $x  
PS C:\> $x=50  
PS C:\> $x  
50  
PS C:\> Rename-Item -Path variable:x -NewName y  
PS C:\> $y  
50  
PS C:\>  

41. Explain the PowerShell get-command?

The get-command is a cmdlet which displays all the installed commands on the computer system. It displays all the commands, filters, aliases, scripts, and applications.

How to execute a PowerShell script?

To run a PowerShell script, you need to follow the given steps:

Step 1: Type the commands in a text editor, such as Notepad.

Step 2: Save the file with the .ps1 extension. Step 3: Open the PowerShell command-shell, and execute the file by typing the name of the PowerShell file.

43. Name some common Automatic Variables

Automatic variables:

  • Describes variables that store state information for PowerShell.
  • These variables are created and maintained by PowerShell.

Some very common Automatic Variables

  • $$ – Contains the last token in the last line received by the session.
  • $? – Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.
  • $^ – Contains the first token in the last line received by the session.
  • $_ – Same as $PSItem. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.
  • $Args – Contains an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block. When you create a function, you can declare the parameters by using the param keyword or by adding a comma-separated list of parameters in parentheses after the function name.
  • $Error – Contains an array of error objects that represent the most recent errors. The most recent error is the first error object in the array ($Error[0]).
  • $ForEach – Contains the enumerator (not the resulting values) of a ForEach loop. You can use the properties and methods of enumerators on the value of the $ForEach variable. This variable exists only while the ForEach loop is running; it is deleted after the loop is completed. For detailed information
  • $Home – Contains the full path of the user’s home directory. This variable is the equivalent of the %homedrive%%homepath% environment variables, typically C:\Users.
  • $OFS – $OFS is a special variable that stores a string that you want to use as an output field separator . Use this variable when you are converting an array to a string. By default, the value of $OFS is ” “, but you can change the value of $OFS in your session, by typing $OFS=””. If you are expecting the default value of ” ” in your script, module, or configuration output, be careful that the $OFS default value has not been changed elsewhere in your code.
  • $PID – Contains the process identifier (PID) of the process that is hosting the current Windows PowerShell session.
  • $Profile – Contains the full path of the Windows PowerShell profile for the current user and the current host application. You can use this variable to represent the profile in commands. For example, you can use it in a command to determine whether a profile has been created

44. What does $_ mean in PowerShell?

This is the variable for the current value in the pipe line, which is called $PSItem in Powershell 3 and newer.

1,2,3 | %{ write-host $_ } 
or
1,2,3 | %{ write-host $PSItem } 

For example in the above code the %{} block is called for every value in the array. The $_ or $PSItem variable will contain the current value.

45. What is PowerShell Cmdlets?

A cmdlet is a lightweight command that is used in the Windows PowerShell environment. The Windows PowerShell runtime invokes these cmdlets within the context of automation scripts that are provided at the command line. The Windows PowerShell runtime also invokes them programmatically through Windows PowerShell APIs.

A PowerShell cmdlet is a compiled piece of .NET code, more precisely a single class. Cmdlets are kind of the “native” commands in PowerShell land, being able to handle object input and output as well as usually playing nice and well with the (object-based) pipeline.

Cmdlets have no direct representation in the file system, as they are not programs or similar. They exist solely within PowerShell. You can use the Get-Command cmdlet to query all available cmdlets, functions, etc.

You can write cmdlets with a .NET language, such as C#. With PowerShell v2 there is also the possibility to write so-called advanced functions which behave similarly to cmdlets and have comparable capabilities but are interpreted PowerShell code, instead of compiled classes. This may incur a run-time overhead.

47.  What is the difference between Start-Job vs Start-Process?

Start-Process launches a process that runs interactively.

Start-Job starts a background job and creates a job object that you use to monitor, query, and interact with the job using the cmdlets Get-Job, Receive-Job, Wait-Job, Stop-Job, and Remove-Job. You won’t see any interactive windows or console output until you query the job object with Receive-Job. Also jobs are local to your session. You cannot do a Start-Job in one PowerShell session and Receive-Job in another.

48. What is the order in which execution policy is evaluated?

Windows PowerShell determines the effective policy by evaluating the execution policies in the following precedence order:

  • Group Policy: Computer Configuration
  • Group Policy: User Configuration
  • Execution Policy: Process (or PowerShell.exe -ExecutionPolicy) – CURRENT SCOPE
  • Execution Policy: CurrentUser – SAVED in HKCU registry
  • Execution Policy: LocalMachine – SAVED in HKLM registry

49. What’s the difference between “Write-Host”, “Write-Output”, or “console::WriteLine”?

Write-Output should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen. The pipeline will eventually write it to out-default if nothing else uses it first.

Write-Host should be used when you want to do the opposite.

[console]::WriteLine is essentially what Write-Host is doing behind the scenes.

Run this demonstration code and examine the result.

function Test-Output {
    Write-Output "Hello World"
}

function Test-Output2 {
    Write-Host "Hello World" -foreground Green
}

function Receive-Output {
    process { Write-Host $_ -foreground Yellow }
}

#Output piped to another function, not displayed in first.
Test-Output | Receive-Output

#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output 

#Pipeline sends to Out-Default at the end.
Test-Output 

50. Whats is the difference between Session and PSSession?

You can create user-managed sessions, known as ” PowerShell sessions” or “PSSessions,” on the local computer or on a remote computer. Like the default session, you can run commands in a PSSession and add and create items.

However, unlike the session that starts automatically, you can control the PSSessions that you create. You can get, create, configure, and remove them, disconnect and reconnect to them, and run multiple commands in the same PSSession. The PSSession remains available until you delete it or it times out.

Typically, you create a PSSession to run a series of related commands on a remote computer. When you create a PSSession on a remote computer, PowerShell establishes a persistent connection to the remote computer to support the session.

51. When should I use Write-Error vs. Throw in PowerShell?

Write-Error should be used if you want to inform the user of a non-critical error. By default all it does is print an error message in red text on the console. It does not stop a pipeline or a loop from continuing.

$URL_Format_Error = [string]"..."
Write-Error $URL_Format_Error
return

Throw on the other hand produces what is called a terminating error. If you use throw, the pipeline and/or current loop will be terminated. In fact all execution will be terminated unless you use a trap or a try/catch structure to handle the terminating error.

$URL_Format_Error = New-Object System.FormatException "..."
Throw $URL_Format_Error

END…..!

Rajesh Kumar
Follow me
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x