Powershell

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

create an array named Array1 containing the values 1 2 and 3

$array1 = @(1,2,3)

create an array named Array2 containing the values 4, 5, and 6

$array2 = @(4,5,6)

create an array named Array3 that contains the sum of sequential numbers in two other Arrays named Array1 and Array2. Array1 contains the values 1, 2 &3. Array2 contains the values 4, 5, & 6.

$array3 = @() $array3 += $array1[0] + $array2[0] $array3 += $array1[1] + $array2[1] $array3 += $array1[2] + $array2[2] $array3

create a variable called $num and set it equal to ten. Then use an if else statement to write "It's 10" if the $num variable is equal to ten or else write "not 10" if the $num variable is not equal to ten

$num=10 <enter key>, if($num -eq 10) {write-host "it's 10"} else {write-host "not 10"}

create a variable called $num and set it equal to ten. Then use an if, elseif, else statement to write "It's 10" if the $num variable is equal to ten or to write "it's 11" if $num = 11 or else write "not 10 or 11" if the $num variable is not equal to ten or 11

$num=10 <enter key>, if($num -eq 10) {write-host "it's 10"} elseif ($num -eq 11) {write-host "It's 11} else {write-host "not 10 or 11"}

check the version of powershell that you are running

$psversiontable.psversion

Find the status of the service 'Spooler' and give the output as 'Service is Good' if it is in the 'Running' state and as 'Service is Bad' if it is in Stopped state.

$service = Get-service spooler | select status if($service.status -eq "Running") { Write-Host "Service is Good" -ForegroundColor Green } elseif($service.status -eq "stopped") { Write-host "service is bad" -foregroundcolor Red }

Variables may be converted from one type to another by explicit conversion. create the variable $v and set it = to 1.9 then convert it to integer.

$v = 1.9 (hit the enter key and then) [int32]$v

call the script FirstScript.ps1 located at X:\FirstScript.ps1

& "X:\FirstScript.ps1"

what symbol is the call operator in a powershell script

& is the call operator which allows you to execute a command, a script, or a function.

See all aliases for the computername parameter to the get-eventlog command

(get-command get-eventlog | select -ExpandProperty parameters) .computername.aliases

What does ++ mean in powershell

++ increases the value of a variable, assignable property, or array element by 1. (double minus does the opposite)

what is the meaning of += in powershell

+= Increases the value of a variable by the specified value, or appends the specified value to the existing value. (tinyurl.com/bdzybhrz)

From a PowerShell prompt: 1. In the Registry, go to HKEY_CURRENT_USER\software\microsoft\Windows\- currentversion\explorer. 2. Locate the Advanced key, and set its DontPrettyPath property to 1.

1. Set-Location HKCU:\software\microsoft\windows\currentversion\explorer. 2. Get-ChildItem (not really necessary) 3. Set-ItemProperty -Path Advanced -Name (or -PSProperty) DontPrettyPath -Value 1

Describe the 3 parts of a For loop. i.e. for(1st part ; 2nd part ; 3rd part) { Code }

1st part - the beginning point of the loop. In the for loop for($i = 1 ; $i -le 10 ; $i++) { Write-Host "Current value : "$i -ForegroundColor Green } the loop will start at the number 1 2nd part: the condition by which the condition executes the code between the curly brackets. In the above example, the for loop will continue as long as $i -le 10. 3rd part: this part is generally incrementing or decrementing the value. Since the 3rd part in the above example has the assingment operator ++, which means to Increases the value of a variable, assignable property, or array element by 1, each running of the loop will increase the value of the $i variable by 1.

what is A PowerShell provider, or PSProvider

A PowerShell provider, or PSProvider is an adapter. It's designed to take some kind of data storage and make it look like a disk drive.

what is the difference between an array and a hashtable?

An array is simply a list of values whereas a hashtable is a collection of key/value pairs. Here are some examples: Array $i = @(1,2,3,4,5) Hashtable [hashtable]$i = @{ Number = 1; Shape = "Square"; Color = "Blue"}

what is an operator in powershell?

An operator is a language element that you can use in a command or expression. PowerShell supports several types of operators to help you manipulate values.

How are arrays most often used? What is one way they can be defined?

Arrays are most often used to contain a list of values, such as a list of usernames or cities. PowerShell arrays can be defined by wrapping a list of items in parentheses and prefacing with the '@' symbol. Eg $nameArray = @("John","Joe","Mary")

Define the data type "Boolean" as defined in Powershell for beginners by Alex Rodrick

Boolean: This value can be either True or False. If it is existing, then it is True otherwise it'll be False.

what is the concept of concatenation

Concatenation, in the context of programming, is the operation of joining two strings together.

common capabilities of providers - credentials

Credentials—The provider permits you to specify alternate credentials when connecting to data stores. There's a - credential parameter for this.

What are the 11 common parameters that can be used with all powershell commands.

Debug (db) ErrorAction (ea) ErrorVariable (ev) InformationAction (infa) InformationVariable (iv) OutVariable (ov) OutBuffer (ob) PipelineVariable (pv) Verbose (vb) WarningAction (wa) WarningVariable (wv)

what is the syntax of the do while loop

Do { Code }while(Condition)

Every process that's in the reference set, but not in the difference set, will have a ? indicator If a process is on the difference computer but not the reference computer, it'll have a ? indicator instead.

Every process that's in the reference set, but not in the difference set, will have a <= indicator (which indicates that the process is present only on the left side). If a process is on the difference computer but not the reference computer, it'll have a => indicator instead.

Define the data type "Floating Point" as defined in Powershell for beginners by Alex Rodrick

Floating Point: The value is of decimal type

For Loop This loop is used in case you require a ?

For Loop This loop is used in case you require a counter, i.e. if you want to run the loop for 'n' number of times. Ex: for($i = 1 ; $i -le 10 ; $i++) { Write-Host "Current value is "$i" -ForegroundColor Green } will write Current value is... for each of the numbers 1 through 10 or whatever else you specify in the numeric value in the second parameter in the for loop

Create a folder "C:\Temp\Test" and copy paste any one sample CSV and two TXT file in it. First show the total files in the folder and then find only the csv file in it and display its size in KB and MB as shown in the screenshot.

Get-ChildItem -Path "C:\temp\test" $file = Get-ChildItem -Path "C:\temp\test" | where {$_.Name -like "*.csv"} | Select Name,Length $sizeinKB = $file.Length/1KB $sizeinMB = $file.Length/1MB Write-Host "`nFileName : "$file.Name Write-Host "Size in KB : "$sizeinKB Write-Host "Size in MB : "$sizeinMB

what is the powershell command for dir or ls

Get-Childitem

Stop the notepad process

Get-Process -name Notepad | Stop-Process

Open two instances of notepad on your machine and find their Process ID. The output should only show the "Process Name" and "Id".

Get-Process | ?{$_.ProcessName -eq "notepad"} | Select ProcessName,Id

export all processes to a csv file named procs.csv located in c:\Labs

Get-Process | Export-CSV -Path c:\Labs\procs.csv

How would you get all services piped out to a file in HTML format?

Get-Service | ConvertTo-HTML | Out-File services.html

find and list all services starting with the letter a that are in a stopped state.

Get-Service | where{$_.status -eq "Stopped" -and $_.name -like "A*"}

import the csv file located at c:\Labs\procs.csv into powershell

Import-CSV -Path c:\Labs\procs.csv

What are the differences between the -Filter, - Include, and -Exclude parameters of Get-ChildItem?

Include and Exclude must be used with - Recurse or if querying a container. Filter uses the PSProvider's filter capability, which not all providers support. For example, you could use DIR -filter in the filesystem but not in the Registry—although you could use DIR -include in the Registry to achieve almost the same type of filtering result.

what is one meaning of square brackets [ ]

It indicates a positional parameter When you're looking at a command's syntax in its help file, you can spot positional parameters easily: SYNTAX Get-ChildItem [[-Path] ] [[-Filter] ] [- Exclude ] [-Force []] [-Include ] [-Name []] [-Recurse []] [- UseTransaction []] [] Here, both -Path and -Filter are positional, and you know that because the parameter name is contained within square brackets

access the item LastName from within the hashtable which has been set equal to a variable named user.

Items within a hashtable are easily accessed using the variable and the key name. eg $user.LastName, in the hash table $user=@{FirstName="John"; LastName="Smith"; MiddleInitial="J"; Age=40}; will return the value "Smith"

How can items in a name array be accessed?

Items within an array can be accessed using their numerical index, beginning with 0, within square brackets like so: $nameArray[0]. In $nameArray = @("John","Joe","Mary") $nameArray[0] will be the first value in the array, ie "John" $nameArray[1] will be the second value in the array, ie "Joe"

Create a new alias; export all aliases or import a list of previously creted aliases

New-Alias, Export-Alias, Import-Alias. When you create an alias, it lasts only as long as your current shell session. Once you close the window, it's gone. That's why you might want to export them, so that you can more easily reimport them.

Create a zero-length file named C:\Labs\Test.txt (use New-Item)

New-Item -Name test.txt -ItemType File -Path C:\Labs

Create a new directory called C:\Labs

New-Item -Path C:\Labs -ItemType Directory

Using this cmdlet, you can ask a question, for which the user can input any answer. This answer can then be saved in a variable which can be further used in the script.

Read-Host $t = Read-Host "What is the time?" will display "What is the time?" on the screen and then hold the answer inputted as the variable $t.

Using the Environment provider, display the value of the system environment variable %TEMP%

Set-location -path ENV: PS Env:\> Get-ChildItem TEMP (or either of these commands Get-item env:temp or Dir env:temp)

The ? command lets you specify the command name you're struggling with and then graphically prompts you for the command's parameters.

Show-Command lets you specify the command name you're struggling with and then graphically prompts you for the command's parameters.

The 'where' command is used to ?

The 'where' command is used to look for information that is being passed/provided by the previous command. Ex: Get-Service | where{$_.status -eq "stopped"}

which wildcard stands in for zero or more characters, and which wildcard stands in for any single character

The * wildcard stands in for zero or more characters, whereas the ? wildcard stands in for any single character

What does @() mean in Powershell?

The @ indicates an array. @() simply creates an empty array. I.e. this snippet: $TodaysMail = @() Would yield a variable TodaysMail representing an empty array.

The ? cmdlet can be used to display information in the console. Its handy while troubleshooting or monitoring a script to identify till which step the script has executed.

The Write-Host cmdlet can be used to display information in the console. Its handy while troubleshooting/monitoring a script to identify till which step the script has executed. Write-Host "It is a good day" will display the text in quotes on the screen.

The continue statement immediately ?

The continue statement immediately returns script flow to the top of the innermost While, Do, For, or ForEach loop. It does not execute the rest of the lines in that loop. $processes = Get-Process foreach($process in $processes) { Write-Host "Process : "$process -ForegroundColor Yellow if($process.PM / 1024 / 1024 -le 100) { continue } Write-Host ('Process ' + $process.Name + ' is using more than 100 MB RAM.') - ForegroundColor Green }

common capabilities of providers - filter

The provider supports the -Filter parameter on the cmdlets that manipulate providers' content.

common capabilities of providers - shouldprocess

The provider supports the use of the -WhatIf and -Confirm parameters, enabling you to "test" certain actions before committing to them.

There are different data types in PowerShell that include 1, 2, 3, 4, & 5 values which are like what you use in our daily life. The 6 method returns the current data type of the given variable

There are different data types in PowerShell that include integers, floating point values, strings, Booleans, and datetime values which are like what you use in our daily life. The GetType method returns the current data type of the given variable

common capabilities of providers - Transactions

Transactions—The provider supports the use of transactions, which allows you to use the provider to make several changes, and then either roll back or commit those changes as a single unit.

Use Get-Content only when 1 and don't want PowerShell attempting to 2—that is, when you want to 3

Use Get-Content only when you're reading in a text file and don't want PowerShell attempting to parse the data—that is, when you want to work with the raw text

What does += mean in PowerShell?

When the value of the variable is an array, the += operator appends the values on the right side of the operator to the array. Unless the array is explicitly typed by casting, you can append any type of value to the array, as follows:

When you write the foreach statement, the first object is what? This is then followed by 2 and 2 is followed by the 3 in which 4

When you write the foreach statement, the first object is a temporary variable '$s' followed by the operator 'in', followed by the array in which the data is stored '$services'. Ex: $services = Get-Content C:\Temp\Services.txt foreach($s in $services)

have powershell prompt you to enter the number associated with either the windows audio, the print spooler or the net log on service and then output the status, name and displayname of the service that you chose.

Write-Host "Check Service Status" -ForegroundColor Green Write-Host "1: Check status of Windows Audio service" -ForegroundColor Yellow Write-Host "2: Check status of Print Spooler service" -ForegroundColor Yellow Write-Host "3: Check status of Netlogon service" -ForegroundColor Yellow $choice = Read-Host "Please enter your choice" switch($choice) { 1 { Get-Service Audiosrv } 2 { Get-Service Spooler } 3 { Get-Service Netlogon } }

Match a set of characters a,b,c.., so ?ake will match fake/make

[abc] Match a set of characters a,b,c.., so [fm]ake will match fake/make

Match a range of characters from 'f to m', so ?ake will match fake/jake/make

[m-n] Match a range of characters from 'm to n', so [f-m]ake will match fake/jake/make

Write a script using a For loop that will display on the screen, in green, the words "Current Value :" and then a number for all numbers between 1 and 10

for($i = 1 ; $i -le 10 ; $i++) { Write-Host "Current value : "$i -ForegroundColor Green }

Write a function named hi with the parameters name and age that will output "My name is..., My age is..., I like Powershell"

function hi { param ( [data type]variable1, i.e. [string]$name [data type]variable2 i.e. [int]$age ) 1st line in code using variable 1 i.e. Write-Host "My name is : "$name 2nd line in code using variable 2 i.e. Write-Host "My age is : "$age additional lines in code i.e. Write-Host "I like powershell" }

Retrieve all aliases for the get service command

get-alias -Definition "Get-Service"

show the current directory

get-location

get all processes that have a priority class of normal

get-process | where-object {$_.priorityClass -eq "normal" }

move, delete, copy and rename a file, folder or other object

move-item, remove-item, copy-item, rename-item

create a new file called myitem.txt in the current directory

new-item myitem.txt

change the directory using a powershell command to c:\new

set-location c:\new

what is the syntax of the switch command

switch(variable containing choice) { Condition 1 or Choice 1 { Action } Condition 2 or Choice 2 { Action } }

what command takes a directory listing and displays it one page at a time

the More command takes that directory listing and displays it one page at a time

parentheses in PowerShell control ?

the order of execution. Diff -reference (Import-CliXML reference.xml) ➥ -difference (Get-Process) -property Name In the previous example, they force Import-CliXML and Get-Process to run before Diff runs. The output from Import-CliXML is fed to the -reference parameter, and the output from Get-Process is fed to the -difference parameter.

what is the syntax of writing a function without parameters

the syntax of writing a function without parameters is function "our choice of name" { 1st line in code 2nd line in code etc } so function hi { Write-Host "My name is John" -ForegroundColor Green Write-host "My age is 30" -ForegroundColor Yellow Write-Host "I like powershell" -ForegroundColor cyan } will output those 3 lines of text should someone type "hi" without the quotation marks and then hit the enter key.

Define the data type "String" as defined in Powershell for beginners by Alex Rodrick

used for storing letters and characters

How do you assign a hash table?

with squiggly brackets prefaced by the '@' sign. Example: $user=@{FirstName="John"; LastName="Smith"; MiddleInitial="J"; Age=40}

Use the get-date function to get the day of the year for todays date

write-host ((get.date).dayofyear)

Tell me what is going on in the command line Get-Service | Where-Object {$_.name -Match "win"}. More specifically what is the significance of the $_.?

you are piping get service to the where object command and then looking for those services whose name property matches "win". $_ is a variable or placeholder. The period specifies that you are looking at/for a specific object property. In this case the name property.


Ensembles d'études connexes

Genetics Chapter 14: Gene Regulation in Bacteria

View Set

Thomas 6th grade Chapter 6 Lesson 4 The Qin Dynasty

View Set

N5451 Skills Lab > Video Quizzes > Module 1. Asepsis

View Set

Microbial Classification and Diversity quiz 1

View Set

Microbiology Chapter 8: Gene Transfer and Genetic Engineering

View Set

#9 Unit 2 Chapter 9 How are powers divided between federal and state governments Federalism, Federal Powers and state powers

View Set