Google News
logo
PowerShell Interview Questions
PowerShell is a cross-platform task automation solution made up of a command-line shell, a scripting language, and a configuration management framework. PowerShell runs on Windows, Linux, and macOS.
 
PowerShell is a modern command shell it was designed on the .NET Framework and the most recent version is created on .NET Core. It is platform-independent and open-source.
PowerShell is a modern command shell that includes the best features of other popular shells. Unlike most shells that only accept and return text, PowerShell accepts and returns .NET objects. The shell includes the following 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
PowerShell is a scripting language, commonly used for automating the management of systems. It is also used to build, test, and deploy solutions, often in CI/CD environments. PowerShell is built on the .NET Common Language Runtime (CLR). All inputs and outputs are .NET objects. No need to parse text output to extract information from output. The PowerShell scripting language includes the following features :
 
* Extensible through functions, classes, scripts, and modules

* Extensible formatting system for easy output

* Extensible type system for creating dynamic types

* Built-in support for common data formats like CSV, JSON, and XML
PowerShell is already installed in all the latest versions of Windows. We need to start PowerShell by the following given steps :
 
1. Search for the Windows PowerShell. Select and Click.
PowerShell

2. PowerShell Window will open.

Power Shell Window
A PowerShell pipeline is the series of statements which are connected by the pipe '|' operator. In a command, each pipeline operator is used to send the output or result of the preceding command to the next command.
 
Following box describes the syntax of a pipeline :
Command-1 | Command-2 | Command-3
* We use () Parentheses Brackets in compulsory arguments.

* We use {} Braces Brackets for blocked statements

* We do not normally use [] Square Brackets. These brackets specify optional items.
Cmdlets are native PowerShell commands, not stand-alone executables. Cmdlets are collected into PowerShell modules that can be loaded on demand. Cmdlets can be written in any compiled .NET language or in the PowerShell scripting language itself.
 
Cmdlet names : PowerShell uses a Verb-Noun name pair to name cmdlets. For example, the Get-Command cmdlet included in PowerShell is used to get all the cmdlets that are registered in the command shell. The verb identifies the action that the cmdlet performs, and the noun identifies the resource on which the cmdlet performs its action.
Microsoft implements updates and the latest features separately for the PowerShell version, but let us look at the list of the primary features and characteristics of PowerShell :
 
Remote commands : Admins can execute remote operations on one or numerous computers, taking the benefit of technologies like WS-Management and Windows Management Instrumentation. For example, the WS-Management protocol, allows the customer to execute PowerShell scripts and commands on remote computers.

Pipelining : Owing to PowerShell, commands can be connected together via the pipe operator, represented as |. This approach permits the output from a particular command to turn into the input for the subsequent command in the pipeline sequence. The PowerShell pipeline allows objects, instead of flowing from one cmdlet to another and text strings.

Tab expansion : Tab expansion is an execution of auto-completion, which executes the cmdlets, properties, and parameter names by pushing the Tab key once.

Discoverability : Consumers can uncover PowerShell's attributes with the help of cmdlets including Get-Command, which constructs a list of all the commands, like cmdlets and functions, accessible on a particular computer. Parameters can be utilized to limit the scope of the search.
9 .
Can PowerShell scripts be created for the deployment of SharePoint components?
If the web part is created employing VS2010, SharePoint components can be deployed with the help of ctrl+f5. Features of the web part can be activated through the PowerShell script.
Comparison Operators compares value in PowerShell.  Four types of comparison operators are used equality, match, containment and replace.  In PowerShell, one of the key comparison operators is –eq that is used instead of “=” sign for declaring variables.  Likewise, there are other operators like –ne for “not equal” , -gt ( greater than ) or –lt (less than).
11 .
What do you understand by get-command in PowerShell?
PowerShell’s get-command is applied to fetch cmdlets. For instance, if anyone is searching cmdlet between E and K, then the get-command would look like - get-command [ E–K ]*
Get command in PowerShell is used to fetch other cmdlets, for example 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 ]*
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( "D:", \\expert\FTL901 )

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

* 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
A PowerShell module is a conjoined portion of PowerShell functions or grouped code. All PowerShell cmdlets and providers are incorporated by a module or a snap-in. The receivers of these modules can add the commands included in the module to their PowerShell sessions to use them like built-in commands. The most uncomplicated method to build a PowerShell module is to save the script as a PSM1 file. 
 
A PowerShell module includes 4 fundamental elements :
 
* A PSM file, being the module;
* Help files or scripts required by the module;
* A manifest file that defines the module
* A directory that accumulates the content.

There are four types of PowerShell modules:
 
