Jump Start to PowerShell (part II)

Who if not you? When if not now?



In the previous part we learned how to start PowerShell, I understood the execution policy of scripts. Understand what the cmdlets that know how to pass them through the pipeline and how to get their properties. Found out that PowerShell is a huge Help.

In this part we will deal with variables, we learn that they types and how to address them, how they compare and display all sorts of ways. Will deal with cycles and we write several functions.

← go to first part

Introduction



I want to start with the answers to the questions raised in the first one that You Jump Start e:

what a huge opportunity PowerShell? Why should I study?
Each by the phrase "huge opportunity" can understand something of their own.
If I had to characterize PowerShell in three words, I would say: it environment to simplify administration, helping to create tools for automation and management.

To learn PowerShell, if you administer Windows Server and server software from Microsoft. Take, for example, one of the most popular products Microsoft Exchange Server — and then encountered the PowerShell console of the Exchange Management Shell.
Knowing PoSh you'll be able to do any uploading data, set the control for any system processes, send reports, create users, to solve their problem...

I don't administer what then?
It is possible to compare how people of different professions are fond of creating web sites. Like it is very not necessary, but they're doing it. For your personal development, entertainment or fun.
Are you a student? Write your first application that will solve a quadratic equation.
Or, for example, examine the parsing and make your app for downloading music or video from youtube.
It all depends on you and your imagination. View here, PowerShell can even be taught to talk.

you Can just watch the videos on MVA!
Yes, I absolutely agree with You — it may be more efficient.
However, not everyone has the time to watch 12-15 hours of training and not everyone can perceive the information.
Here I try to give the basic knowledge they need to successfully continue to develop your skills infinitely further.


Variables



the
    the
  • a Variable in PowerShell starts with the character $ (the European Union sign €) and the name can contain any letters, numbers and underscore.
  • the
  • to assign a value to a variable, it is enough to assign the sign "=". To display the value of a variable, you can simply write this variable. Output we will look on the text below.

    the
    $var = 619
    $var
    




  • the
  • Above numbers, you can carry out arithmetic operations, strings can be added. If the line is to increase the number, the number is automatically converted to a string.

    the
    $a = 1
    $b = 2
    $c = $a + $b
    $c #c = 3
    
    $str = "Habra"
    $str = $str + "Habr"
    $str #str = ... 
    
    $str = $str + 2014
    $str #str = Хабрахабр2014
    
    


  • the
  • If we need to know what type has one or the other variable, you can use the method GetType()

    the
    $s = "This is a string?"
    $s.GetType().FullName
    




  • the
  • the type of the variable, PowerShell automatically defines or can be assigned manually.

    the
    $var = "one"
    [string]$var = "one"
    


    PowerShell uses the data types of the Microsoft .NET Framework. Consider the main:

    the the the the the the the the the the the
    Type / .NET class Description
    [string]

    System.String
    Row

    the
    $var = "one"
    

    [char]

    System.Char
    Symbol

    the
    $var = [char]0x263b
    

    [bool]

    System.Boolean
    Boolean. Can have the value $true or $false.

    the
    $bvar = $true
    

    [int]

    System.Int32
    32-bit integer

    the
    $i = 123456789 
    

    [long]

    System.Int64
    64-bit integer

    the
    $long_var = 12345678910
    

    [decimal]

    System.Decimal
    128-bit decimal number. The letter d at the end of the number of mandatory

    the
    $dec_var = 12345.6789 d
    

    [double]

    System.Double
    8-byte decimal floating point number

    the
    [double]$double_var = 12345.6789
    

    [single]

    System.Single
    32 bit floating point

    the
    [single] = $var 123456789.101112
    

    [DateTime]

    System.DateTime
    Variable date and time.

    the
    $dt_var = Get-Date
    

    [array]

    System.Object[]
    the Array. The index of array elements starts with 0 — to refer to the first element of the array $mas, you should write $mas[0].

    the
    $mas = "one", "two", "three"; 
    


    To add an element to the array, you can write

    the
    $mas = $mas + "four"
    


    Each array element can have its type

    the
    $mas[4] = 1
    


    [hashtable]

    System.Collections.Hashtable
    the Hash table. Difference between hash tables and arrays is that arrays use indices and hash-table named keys. The hash tables are built on the principle @{ key = "value" }

    the
    $ht = @{odin="one"; dva="two"; tri="three"} 
    




    To add an item to the hash table, you can either assign it to that key, which is still there, or you can use the method Add(). If the assignment is to do to an existing key — the key value will change to assigned. To remove an item from the hash table is a method Remove().

    the
    $ht.Add("chetyre sezona", "four")
    $ht.pyat = "five"
    $ht.Remove("dva")
    







