PowerShell Training Primer
PowerShell Training Primer
Variables
Variables begin with a $ and their VALUE gets interpreted inside strings with DOUBLE QUOTES.
In this case, I'm referencing the variable s inside of the string. PowerShell does the interpolation 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.
99-asdfx.txt
#1
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 s uare brackets and you can assign to specific members using standard synta.. In addition, PowerShell supports slicing of the array. /or e.ample, 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 mi.ed type too. In this e.ample, the array will contain the numbers (, ), the string * and the numbers + and ,.
Hash Tables
!se @{
In this e.ample, 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 s uare brackets. "hash:;b<= -ou can also use this to assign values to specific keys in the hash table. In this e.ample, I assigned the ra variable which contains an array to the hash table at key b. "hash:;b<=4"my>rray
Flow Control
If? 3lse?#hen
#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 e ual to the number A even though they're both considered to be false inside of a conditional e.pression.
$global2a = 3$global2b = ..$a -e4 $b $b -e4 $a #tr0e#false-
ForEach
!se %(
or
forea !
-ou !se the foreach operator to iterate over a list. In this e.ample, the foreach operator pulls the values from the list (, ) and *, assigning each value to a then e.ecuting 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 while statement. In this e.ample, the while statement will e.ecute the following block of code as long as the value of a is greater than A. 3ach time the block of code is e.ecuted, the value of a is decremented by ( then the value of a is added to ,AA and output to the console.
.ToString(
B$er%
"et
#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$
PowerShell outputs details for every parameter the command accepts, as well as notes e.amples of how to use the command.
"etB!e'( a%o&t)* !se "etB!e'( GsomethingG Be+a#('es !se $er%Bno&n !se "etB#e#%er to find out what something can do
or
, to move to the root of the drive %like E2S& -- to move up one directory %like E2S&
./documents
!se .et/'o ation or C9 to retrieve your current location %current folder& !se Set/'o ation and pass it a relative or absolute path to the new location set-location
from
c:\users\<WindowsId>
3 refers to c:\users\<WindowsId>
hard drive
!se $!o#e instead of the tilde !se (&s!d 3 to push the directory to the c$K!sersKlolevy folder !se (&s!d to push to a different folder and give it a relative or absolute path to the new location !se (o(d to 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 sa$es 4o&r &rrent 'o ation on to a sta 5, before moving you to the new location. Fhen you're done working at the new location, use the PowerShell (o(d o##and'et to %o&n e %a 5 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 ne.t 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 will return 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 -path foo-from-powershell.txt -type file -value .hello5.
to create a file in the e.isting fo'der using PowerShell !se #io.file%22write6ll7ext "bar-from-dotnet.txt","hello again5" ! to create a file in the e.isting 'o ation using .@3#
# write content to the data.txt file instead of the console # 0sing the 1 symbol $firstline = "this is the first Cine"
get-content .Adata).txt 1 .Adata.txt cls # ,erify content starts with date and has both lines get-content .Adata.txt
/# Forces 9ower:hell to look at the .*&*. FG+:7, e,al0ating 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 in$o5e/ite# or ii to invoke an item
Invoke0item is PowerShell's e uivalent to a double click in Findows 3.plorer. In this e.ample, I used invoke item on a te.t file, and PowerShell open the file, and the default te.t editor on the
system, which is notepad. I can use this techni ue open any registered file type on the system for e.ample, a Power Point presentation. -ou can also pipe things to invoke item. /or e.ample, I can get a list of every te.t file on the current directory, pipe it to invoke item, and PowerShell will open each te.t file in turn. If you specify a folder path to invoke item, it'll open that folder in Findows 3.plorer. #his gives you a very handy way to move between the two shells in Findows
PowerShell 4 .0ET
!se $1SVersionTa%'e to 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.
!se $1SVersionTa%'e to find out which versions PowerShell and .@3# you are running
6e7erencing Types
#o get a reference to a .@3# type in PowerShell, simply surround the name of the type with s uare 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 e.ample above, the reference to sha( is assigned to the local variable $s.
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# obIect that acts as an event listener for another .@3# obIect that's the event source. In this case, you're listener obIect subscribes directly to the event source. Fhen the event is raised by the event source, it's raised directly back to your .@3#
obIect. Ly contrast in PowerShell, your script will re uest the 1o0erS!e'' r&nti#e to s&%s ri%e to t!e e$ent using 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'e cmdlet enables you to send pipelined output directly to a te.t file rather than displaying that output on screen. /or e.ample, this command retrieves process information using Cet0Process, then uses 2ut0/ile to write the data to the file D$KScriptsK#est.t.t$ Jet-9rocess ' (ut-)ile c:*scripts*test.t+t Ly default 2ut0/ile saves the data e.actly the way that data appears in your Findows PowerShell console. #hat means that some of the data could end up truncated.
,oading Assemblies
#here are several ways to load assemblies into PowerShell.
!se add0type with an assembly@ame parameter representing the name of the assembly that you want to load.
#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<s say that we have created .@3# assembly named Dustom#ypes.dll which defines a single public type named User in the namespace 9&sto#T4(es. #he user type e.poses a few public string properties. !se the PowerShell range operator to define the numbers one to a hundred and then pipe these numbers to the forea ! cmdlet, and for each one of these numbers, create a new0obIect of type 9&sto#T4(es-&ser. In addition, I'm going to use the new obIect property parameter to initialiOe each of these obIects. /or the name property of each user, I will specify a string that contains the name user and then the dollar undervalue, which will be the current number using the "P to grab them QitemR value.
!se e+port ,- ./filename %state the path and file name& to e.port to a .csv file
Searching
Functions
Scope
!se %global:var#ame to give a variable global scope
Prompt reset$
'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 re uire functionality from another module that you may or may not have installed. !se get-module listavailable to list all modules available for import on the machine. !se get-command -module module#ame to list all functions in the module.
")hat/7
!seB2!at:f at the end of your command to find out what will happen if you e.ecute 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 e.ecute that command.
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'e variable. Probably your current profile script is located in documents folder under Findows PowerShell and is named #i rosoft-(o0ers!e'':SE)(rofi'e-(s;. #his is especially true if you are using an IE3 for PowerShell. <&st %e a&se t!e (rofi'e s ri(t is 5no0n to 1o0erS!e'' doesn6t #ean t!at t!e fi'e e+ists-
If I pass the "profile variable to the test path commandlet, PowerShell tells me that this profile script doesn't actually e.ist yet. I'm going to go ahead and create it using the new item commandlet, Iust filling a type of file and providing the profile path. @ow that the file e.ists, I can edit my profile script using the invoke0item commandlet and passing at the profile path. I can add the push proIect function to my profile script and save it. @ow, when I start a new PowerShell session, the push0proIect command is available. I can include any valid PowerShell statements I want inside of this profile script. /or e.ample, maybe I don't want to type push0 proIect all the time. I want to create a shorter alias for the command. I can add a call to the new alias commandlet, give it the name of the alias I want to create, set the value for the alias to the push0proIect command. If I save the profile script and open up a new PowerShell session. #he alias is available for use.
-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.
Sandbagging
Dommand
Dode$