Script module : A PSM1 file that includes different functions to allow admins to execute management functions, import, and export.

Binary module : A .NET framework assembly (DLL file) that includes saved code. Programmers generally utilize a binary module to build cmdlets with strong features not easily done with a PowerShell script.

Manifest module : A module (PSM1) file with an associated PSD1 file (manifest).

Dynamic module : A dynamic module is dynamically built on demand by a script. It isn't reserved or loaded to persistent storage.
PowerShell is a famous instrument for many MSPs as its scalability allows to streamline management tasks and develop insights into instruments, specifically over medium or large networks. 
 
Here’s how PowerShell's usefulness can change your workflow :
 
Automate time-consuming tasks : With the help of Automate time-consuming tasks provided by PowerShell, you don’t have to complete the identical task again and again or even take the time for manual configuration. For example, you can employ cmdlets like Get-Command to look for other cmdlets, Get-Help to find these cmdlets’ syntax and benefits, and Invoke-Command to drive a common script remotely or locally even with batch control.

The benefit of command-line interfaces : The added advantage of command-line interfaces such as PowerShell is the access they give you to a system's file system. PowerShell constructs the Windows Registry, hard-to-find data in files, and digital signature certificates visible even though it is housed on many systems. This information can then be exported for the purpose of reporting.

Offer network-wide workarounds : Making use of PowerShell allows you to get around the limitations of software or program, particularly on a business-wide scale. For example, PowerShell can be employed to reconfigure the default settings of a program over an entire network. This could be helpful if a company wishes to roll out a certain protocol to all its customers—say, convincing users to employ two-factor authentication (2FA) or modify their password every other month.

Take your endeavours across various devices : PowerShell serves as a lifesaver if your script requires to be run across countless systems, especially if some of them are remote devices.If you’re attempting to incorporate a solution on quite a few devices or servers at once, you don’t want to log in individually into devices. In minutes PowerShell can assist you to collect information about numerous devices, as compared to the endless time it would require to scan each device manually. Once you allow PowerShell remoting, you’ll be able to enable your scripts to reach several machines at once, letting you install updates, settings configuration, compile information, and more importantly, cutting down hours of work and travel time.

Ultimately, as every Windows 10 computer should have pre-installed it, it’s not challenging to understand PowerShell. As an MSP, comprehending PowerShell not only places you a step ahead of your peers but offers you a broad range of useful capabilities. If you are aware of scripting cmdlets for PowerShell, it’s that much uncomplicated for you to heighten your efforts and deliver precise, adjustable, and quick service to customers.
Followings are the six types of execution policy in PowerShell :
 
AllSigned : It is an execution policy which executes only those scripts that are signed by a trusted publisher with a digital signature.
 
RemoteSigned : PowerShell will execute any script which is written on a local computer. But the script which is downloaded from the internet must require the digital signature from the trusted publisher.
 
Restricted : This type of execution policy does not allow to execute any script but permits the individual commands. This policy is available for the Windows client computer by default.
 
Undefined : No execution policy is set or defined in the current scope.
 
Bypass : It is mainly designed for those configurations in which a PowerShell script is built into a larger application. In this type of policy, no warnings and no prompts are provided.
 
Unrestricted : This policy is the default for Non-Window computers. This policy executes those scripts which are unsigned.
Try : It is a part of a script where we want the PowerShell to monitor the errors. If an error occurs in this block, the automatic variable $Error stores the error. And then, the PowerShell searches the Catch block to handle the error.
 
Catch : In a PowerShell script, it is a part which handles the errors generated by the Try block.
 
Finally : In a PowerShell script, it is a part which releases the resource that no longer needed by a script.
PowerShell’s hash table can be referred to as a dictionary. Basically, it is a series that enables users in storing data with a pair association known as “key-value”. Here, both “key”, as well as “value”, might comprise any length and data. In order to declare hash table users will have to apply @ in front of curly braces.
PowerShell Array is used to run scripts on remote computers. To create a PowerShell Array, users will need to create a variable, as well as they will have to assign the PowerShell Array.  PowerShell Arrays are expressed with a “@” symbol and illustrated as a hashtable.
For instance, it would be like -
$arrmachine = @ ( “machine1” , “machine2” , “machine3”)
PowerShell Command Prompt (CMD)
1. It is a task-based command-line shell and associated scripting language which is based on the .NET framework. 1. It is the default command-line interpreter for the Microsoft Windows Operating System.
2. It can interpret both the commands of a batch and PowerShell. 2. It can interpret only the commands of a batch.
3. It controls and automates the Windows operating system and applications on a Windows server. 3. It executes the commands which are specified on the console to debug the problem.
4. The output generated by the PowerShell is not just a stream of characters (text) but a collection of objects. 4. The output generated by the command prompt is just a stream of characters (text).
5. It is both a shell and scripting environment which supports the creation of large files for managing the windows operating system. 5. It is just a shell environment, which allows a user to do only easy and basic scripts for the execution of the batch file.
This question is a great opportunity to get an understanding of the candidate's knowledge of PowerShell core concepts and his/her favourite PowerShell features. 
 
