Powershell Interview Questions

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Number of ways to create an Object in PowerShell

# 1. Using Hashtables [pscustomobject]@{ firstname = 'Prateek' lastname = 'Singh' } # 2. Using Select-Object Select-Object @{n='firstname';e={'Prateek'}},@{n='lastname';e={'Singh'}} -InputObject ''

Number of ways to create an Object in PowerShell

# 1. Using Hashtables [pscustomobject]@{ firstname = 'Prateek' lastname = 'Singh' } # 2. Using Select-Object Select-Object @{n='firstname';e={'Prateek'}},@{n='lastname';e={'Singh'}} -InputObject '' # 3. 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' # 4. Using New-Object and hashtables $properties = @{ firstname = 'Prateek' lastname = 'Singh' } $o = New-Object psobject -Property $properties; $o

How to identify if a windows machine is 32/64 bit? How to find operating system name/version?

# method 1 $env:PROCESSOR_ARCHITECTURE (Get-WmiObject Win32_OperatingSystem).Name (Get-WmiObject Win32_OperatingSystem).caption

How to form credentials objects in PowerShell?

$UserName = 'Prateek' $Password = 'Password@123' | ConvertTo-SecureString -AsPlainText -Force

How to form credentials objects in PowerShell?

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

How to extend a Boot Partition using PowerShell?

$part = Get-Partition |? {$_.isboot} $size = Get-PartitionSupportedSize -DriveLetter $part.DriveLetter Resize-Partition -DriveLetter $part.DriveLetter -Size $size.SizeMax -Verbose

How to reverse order of a String

$str[$($str.Length-1)..0] -join ''

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 -

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 Execution Policy: LocalMachine - SAVED in HKLM registry

Powershell Workflows

1. Persist 2. Parallelism ○ Parallel ○ Foreach -Parallel 3. Sequence InlineScript

Execution Policies Types of Execution Policy? 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.

You have a script which uses Read-Host to prompt the user for an IP address. You need to make sure the user inputs a valid IP address. How would you do that ?

1. Splitting the address in 4 elements and try to cast them to a [byte] 2. A regular expression [regex] Cast the input string to the [System.Net.IPAddress] class

What is a Filter?

A filter is a function that just has a process scriptblock PS C:\> filter myFilter { $_ } PS C:\> @(1,2,3) | myFilter 1 2 3

What is an advanced function?

Advanced functions allow you to write functions that can perform operations that are similar to the operations you can perform with cmdlets. Advanced functions are helpful when you want to quickly write a function without having to write a compiled cmdlet using a Microsoft .NET Framework language. These functions are also helpful when you want to restrict the functionality of a compiled cmdlet or when you want to write a function that is similar to a compiled cmdlet.

What is $_ and $PSItem variable

Both represents the Current object in pipeline

TOP 5 PS Commands

Get-Command Get-Help Set-ExecutionPolicy Get-Service ConvertTo-HTML

1. Get-Command

Get-Command is an easy-to-use reference cmdlet that brings up all the commands available for use in your current session.

5. ConvertTo-HTML

If you need to extract data that you can use in a report or send to someone else, the ConvertTo-HTML is one simple way to do so. To use it, pipe the output from another command to the ConvertTo-HTML command and use the -Property switch to specify which output properties you want in the HTML file. You'll also need to provide a file name.

4. Get-Service

It's also helpful to know what services are installed on the system. You can easily access this information with the following command:

3. Set-ExecutionPolicy

Microsoft disables scripting by default to prevent malicious scripts from executing in the PowerShell environment. Developers want to be able to write and execute scripts, however, so the Set-ExecutionPolicy command enables you to control the level of security surrounding PowerShell scripts. You can set one of four security levels:

How to Rename a Variable?

PS C:\> $a = 1..3 PS C:\> $a 1 2 3 PS C:\> Rename-Item -Path variable:a -NewName b PS C:\> $b 1 2 3

How to find the Largest File in a Folder?

PS C:\> Get-ChildItem C:\Data\Powershell\PoshBot\ -recurse | Sort-Object Length -desc | Select-Object -f 1 Directory: C:\Data\Powershell\PoshBot\PoshBot\en-US

How to find free space on a drive using PowerShell?

PS C:\> Get-PSDrive PS C:\> Get-Volume

Explain what is PowerShell?

Power shell is an extendable command shell and a scripting language for Windows. • PowerShell is a shell designed especially for system administrators. • Open Source and Platform Independent (Windows/Linux/Mac) • Object oriented, not text-based • Built on .NET framework Interactive prompt and a scripting environment.

