FullStackFSCCafé
 
 
Sign in with GoogleSign in with Google. Opens in new tab
Kill Your Tech Interview
3877 Full-Stack, Algorithms & System Design Interview Questions
Answered To Get Your Next Six-Figure Job Offer
      
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

23 PowerShell Interview Questions DevOps Engineers Must Master

Powershell is getting more popular because configuration management for Cloud is getting more popular. These days, if you don't do PowerShell, you don't do Windows and Azure. Every (Windows) Sys Admin and DevOps level position has PowerShell listed in the job description. Follow along to catch up on the 15 top PowerShell interview questions and answers you must be aware of before your next DevOps interview.

Q1: 
What is PowerShell?

Answer

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

The consistency of PowerShell is one of its primary assets. For example, if you learn how to use the Sort-Object cmdlet, you can use that knowledge to sort the output of any cmdlet. You don't have to learn the different sorting routines of each cmdlet. PowerShell combines an interactive shell and a scripting environment. PowerShell can access command-line tools, COM objects, and .NET class libraries. PowerShell is based on object not text. The output of a command is an object. You can send the output object, through the pipeline, to another command as its input.


Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q2: 
How to map Network Drives using PowerShell?

Answer
  • Using WScript.Network COM object

    $Net = $(New-Object -ComObject Wscript.Network )
    $Net.MapNetworkDrive( "S:", '\\localhost\filemov',$true )
  • Using net command from Native CMD net use M: \\Server\Share /Persistent:Yes

  • Using PSDrive

    New-PSDrive -Persist -Name "y" -PSProvider "FileSystem" -Root   "\\localhost\filemov"

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q3: 
What is PowerShell execution policies?

Answer

The PowerShell execution policy is the setting that determines which type of PowerShell scripts (if any) can be run on the system. PowerShell's execution policy is a safety feature that controls the conditions under which PowerShell loads configuration files and runs scripts.


Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q4: 
What is a PowerShell session?

Answer

A session is an environment in which PowerShell runs.

Each time you start PowerShell, a session is created for you, and you can run commands in the session. You can also add items to your session, such as modules and snap-ins, and you can create items, such as variables, functions, and aliases. These items exist only in the session and are deleted when the session ends.


Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q5: 
What would be the PowerShell equivalent of echo?

Answer

There are several ways:

  • Write-Host: Write directly to the console, not included in function/cmdlet output. Allows foreground and background colour to be set.
  • Write-Debug: Write directly to the console, if $DebugPreference set to Continue or Stop.
  • Write-Verbose: Write directly to the console, if $VerbosePreference set to Continue or Stop.
  • echo as an alias mapping to Write-Output

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q6: 
Explain what is #Requires statement?

Answer
  • The #Requires statement prevents a script from running unless specific conditions the PowerShell version, modules, snap-ins, module and snap-in version, and edition prerequisites are met.
  • If the prerequisites are not met, PowerShell does not run the script.
#Requires -Version <N>[.<n>]
#Requires -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]
#Requires -Modules { <Module-Name> | <Hashtable> }
#Requires -PSEdition <PSEdition-Name>
#Requires -ShellId <ShellId>

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q7: 
Explain what is the function of $input variable?

Answer
  • Contains an enumerator that enumerates all input that is passed to a function.
  • The $input variable is available only to functions and script blocks (which are unnamed functions).
  • In the Process block of a function, the $input variable enumerates the object that is currently in the pipeline.
  • When the Process block completes, there are no objects left in the pipeline, so the $input variable enumerates an empty collection.
  • If the function does not have a Process block, then in the End block, the $input variable enumerates the collection of all input to the function.

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q8: 
How Cmdlets Differ from Commands?

Answer

Cmdlets differ from commands in other command-shell environments in the following ways:

  • Cmdlets are instances of .NET Framework classes; they are not stand-alone executables.
  • Cmdlets can be created from as few as a dozen lines of code.
  • Cmdlets do not generally do their own parsing, error presentation, or output formatting. Parsing, error presentation, and output formatting are handled by the Windows PowerShell runtime.
  • Cmdlets process input objects from the pipeline rather than from streams of text, and cmdlets typically deliver objects as output to the pipeline.
  • Cmdlets are record-oriented because they process a single object at a time.

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q9: 
How PowerShell is Object Oriented?

Answer

The PowerShell pipeline deals with objects, not just a text stream a a Unix pipeline does. All variables are instances of objects as well. A PowerShell cmdlet is a .NET class extending from PSCmdlet.