For instance, one of the most essential distinctions between PowerShell and bash is that PowerShell is object-oriented whereas bash is text-oriented. PowerShell treats input and output as an object and Bash always considers input and output as a text structure.
 
PowerShell's user interface is a graphical command-line interface CLI. whereas Bash's user interface shell is a text-based command-line interface. PowerShell can run on any version of Windows ranging from Windows 97 to Windows 10. Bash is specifically designed for Linux and Unix operating systems from the first day.
Old WMI
* Employs the old-style native code providers and a repository.
* Accessible only on Windows as mentioned.
* It has been more or less deprecated which means it’s is not focused on further advancement or development but can be used..

New WMI
* Backs old-style native code providers and a repository, along with new-style MI providers.
* Accessible only on Windows as mentioned. It has a stateless relationship with the remote machine.
* The main attraction of the new WMI is that it employs WSMan and no more DCOM errors are possible with this.
Like other scripting languages, PowerShell also supports single or multi-line comments.
 
Single-Line comments : "Those comments which use the (hash) # symbol at the beginning of each line".
 
Syntax of single-line comment :
<Any Command or statement> # <Any comment>  
Multi-line comments : "Those comments which use the # (hash) symbol at the end of last line and beginning of the first line".
 
Syntax of Multi-line comment :
<# Multiple-line Comment.........................  
....................  
................................................#>  
Statement-1  
Statement-2  
Statement-N  
win32_computersystem.
We can use this as follows :
PS C:> $server = gwmi -cl win32_computersystem
PS C:> $server.SystemType X86-based PC
CIM Old WMI New WMI
CIM is a Vendor-neutral and industry-standard designed way of manifestation of management information. Old WMI is Microsoft’s initial incorporation of CIM. New WMI was released alongside WMF v3 in the year 2012 and it was compliant to the latest CIM standards.
It is designed by another company named the DMTF It is designed by Microsoft It is designed by Microsoft as well.
It not available It is available in PowerShell v1 It is available in PowerShell v3.
It employs  WSMan which is a standard developed by DMTF. It used DCOM and RPCs Remote Procedure Calls.    It employs WSMan and no more DCOM errors are possible with this.
It can work on any platform. Works on Windows only. Works on Windows only.
It owns WSMan Port – 5985 (HTTP) and 5986(HTTPS) for its purpose. It has RPC port- 135 for use It owns WSMan Port – 5985 (HTTP) and 5986(HTTPS) for use.
The four types of PowerShell scopes are Global, Local, Script, Private.
 
Global :
* The scope that is in effect while PowerShell runs or when you start a new session or run space.
* Variables and functions that are included when PowerShell begins have been designed in the global scope. This contains preference variables and automatic variables.
* This also comprises functions, variables, aliases that are within your PowerShell profile.

Local :
* The current scope. The local scope can be the global scope or any other scope.

Script :
* The scope is built while a script file runs. Just the commands in the script operate in the script scope. To the commands in a script, the script scope is the local scope.

Private :
* You cannot see the items in private scope outside of the current scope. You can utilize the private scope to build a private version of an item having the exact name in another scope.
PowerShell offers a number of language constructs that allow you to manage the flow of your script and let you make decisions about what it should do. A few of the language constructs have conditionals, switches, loops, and variables.
 
Conditionals : This language construct is utilized to assess a conditional expression. If the conditional expression is true, a script block is accomplished:
if ( $i -eq 1)
{
   ## Do something
}
Else
{
   ## Do something
} 
Switch : The switch statement lets you deliver a variable and a list of potential values. If the value matches the variable, then its script block is completed..
switch  ($i)  {
    0
    {
       Write-Host “I is 0”
    }
    1
    {
       Write-Host “I is 0”
     }
     Default
     {
       Write-Host “I is 0”
      }
  }
Loops : What while statement does is repeat a block of code  as long as the below mentioned conditional expression is working:
while ($i -eq 0)  {
         ## do something
}
The do loop is identical to the while loop. The only distinction is PowerShell runs the do loop at the end of the loop.
do  {
     ## do something
  }  while  ($i -lt 0)
