+ All Categories
Home > Documents > PowerShell training Primer

PowerShell training Primer

Date post: 07-Aug-2018
Category:
Upload: lorilevy
View: 220 times
Download: 0 times
Share this document with a friend

of 29

Transcript
  • 8/21/2019 PowerShell training Primer

    1/29

    PowerShell

    Variables

    Variables begin with a $and their VALUEgets interpreted insidestrings with DOUBLEQUOTES.

    In this case, I'm referencing the variable sinside of the string. PowerShell does theinterpolation for me. However, this only works for double uoted coded strings. If you try to

    attempt this with single uoted strings, PowerShell won't perform the interpolation.

    !se double uotes whenever " is involved to translation to the value.

    !se single uotes for literal translation of Variables.

    #hese two commands return the same result$$str = asdfx-99.txt

    # below is regEx for any chars, followed by a followed by some digits

    # first-line escapes the $ with a back-tick a backward accent mark!

    $str-replace"a-%&!-'d&!", "($)-($*" # $) is the )nd+egEx eal $* the *st

    $str-replace"a-%&!-'d&!", $)-$*

  • 8/21/2019 PowerShell training Primer

    2/29

    99-asdfx.txt

    Type Casting in PowerShell

    !se [int]%someVariable& to convert a string to an integer

    Comments in Script Files/#

    m0lti-line comments are created anywhere in the script file

    by s0rro0nd the lines with the element brackets and hash symbols

    as shown here.

    #1

    # single-line comments begin with a hash symbol

  • 8/21/2019 PowerShell training Primer

    3/29

    Arrays

    !se @( )to create an array

    Here I am defining a variable named ra and assigning it a value of an array containing the

    numbers (, ), *, + and . If I recall the array variable, PowerShell output the elements of the

    array one at a time. -ou can inde specific numbers using suare brackets and you can assign

    to specific members using standard synta. In addition, PowerShell supports slicing of the array.

    /or eample, I can retrieve elements ) through + inclusive of the ra variable using the dot0dot

    operator and the inde. #his works for retrieval, but unfortunately, you can't use it for

    assignment as well. 1ost of the time, the at symbol and the parenthesis are optional.PowerShell is smart enough to know, if you provide a list of things separated by commas, you

    probably want an array. 2h, and arrays are mied type too. In this eample, the array will

    contain the numbers (, ), the string * and the numbers + and .

  • 8/21/2019 PowerShell training Primer

    4/29

    Hash Tables

    !se @{ } to create a hashtable 3ample$ "myHash#able 4 56 a4(7 b4)7 c4* 8

    In this eample, I'm defining a variable named hash that contains a hash table where key is set

    to value (, key b is set to value ) and key c is set to value *.

    9ike arrays, you can inde to specific elements of the hash table by specifying the key in the

    suare brackets. "hash:;brray

  • 8/21/2019 PowerShell training Primer

    5/29

    Flow Control

    If? 3lse?#hen

    True and False

    #rue$ "true

    PowerShell considers the number ( to be true.

    @egative numbers are considered true in PowerShell

    /alse$ "false

    PowerShell considers A to be false.

    PowerShell considers an empty string to be false.

    PowerShell considers the value null to be false

    In addition, PowerShell is smart enough to know that an empty string is not eualto the number A even though they're both considered to be false inside of a conditionalepression.$global2a=3

    $global2b=

    $a-e4$b #tr0e

    $b-e4$a #false

    ForEach

    !se %( ) or forea!

  • 8/21/2019 PowerShell training Primer

    6/29

    -ou

    !se the foreachoperator to iterate over a list. In this eample, the foreachoperator pulls the

    values from the list (, ) and *, assigning each value to a then eecuting the block that follows

    the foreach statement. In this case, each value of a will be added to AA and output to the

    console.

    PowerShell supports a whilestatement. In this eample, the while statement will eecute the

    following block of code as long as the value of ais greater than A. 3ach time the block of code

    is eecuted, the value of ais decremented by ( then the value of a is added to AA and output

    to the console.

    .ToString(

  • 8/21/2019 PowerShell training Primer

    7/29

  • 8/21/2019 PowerShell training Primer

    8/29

    !et"Command#Finding out what$s a%ailable

    !se "etBo##and Ber "et

    !se erBno&n

  • 8/21/2019 PowerShell training Primer

    9/29

    #he commands in PowerShell follow a naming convention. #his convention is verb dash noun.

    #he idea behind this convention is to help you remember, or more specifically, make it so you

    don't have to remember the names of these commands.

    Cet0help responds with a restart service help topic that provides a uick synopsis.

    Dommand synta.

    Eetailed description.

    9ist of other help topics that are relevant. Here's the best part. Fhat you're looking at on

    the screen right now is the short version of help for restart service. If I were in the same

    command I did before, pass the restart service command name to get0help, but this time

    I specify the 0full parameter to get0help$

    get-helpget-exec0tionpolicyfull

    PowerShell outputs details for every parameter the command accepts, as well as notes

    eamples of how to use the command.

  • 8/21/2019 PowerShell training Primer

    10/29

    !et"Help and !et&'ember to isco%er )hat$s A%ailable

    !se "etB!e'Bf&'' or "etB!e' ao&t*

    !se "etB!e' GsomethingG Be+a#'es

    !se erBno&n

    !se "etB#e#er to find out what something can do

    The Top *+ Commands

    Chaining with the Pipe Symbol

    !seto find chain commands together

    Fhatever is output from the command before the pipe will be eecuted like it was on the net

    line of script, similar to chaining together actions in Juery.

    If you are not using the output of the first command in the second, then use a semi0colon to

    separate your commands.

    Changing your ,ocation

    !se "home global variableto change to$ c$KusersKlolevy %your used id&

    !se cd to change directories %like E2S&

    !se cd , to move to the root of the drive %like E2S&

    !se cd -- to move up one directory %like E2S&

    !se .et/'oation or C9to retrieve your current location %current folder&!se Set/'oationand pass it a relative or absolute path to the new location set-location ./documents from c:\users\

    !se 0dto 1rint 2orking Directory

  • 8/21/2019 PowerShell training Primer

    11/29

    3refers to c:\users\ cd ~/documentsgoes to your documents provided your shell is yourhard drive

    !se $!o#einstead of the tilde

    !se &s!d 3to push the directory to the c$K!sersKlolevy folder

    !se &s!dto push to a different folder and give it a relative or absolute path to the new

    location

    !se odto get back to where you were before you changed locations

    #he push location commandlet behaves similar to set location. However, using the &s!d

    o##and saes 4o&r &rrent 'oation on to a sta5, before moving you to the new location.

    Fhen you're done working at the new location, use the PowerShell odo##and'et to

    o&ne a5 to 0!ere 4o&6re 0or5in" efore. -ou can use the shorter pushd alias for push

    location. >nd you can push multiple locations on to the stack. 3ach call the pop location, or its

    alias popd, will bounce you to the net location store on the stack. > common use for push

    location and a pop location is to control the current working directory inside of a script. -ou'll

    often see push location at the start of a script. #o move the current location, to a specific area

    where the script needs to get some work done. #he pop0location at the end of the script willreturn the user back where they were originally working. If you write scripts that need to work on

    a specific location, using push location and pop location, to control the current location of the

    user session, it is generally good form.

    ,isting Files

    !se dir to list files in a folder %like E2S&

    !se 9S to list files in a folder

    Creating Files

    !se new-item-pathfoo-from-powershell.txt-type file-valuehello5

    to create a file in the eisting fo'derusing PowerShell

    !se io.file%22write6ll7ext "bar-from-dotnet.txt","hello again5"!to create a file in the eisting 'oationusing .@3#

  • 8/21/2019 PowerShell training Primer

    12/29

    .@3# uses [environment]::currentDirectory which isc:\users\

    S-,T/-01/# 8o0 can p0t any logic yo0 want into this f0nction, since f0nctionprompt

    gets called after eery ower:hell command exec0tes, its a great place to

    keep yo0r c0rrent directory and location in synch2

    #1

    cls

    f0nctionprompt;

    $c0rdir=get-location-PSProviderfile:ystem< select-object-expandath

    #set the path e40al to the c0rrent windows directoryenironment%220rrent>irectory=$c0rdir

    #7ell owershell to show the working directory at the prompt": $pwd1 "

    ?

    Creating 0ew Te2t Files# write content to the data.txt file instead of the console

    # -inp0tob@ect is the content to write

    yo0 will oerwrite the content if yo0 0se the same file name

    # get-content will print the whole content of the file to the console.out-file.Adata.txt-inputobjectthis is the first line.get-content.Adata.txtclsout-file.Adata.txt-inputobjectthis is the second BBB5get-content.Adata.txt

    # write content to the data.txt file instead of the console

    # 0sing the 1 symbol

    $firstline="this is the first Cine"

  • 8/21/2019 PowerShell training Primer

    13/29

    Appending to Te2t Files# Dse 11 to append content to the a file instead of the console

    # -inp0tob@ect is the content to write

    # get-content will print the whole content of the file to the console.

    # reate a new file to with the res0lt of the expression in !out-file.Adata.txt-inputobject*&*!get-content.Adata.txt# reate ariable to hold content to append to the file

    $firstCine="this is the first Cine"

    # 6ppend the firstCine to the text file

    $firstCine11 .Adata.txt

    clsget-content.Adata.txt# reate ariable to hold content to append to the file

    $secondCine="this is the second BBB5"

    # 6ppend the secondCine to the text file

    $secondCine11 .'data.txt

    ls

    # erify both are thereget-content.Adata.txt

    # eed to prefix the file with date, so create a new text file with @0st the date

    get-date1 .Adata).txt

    # 6ppend the data in data.txt to data).txt

    get-content.Adata.txt11 .Adata).txtcls# recreate the data.txt file with date, by copying datat).txt to data.txt

    get-content.Adata).txt1 .Adata.txtcls# erify content starts with date and has both lines

    get-content.Adata.txt

    /# Forces ower:hell to look at the *&* FG+:7,

    eal0ating it as an expression before

    appending it to the context of the o0t-file data.txt

    #1

    out-file.Adata.txt-inputobject*&*!

    get-content.Adata.txt

    /n%o3e&/tem

    !se ino5e/ite#or ii to invoke an item

    Invoke0item is PowerShell's euivalent to a double click in Findows 3plorer. In this eample, I

    used invoke item on a tet file, and PowerShell open the file, and the default tet editor on the

  • 8/21/2019 PowerShell training Primer

    14/29

    system, which is notepad. I can use this techniue open any registered file type on the system

    for eample, a Power Point presentation. -ou can also pipe things to invoke item. /or eample, I

    can get a list of every tet file on the current directory, pipe it to invoke item, and PowerShell will

    open each tet file in turn.

    If you specify a folder path to invoke item, it'll open that folder in Findows 3plorer. #his gives

    you a very handy way to move between the two shells in Findows

    PowerShell 4 .0ET

    !se $1SVersionTa'eto find out which versions PowerShell and .@3# you are running

    If you're running PowerShell ).A, you'll have access to the .@3# /ramework ).A. However, if

    you're running PowerShell *.A, you'll have access to the .@3# /ramework +.A.

  • 8/21/2019 PowerShell training Primer

    15/29

    Creating .0ET -b5ects

    !se reate ne0/o7etto new0up an obect. 3ample$ $ob@ = new-ob@ect :ystem.text.+eg0larExpressions.+egExH.@pg

  • 8/21/2019 PowerShell training Primer

    16/29

    6e7erencing Types

    #o get a reference to a .@3# type in PowerShell, simply surround the name of the type with

    suare brackets. PowerShell implicitly understands this synta as a type reference.

    Lecause so many namespaces in the Lase Dlass 9ibrary start with the name system, you can

    omit this part of the namespace and PowerShell will still know what you're talking about. !sing

    the bracket synta to obtain a type reference can get a little cumbersome. >ssign these type

    references to local variables to make it easy to reference to type later.

    In the eample above, the reference to sha( is assigned to the local variable $s.

    sing Static 'embers 4 /nstance 'embers

    !se two colons after the type reference and then the name of the property or method you want.

    /or eample$ if![string]::"s#ullor$mpty$arDser! !

    2nce you have an obect reference, you can access its instance members by using a period

    followed by the name of the member you're looking for.

    View what you have in one of your local variables by piping it to the get0member cmdlet and it

    will tell you eactly what it is$ %obj get-member

    -ou can also get information withget-member &membertype event

    Handling E%ents

    Handling events in PowerShell is a bit different than working in other .@3# languages such as

    DM. In DM, you're able to create a .@3# obect that acts as an event listener for another .@3#

    obect that's the event source. In this case, you're listener obect subscribes directly to the event

    source. Fhen the event is raised by the event source, it's raised directly back to your .@3#

  • 8/21/2019 PowerShell training Primer

    17/29

    obect. Ly contrast in PowerShell, your script will reuest the 1o0erS!e'' r&nti#e to

    s&srie to t!e eentusing a special set of event handling cmdlets. Fhen the event source

    raises the event, the PowerShell runtime stores the event data until such time that your script is

    ready to process it.

    Sa%ing ata irectly to a Te2t File

    #he O&t/8i'ecmdlet enables you to send pipelined output directly to a tet file rather thandisplaying that output on screen. /or eample, this command retrieves process informationusing Cet0Process, then uses 2ut0/ile to write the data to the file D$KScriptsK#est.tt$Jet-rocess ' (ut-)ile c:*scripts*test.t+t

    Ly default 2ut0/ile saves the data eactly the way that data appears in your FindowsPowerShell console. #hat means that some of the data could end up truncated.

    6eading a te2t 7ile

    !se cat .*filenameto display a file

  • 8/21/2019 PowerShell training Primer

    18/29

    !se add0type with an assembly@ame parameter representing the name of the assembly that

    you want to load.

    !se add0type with a path parameter to specify a path to an assembly file.

    !se import0module to load assemblies from disk.

    #he import0module cmdlet is used to load assemblies that contain PowerShell features such as

    cmdlets or providers.

    !se the static load methods that are available on the System.Neflection.>ssembly type to load

    assemblies in various forms into your PowerShell session.

    9et

  • 8/21/2019 PowerShell training Primer

    19/29

    !se e+port, ./filename%state the path and file name& to eport to a .csv file

    Searching

  • 8/21/2019 PowerShell training Primer

    20/29

    Functions

    Scope

    !se %global:var#ame to give a variable global scope

  • 8/21/2019 PowerShell training Primer

    21/29

    Format the Prompt

    Prompt reset$

    Putting it back after we are done$

  • 8/21/2019 PowerShell training Primer

    22/29

    'odules!nfortunately, there's no standard mechanism for distributing and installing a PowerShell

    module

    Save the file in you're 1y Eocuments, Findows PowerShell, modules folder.

    9reate a fo'der 0it! t!e na#e of t!e #od&'e t!at 4o&6re reatin"-#he name of the psm( file

    has to match the name of the folder in which the file lives. #his is a standard PowerShell

    convention use to find modules by their name.

    >fter you've install the module, be sure to check the module documentation before you attempt

    to use the module on PowerShell. 2ften times, a module will reuire functionality from another

    module that you may or may not have installed.

    !se get-modulelistavailableto list all modules available for import on the machine.

    !se get-command -modulemodule#ameto list all functions in the module.

    !se remove-modulemodule#ameto take module out of memory.

    If the module includes an assembly %.dll&, all members that are implemented by the assembly are

    removed, but the assembly is not unloaded.

    Places to 7ind code1

    Dodeblocks.com

    PoshDode.org

    Callery.#echnet.microsoft.comscriptcenter

    Dodeple.com

    Psget.netdirectory

  • 8/21/2019 PowerShell training Primer

    23/29

    ")hat/7!seB2!at:f at the end of your command to find out what will happen if you eecute it.

    #he BFhatIf parameter is your friend. If you find yourself asking I wonder what will happen if I

    do thisT It's a safe bet that you should probably try the FhatIf parameter before you actually

    eecute that command.

  • 8/21/2019 PowerShell training Primer

    24/29

    Finding 8our Pro7ile Script

    !se $1rofi'eto find out which .ps( file is running as your profile%Probably

    D$K!sersK9o9evyKEocumentsKFindowsPowerShellK1icrosoft.PowerShellIS3Profile.ps(&

    Fhenever you start a new PowerShell session, PowerShell initialiOes itself using a very special

    script called a profile script, and the path to this profile script stored in the $rofi'evariable.

    Probably your current profile script is located in documents folder under Findows PowerShell

    and is named #irosoft-o0ers!e'':SErofi'e-s;. #his is especially true if you are using an

    IE3 for PowerShell.

  • 8/21/2019 PowerShell training Primer

    25/29

    -ou can see the four profile scripts available. #wo of the scripts apply to all users on the system

    while the other two profile scripts apply to the current user. In addition, two of the profile scripts

    apply to all hosts on the system and the other two profile scripts apply to the current host.

  • 8/21/2019 PowerShell training Primer

    26/29

    SandbaggingDommand

    Dode$

  • 8/21/2019 PowerShell training Primer

    27/29

  • 8/21/2019 PowerShell training Primer

    28/29

    >dd new menu item to help menu$

  • 8/21/2019 PowerShell training Primer

    29/29

    Split Path#9oin Path


Recommended