A cmdlet is a lightweight command that is used in the Windows PowerShell environment. Cmdlets perform an action and typically return a Microsoft .NET Framework object to the next command in the pipeline. To write a cmdlet, you must implement a cmdlet class that derives from one of two specialized cmdlet base classes.


Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q10: 
How to create an object in PowerShell?

Answer
  1. Using Hashtables
    [pscustomobject]@{
        firstname = 'Prateek'
        lastname =  'Singh'
    }
  1. Using Select-Object
    Select-Object @{n='firstname';e={'Prateek'}},@{n='lastname';e={'Singh'}} -InputObject ''
  1. Using New-Object and Add-memeber
    $obj = New-Object -TypeName psobject
    $obj | Add-Member -MemberType NoteProperty -Name firstname -Value 'Prateek'
    $obj | Add-Member -MemberType NoteProperty -Name lastname -Value 'Singh'
  1. Using New-Object and hashtables
    $properties = @{
        firstname = 'Prateek'
        lastname = 'Singh'
    }       
    $o = New-Object psobject -Property $properties; $o

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions
Source: ss64.com

Q11: 
How to form credentials objects in PowerShell?

Answer
    $UserName = 'Prateek'
    $Password = 'Password@123' | ConvertTo-SecureString -AsPlainText -Force
    
    # method 1
    [pscredential]::new($Username,$Password)
    
    # method 2
    New-Object System.Management.Automation.PSCredential($UserName,$Password)

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q12: 
Mention some types of Execution Policy?

Answer

There are 6 types of execution policies

  1. Restricted This is the default. PowerShell will not run any script, including PowerShell profiles.

  2. RemoteSigned PowerShell will run any script that you create locally. But any script that has been detected as coming from the Internet, such as via Internet Explorer, Microsoft Outlook, Mozilla Firefox or Google Chrome must be digitally signed with a code signing certificate that is trusted by the computer.

  3. AllSigned PowerShell will not run any script unless it has been digitally signed with a trusted code signing certificate.

  4. Unrestricted PowerShell will make no attempts to hinder script execution and will run any script. If the script comes from an untrusted source, like the Internet, you will be prompted once to execute it. Though it is not preferred.

  5. Bypass There is also a Bypass policy, which I don’t recommend for daily use. This policy will run any script without question or prompting. The assumption is that you have taken steps outside of Nothing is blocked and there are no warnings or prompts.PowerShell to verify the safety and integrity of the script.

  6. Undefined There is no execution policy set in the current scope. If the execution policy in all scopes is Undefined, the effective execution policy is Restricted, which is the default execution policy.


Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q13: 
Name some common Automatic Variables

Answer

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

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q14: 
What does $_ mean in PowerShell?

Answer

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.


Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q15: 
What is PowerShell Cmdlets?

Answer

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.


Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q16: 
What is the difference between Start-Job vs Start-Process?

Answer
  • 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.

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q17: 
What is the order in which execution policy is evaluated?

Answer

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

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

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q18: 
What's the difference between “Write-Host”, “Write-Output”, or “console::WriteLine”?

Answer
  • 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 

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q19: 
Whats is the difference between Session and PSSession?

Answer
  • 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.


Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

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

Answer
  • 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

Having Tech or Coding Interview? Check 👉 24 PowerShell Interview Questions

Q21: 
Is there an equivalent of bash ampersand (&) for forking/running background processes?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q22: 
Does PowerShell support OOP?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q23: 
Explain what is Powershell Scopes?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe
 

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

Cosmos DB has gained popularity among developers and organizations across various industries, including finance, e-commerce, gaming, IoT, and more. Follow along and learn the 24 most common and advanced Azure Cosmos DB interview questions and answers...
More than any other NoSQL database, and dramatically more than any relational database, MongoDB's document-oriented data model makes it exceptionally easy to add or change fields, among other things. It unlocks Iteration on the project. Iteration f...
Unit Tests and Test Driven Development (TDD) help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outpu...
Domain-Driven Design is nothing magical but it is crucial to understand the importance of Ubiquitous Language, Domain Modeling, Context Mapping, extracting the Bounded Contexts correctly, designing efficient Aggregates and etc. before your next DDD p...
At its core, Microsoft Azure is a public cloud computing platform - with solutions including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) that can be used for services such as analytics, virtual c...
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. Follow along to refresh your knowledge and explore the 52 most frequently asked and advanced Node JS Interview Questions and Answers every...
Dependency Injection is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain. DI is also useful for decoupling your system. DI also allows easier unit testing without having to hit a database and...