When you employ a foreach loop, PowerShell repeats the code for every item cited in the script.
$array = ( ‘item1’ , ‘item2’ , ‘item3’)
  foreach ($item in $array)  {
}
Make use of a for loop to execute statements constantly till a condition is met.
for ($i = 0; $i -lt 5; $i++)
  {
     $i
   }
A PowerShell variable is a unit of memory which is used to store the data. You can easily store all the types of values in the variable of PowerShell. In the variables, PowerShell contains integers, strings, and objects.
Declaration : In PowerShell, you can declare a variable by using the $ (dollar) sign at the beginning of the variable name. Following syntax describes how to declare the variable :
$ <variable_name>
For example : $var
 
Creation or Initialization : In PowerShell, you can create a variable by assigning the value to a variable using the assignment operator. Following syntax describes how to declare the variable :
$ <variable_name> = <value>
There are so many predefined variables in PowerShell, which are known as the automatic variables. These variables mainly store the information about the PowerShell, and created and maintained by the PowerShell. Any user can't change or update the value of these variables.
 
Following are some very popular Automatic Variables are :
 
$ : This variable includes the last token available in the last line that is received by the session.

$? : This variable may include the completion status of the last operation. If the last operation succeeded, its value is TRUE and FALSE if it has failed.

$^ : It may include the first token of the last line obtained by the session.

$Args : Includes a collection of the undeclared parameters or parameter values. These are handed over to a script, script block, or function. When you construct a function, you can display the parameters by making use of the param keyword or by incorporating a comma-separated list of parameters in parentheses just after the function name.

$Error : This variable includes an array of error objects that represent the most recent errors. The current mistake is the first error object in the array ($Error[0]).

$ForEach : This variable includes the enumerator (not the resulting values) of a ForEach loop. You can make use of the properties and processes of enumerators on the value of the $ForEach variable. This variable lives only while the ForEach loop is operating; it gets deleted post the completion of the loop.

$Home : This variable includes the full path of the customer’s home directory. This variable is the counterpart of the %homedrive%%homepath% environment variables, commonly known as C:\Users<UserName>.

$OFS : $OFS is a remarkable variable that saves a string (Series of characters) that you wish to utilize as an output field separator. Employ this variable when you are transforming an array into a string. By default, the value of $OFS is " ", but you can modify the value of $OFS in your session, by just typing $OFS="<value>". If you are anticipating the default value of " " in your module, script, or configuration output, be mindful that the $OFS default value has not been modified anywhere in your code.
Following are the different types of operators in PowerShell :
 
* Arithmetic Operator
* Assignment Operator
* Comparison Operators
* Logical Operators
* Redirection Operators
* Split and Join Operators
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
PowerShell utilizes execution policies to regulate how it loads configuration files and runs scripts. Implementation of these policies only happens on Windows platforms. The PowerShell execution policies are mentioned below :

AllSigned :
* The scripts can run.
* Needs that all scripts and configuration files be signed by a reliable publisher, which includes scripts that you compose on the local computer.
* Encourages you before executing scripts from publishers that are still not categorized as untrusted or trusted.
* Risks running signed, but vicious, scripts.

Bypass :
* Nothing is stopped and there are no alerts or prompts generated.
* The Bypass execution policy is created for configurations in which a PowerShell script is constructed into a larger application or for configurations in which PowerShell is the basis for a program that possesses its security model.

Default :
* Restricted for Windows clients.
* RemoteSigned for Windows servers.

RemoteSigned :
* The default execution policy for the Windows system.
* Scripts can run.
* A digital signature from an authorized publisher is required on internet downloaded scripts and configuration files. It contains email and instant messaging programs.
* It doesn't need digital signatures on scripts that are not downloaded from the internet and composed on the local computer.
* It executes internet downloaded scripts that are not signed if the scripts are unblocked, like utilizing the Unblock-File cmdlet.
* Risks executing unsigned scripts from sources except for the internet and signed scripts that could be malicious in nature.

Restricted :
* The default implementation policy for Windows client computers.
* Allows individual commands, but does not permit scripts.
* Stops operating all script files, including configuration files (.ps1xml), PowerShell profiles (.ps1), and module script files (.psm1) formatting

Undefined :
* There is no implementation policy specified in the current scope.
* The execution policy is Restricted for Windows clients and RemoteSigned for Windows Server if the implementation policy in all scopes is Undefined.

Unrestricted :
* The default execution policy for non-Windows systems and cannot be modified.
* Unsigned scripts can operate. There is a chance of running malicious scripts.
* Alerts the customer before running scripts and configuration files that do not belong from the Local intranet zone.