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.
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.
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"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.
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.
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#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.#Requires -Version <N>[.<n>]
#Requires -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]
#Requires -Modules { <Module-Name> | <Hashtable> }
#Requires -PSEdition <PSEdition-Name>
#Requires -ShellId <ShellId>Cmdlets differ from commands in other command-shell environments in the following ways:
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.
[pscustomobject]@{
firstname = 'Prateek'
lastname = 'Singh'
} Select-Object @{n='firstname';e={'Prateek'}},@{n='lastname';e={'Singh'}} -InputObject '' $obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name firstname -Value 'Prateek'
$obj | Add-Member -MemberType NoteProperty -Name lastname -Value 'Singh' $properties = @{
firstname = 'Prateek'
lastname = 'Singh'
}
$o = New-Object psobject -Property $properties; $o $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)There are 6 types of execution policies
Restricted This is the default. PowerShell will not run any script, including PowerShell profiles.
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.
AllSigned PowerShell will not run any script unless it has been digitally signed with a trusted code signing certificate.
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.
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.
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.
Automatic variables:
Some very common Automatic Variables
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.
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.
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.Windows PowerShell determines the effective policy by evaluating the execution policies in the following precedence order:
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 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.
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
returnThrow 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_ErrorRust 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...