Powershell adaptive systems

PowerShell does not have support for creating types directly, but instead favors monkey patching using PowerShell's Adaptive Type System (ATS) to add variables, properties, methods, and ScriptBlocks to a PSObject instance. • Add-Member With ATS you are in control of your own destiny. (If you don't like the world - change it yourself. [then share to help others]) ~JSnover

Conclusion- PowerShell vs Python

PowerShell vs Python does not make an apple-apple comparison in many ways. Python is an interpreted high-level programming language whereas PowerShell provides a shell scripting environment for Windows and is a better fit if you choose to automate tasks on the Windows platform. Choosing among these depends on the kind of environment you are using as with Python you do get a handsome support to work on Windows OS. Stay tuned to our blog for more articles.

How to enable PSRemoting on a server? SERVER SIDE

SERVER SIDE: Enable-PSRemoting -Force # The asterisk is a wildcard symbol for all PCs. If instead you want to restrict computers that can connect, you can replace the asterisk with a comma-separated list of IP addresses or computer names for approved PCs. Set-Item wsman:\localhost\client\trustedhosts * # After running that command, you'll need to restart the WinRM service so your new settings take effect. Type the following cmdlet and then hit Enter: Restart-Service WinRM

How to enable PSRemoting on a server? CLIENT SIDE And how to TEST

Set-Item wsman:\localhost\client\trustedhosts * Test-WSMan

2. Get-Help

The Get-Help command is essential for anyone using PowerShell, providing quick access to the information you need to run and work with all of the available commands.

2) What are the key characteristics of PowerShell?

The key characteristics of PowerShell are • PowerShell is object-based and not text based • Commands in PowerShell are customizable It is a command line interpreter and scripting environment

Error handling?

The second part of the catch (pun intended again), and this is where many PowerShell beginners get tripped up, is that the Catch block will execute only if a cmdlet in the Try block raises a terminating error. So, the Get-ChildItem example above would not trigger the Catch block. 2 possible solutions : • Set the global variable $ErrorActionPreference to "Stop" Use the cmdlet parameter -ErrorAction to ensure any error from that cmdlet is terminating.

What is Splatting?

Use a hash table to splat parameter name and value pairs. You can use this format for all parameter types, including positional and named parameters and switch parameters. $HashArguments = @{ Path = "test.txt" Destination = "test2.txt" WhatIf = $true } Copy-Item @HashArguments

How to find installed applications on a Windows Computer?

Use the Get-ItemProperty cmlet to pull installed softwares from the registries. Searching the registry is a lot faster and can return some other useful information information such as the UninstallString. Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate

Powershell Pipelines

• A pipeline is a series of commands connected by pipeline operators (|) or ASCII 124. Each pipeline operator sends the results of the preceding command to the next command. • A very powerful command chain or "pipeline" that is comprised of a series of simple commands. • Objects from previous cmdlet binds parameters (ByValue/ByPropertyName) to the cmdlet following the pipeline Pipeline processes one object at a time

Explain what is the function of $input variable?

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

Powershell Scopes

• Global, Local, Script, Private Global • The scope that is in effect when PowerShell starts. and is the Default scope • Variables and functions that are present when PowerShell starts have been created in the global scope. This includes automatic variables and preference variables. • This also includes variables, aliases, and functions that are in your PowerShell profile. Local • The current scope. The local scope can be the global scope or any other scope. Script • The scope that is created while a script file runs. Only the commands in the script run in the script scope. To the commands in a script, the script scope is the local scope. Private Items in private scope cannot be seen outside of the current scope. You can use private scope to create a private version of an item with the same name in another scope.

#Require statement

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

How to write PowerShell scripts that can withstand reboots or Interruptions?

• WorkFlows RunOnce Registry key

How to map Network Drives using PowerShell? and persist them

•Using WScript.Network COM object $Net = $(New-Object -ComObject Wscript.Network ) $Net.MapNetworkDrive( "S:", '\\localhost\filemov',$true ) • Using net command from Native CMDnet use M: \\Server\Share /Persistent:Yes • Using PSDrive New-PSDrive -Persist -Name "y" -PSProvider "FileSystem" -Root "\\localhost\filemov"


Ensembles d'études connexes

Health, Illness, & Medicine TCU Exam 2

View Set

Chapter 6-Strategic Management (CAP)

View Set

Chapter 38 - Thyroid, parathyroid, and adrenal

View Set

AP Psych: Unit 7 & 8: Cognition and Language and Conscious

View Set

Practice test Agile tester ISTQB.org

View Set