You probably already understand that a variable can not only capture a certain value noticed in the table class of the System.Object[]. In a variable so you can record the output of any cmdlet.

Analyze combat puzzle need to know IP address and MAC address multiple computers on the network. The names of the domain computers-comp1, domain-comp2. Solution spoiler:
Show code

the
$MAC = Get-WmiObject -ComputerName domain-comp1, domain-comp2 -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=True | Select-Object-Property * | SELECT PSComputerName, @{Name="IPAddress";Expression={$_.IPAddress.get(0)}}, MACAddress, Description
$MAC

What happens:

We record in the variable $MAC the result of the command Get-WmiObject, through which pass the WMI query on the computers in the-computername parameter and return the information we need from the class Win32_NetworkAdapterConfiguration.
Please note, if you need to obtain the IP address and MAC address of the current computer, instead of computer names to-computername parameter we will pass the point. And, let us, in the next example, save the result to a file D:\comp_mac_ip.csv:
the
$MAC = Get-WmiObject -ComputerName . -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=True | Select-Object-Property * | SELECT PSComputerName, @{Name="IPAddress";Expression={$_.IPAddress.get(0)}}, MACAddress, Description
$MAC | Export-Csv D:comp_ip_mac.csv -Encoding UTF8




Scope of variables


The scope of a variable in PowerShell can be either local or global. By default, the variable has a local scope and limited scope, for example, is available only in functions or only in the current script. A global variable is valid throughout the current PowerShell session. In order to define a global variable, simply write the following construct: $Global: variable = value

the
$Global:var = 12


And another thing on the topic of variables... discussing with a colleague 1C and its Russian-language programming environment, wondered:

And Yes, indeed:

the
function Hello() { "Hello $env:USERNAME. Maybe you should not write in Russian?"
Start-Sleep 3
"Open Habr?"
}
function open() { & "C:\Program Files\Internet Explorer\iexplore.exe" http://habrahabr.ru/post/242425/ }







comparison Operators and logical operators



Comparison operators and logical operators test for equality or conformity between two values.

the
    the
  • When the condition, design comparison always returns a Boolean value $true or $false if the condition is false.


The table below lists the comparison operators:

the the the the the the the the the the the the the the
Operator Description Example
-eq Equal / Equal (=)
$var = "619"
$var -eq 123 #$false

ne Not equal / is Not equal to (<>)
$var = "619"
$var -ne 123 #$true
-gt Greater than / Greater than (>)
$var = "619"
$var -gt 123 #$true
-ge Greater than or equal / Greater or equal (>=)
$var = "619"
$var -ge 123 #$true
-lt Less than / Less than (<)
$var = "619"
$var -lt 123 #$false
le Less than or equal / Less than or equal to (<=)
$var = "619"
$var -le 123 #$false
-like sensitive Comparison wildcard
"Habra" -like "habr*" #true
-notlike Comparison, taking into account not matching the wildcard
"Habra" -notlike "habr*" #false
-contains Contains a value from the left value to the right
1, 2, 3, 4, 5 -contains 3 #$true
-notcontains If the value on the left contains the value on the right, get the truth
1, 2, 3, 4, 5 -notcontains 3 #$false
match Using regular expressions to match pattern
$str = "http://habrahabr.ru"
$str -match "^http://(\S+)+(.EN)$" #$true
-notmatch Using regular expressions to search for inconsistencies sample
$str = "http://habrahabr.ru"
$str -notmatch "^http://(\S+)+(.com)$" #true
-replace Replaces all or part of the value left of the operator
"Microhabr" -replace "Micro","Habra" #Habrahabr


let us Consider an example. In the example we create a path to possible user profile on the remote computer depending on the operating system. The decision under the spoiler:
Show code

the
#profile Path on the remote computer
Function UProfile ($UCompName, $ULogin) {
[string]$CompOS = Get-WmiObject -ComputerName $UCompName -Class Win32_OperatingSystem | SELECT Caption #Get the title of the operating system of your computer
if ($CompOS -match "Windows 7") { #If the header contains "Windows 7"
[string]$LinkUserProfile = "\\$UCompName\d$\users\$ULogin" #Get this way
$LinkUserProfile 
} elseif ($CompOS -match "Windows XP") { #If the header contains "Windows XP"
[string]$LinkUserProfile = "\\$UCompName\d$\Documents and Settings\$ULogin" #Get this way
$LinkUserProfile 
}
}

UProfile domain-Administrator comp1 #the function name is the computer login user


Yes, here we do not check whether there is a profile. But you can check. For this, we will add another condition which will check cmdlet Test-Path the path exists:

the
#profile Path on the remote computer
Function UProfile ($UCompName, $ULogin) {
[string]$CompOS = Get-WmiObject -ComputerName $UCompName -Class Win32_OperatingSystem | SELECT Caption #Get the title of the operating system of your computer
if ($CompOS -match "Windows 7") { #If the header contains "Windows 7"
[string]$LinkUserProfile = "\\$UCompName\d$\users\$ULogin" #Get this way
} elseif ($CompOS -match "Windows XP") { #If the header contains "Windows XP"
[string]$LinkUserProfile = "\\$UCompName\d$\Documents and Settings\$ULogin" #Get this way 
}
if (Test-Path $LinkUserProfile) { $LinkUserProfile } else { "Profile $ULogin does not exist on your computer $UCompName" } #Check the existence of profile
}

UProfile domain-Administrator comp1 #the function name is the computer login user



By the way, a regular expression in PowerShell describe very well Xaegr in his blog. Worth it to spend a couple of hours to read and comprehend the ability of writing regular expressions.
the
    the
  • you Can optionally define a condition if the comparison should be case sensitive. To do this in front of the operator to substitute the letter "c"

    the
    $str1 = "Habr"
    $str2 = "habr"
    $str1 -ceq $str2 #to$false
    


  • the
  • you Can use several comparison operators, using logical operators. Logical operators are listed in the table below:


the the the the
Operator Description Example
and Logical and
("String" -eq "String") -and (619-619 eq) #$true
-or Logical or
("String" -eq "String") -or (619 -eq 123) #$true
-not Logical not
not (123 -gt 324) #$true
or
the
!(123 -gt 324) #$true


a few words about if... elseif and else

the
if ( condition1 is true ) { execute code } #if condition 1 is true, execute code, if not - go ahead
elseif ( condition2 is true ) { execute code } #an optional condition: else if condition 2 is true, execute the code
else { execute code } #an optional condition: if the past condition is not true execute code


All quite simple. If the condition is true, we execute the following code for the condition in curly brackets. If the condition is not true, we skip running and are looking to continue to whether we have the condition further.
If you find elseif — check new condition and, if successful, execute the code, otherwise, again, look, whether there is a continuation of the elseif or else statement.
If the condition is true, then the code is executed and the branch of the elseif or else statement is skipped.

the
$str = ""
if ( 1 -gt 2 ) { $str = "Orange" } 
elseif ( $str -eq "Orange" ) { $str } 
else { $str = "Apple"; $str } 

Response



Output



Consider a few key options is displayed on the screen:
the
    the
  • writing to a file using Out-File

    the
    $str = "Hello Habr!"
    $str | Out-File D:\out_test1.txt
    

    or, as we said in part I, use the sign ">"

    the
    $str = "Hello Habr!"
    $str > D:\out_test2.txt
    

  • the
  • Export data .csv file using the Export Csv

    the
    $p = Get-Process
    $p | SELECT Name, Path | Export-Csv -Path D:\out_test3.csv
    

  • the
  • Entry in the HTML file using the ConvertTo-Html

    the
    $h = Get-Process
    $h | ConvertTo-Html-Property Name, Path > D:\out_test4.html
    & D:\out_test4.html #Open the file after the formation of the
    




    To work with the HTML output is actually very nice. Having skills of web programming, you can add styles and get very pretty reports.


To read the file we will help familiar cmdlet Get-Content

the
Get-Content D:\out_test1.txt




Cycles


Loops in PowerShell are not much different from loops in other languages. Almost everything and everywhere:

Do While

To do as long as the condition is true

the
$x = 10

do
{
$x
$x = $x - 1 
}
while ($x -gt 0)


Do Until

A loop that repeats a set of commands until a condition is met

the
$x = 0

do
{
$x
$x = $x + 1 
}
until ($x -gt 10)


For

A loop that repeats the same steps a specific number of times

the
for ($i = 0; $i -lt 10; $i++)
{ 
$i
}


ForEach

Loop through a collection of objects

the
$collection = "Name-Компьютера1", "Name Компьютера2", "Name Компьютера3"
foreach ($item in $collection)
{
$item 
}


Write



the
    the
  • in PowerShell, Functions have the following structure:

    the
    function functionname ([parameter1, ..., параметрN]) 
    { 
    the body of the function 
    } 
    

  • the Function does not need to return the result. the

  • When calling a function, all parameters are separated by spaces.


For example, the function for obtaining the square of a number, PowerShell will look like this:

the
function sqr ($a)
{
return $a * $a
}

sqr 2 #Result: 4


And lastly, an example of a function that will help us to perform the transliteration. In this example, just all what we discussed today:
the
#Transliteration
function Translit ([string]$inString)
{
$Translit = @{ #Create a hash table of matching symbols
[char]'a' = 'a'
[char]'A' = 'A'
[char]'b' = "b"
[char]'B' = "B"
[char]'in' = "v"
[char]'In' = "V"
[char]'g' = "g"
[char]'G' = "G"
[char]'d' = "d"
[char]'D' = "D"
[char]'e' = "e"
[char]'E' = "E"
[char]'e' = "yo"
[char]'E' = "Yo"
[char]'W' = "zh"
[char]'W' = "Zh"
[char]'z' = "z"
[char]'Z' = "Z"
[char]'and' = "i"
[char]'And' = "I"
[char]'th' = "j"
[char]'Th' = "J"
[char]'K' = "k"
[char]'K' = "K"
[char]'l' = "l"
[char]'L' = "L"
[char]'m' = "m"
[char]'M' = "M"
[char]'n' = "n"
[char]'N' = "N"
[char]'o' = "o"
[char]'O' = "O"
[char]'p' = "p"
[char]'P' = "P"
[char]'R' = "r"
[char]'R' = "R"
[char]'with' = "s"
[char]'With' = "S"
[char]'t' = "t"
[char]'T' = "T"
[char]'' = 'u'
[char]'' = 'U'
[char]'f' = "f"
[char]'f' = "F"
[char]'x' = "h"
[char]'X' = "H"
[char]'C' = "c"
[char]'C' = "C"
[char]'h' = "ch"
[char]'H' = "Ch"
[char]'W' = "sh"
[char]'W' = "Sh"
[char]'Sch' = "sch"
[char]'Sch' = "Sch"
[char]'b' = ""
[char]'b' = ""
[char]'s' = "y"
[char]'S' = "Y"
[char]'b' = ""
[char]'B' = ""
[char]'e' = "e"
[char]'e' = "E"
[char]'s' = "yu"
[char]'s' = "Yu"
[char]'z' = "ya"
[char]'Z' = "Ya"
}
$TranslitText = ""
foreach ($in CHR $inCHR = $inString.ToCharArray())
{
if ($Translit[$CHR] -cne $Null) 
{ $TranslitText += $Translit[$CHR] } #analogue record $TranslitText = $TranslitText + $Translit[$CHR] 
else
{ $TranslitText += $CHR }
}
return $TranslitText
}

Translit. #Output: Habrahabr



PostScript



We now know enough information to begin to dive deeper into PowerShell. In this part we meet with variables, data types, understood the conclusion of the information, comparison operators, loops... we'll See after starting is not so difficult!

Keep calm and learn PowerShell.

to be Continued...



Additional information



the
Article based on information from habrahabr.ru