Anda di halaman 1dari 29

PowerShell

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.

#hese two commands return the same result$


$str = asdfx-99.txt # below is regEx for any # first-line escapes the $str -replace " #a-$%&!$str -replace " #a-$%&!chars, $ with 'd&!", 'd&!", followed by a followed by some digits a back-tick a backward accent mark! "($)-($*" # $) is the )nd +egEx e,al- $* the *st .$)-$*.

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

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 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 @{

to create a hashtable 3.ample$ "myHash#able 4 56 a4(7 b4)7 c4* 8

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

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

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


!se "etB

o##and !se $er%Bno&n

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$

get-help get-exec0tionpolicy full

PowerShell outputs details for every parameter the command accepts, as well as notes e.amples of how to use the command.

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


!se "etB!e'( Bf&''

"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

The Top *+ Commands

Chaining with the Pipe Symbol


!seH to find chain commands together Fhatever is output from the command before the pipe will be e.ecuted like it was on the ne.t line of script, similar to chaining together actions in IJuery. 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 variable to change to$ c$KusersKlolevy %your used id& !se cd to change directories %like E2S& !se cd !se cd

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

!se (0d to 1rint 2orking Directory

3 refers to c:\users\<WindowsId>
hard drive

cd ~/documents goes to your documents provided your shell is your

!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#

.@3# uses [environment]::currentDirectory which is c:\users\<WindowsId> S-,.T/-01


/# 8o0 can p0t any logic yo0 want into this f0nction, since f0nction prompt gets called after e,ery 9ower:hell command exec0tes, it.s a great place to keep yo0r c0rrent directory and location in synch2 #1 cls
f0nction prompt ; $c0rdir = get-location -PSProvider file:ystem < select-object -expand 9ath-

#set the path e40al to the c0rrent windows directory


#en,ironment%22=0rrent>irectory = $c0rdir "9: $pwd1 "

#7ell 9owershell to show the working directory at the prompt ?

Creating 0ew Te2t Files


# write content to the data.txt file instead of the console # -inp0tob@ect is the content to write yo0 will o,erwrite 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 -inputobject .this is the first line.. get-content .Adata.txt cls out-file .Adata.txt -inputobject .this is the second BBB5. get-content .Adata.txt

# write content to the data.txt file instead of the console # 0sing the 1 symbol $firstline = "this is the first Cine"

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 $firstCine 11 .Adata.txt cls get-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 $secondCine 11 .'data.txt ls # ,erify both are there get-content .Adata.txt
# Eeed to prefix the file with date, so create a new text file with @0st the date

get-date 1 .Adata).txt# 6ppend the data in data.txt to data).txt

get-content .Adata.txt 11 .Adata).txt cls

# recreate the data.txt file with date, by copying datat).txt to data.txt

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.

Creating .0ET -b5ects


!se reate ne0/o%7e t to new0up an obIect. 3.ample$
$ob@ = new-ob@ect :ystem.text.+eg0larExpressions.+egEx H. @pg<@peg<tiff<bmp!I!-

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

.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 e.ample$ if! [string]::"s#ullor$mpty $,arDser! ! 2nce you have an obIect 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 e.actly what it is$ %obj get-member
-ou can also get information with

get-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# 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.

6eading a te2t 7ile


!se cat .*filename to display a file<s contents

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

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

Format the Prompt

Prompt reset$

Putting it back after we are done$

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

!se remove-module module#ame to 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.comSscriptcenter Dodeple..com Psget.netSdirectory

")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.

Finding 8our Pro7ile Script


!se $1rofi'e to find out which .ps( file is running as your profile
%Probably D$K!sersK9o9evyKEocumentsKFindowsPowerShellK1icrosoft.PowerShellIS3PProfile.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'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.

Pro7iles and Hosts


-ou might e.pect the push0proIect command to be available inside of the PowerShell IS3. Lut if I try to run the command, I get an error from PowerShell indicating that that command is not defined. If you look at the value of the profile variable inside of the IS3 environment and then compare it to the value of the profile variable available inside of the console, you'll notice that there are actually two different files. #he IS3 profile script lives in the same directory what is called 1icrosoft.PowerShellIS3Pprofile.ps(. I can use the same process I used on the console to create a profile script for the IS3 environment. Dreate the new profile script using the new item commandlet and then use invoke0item on the profile path to open up the script for editing. I simply add any PowerShell I want to use to initialiOe the IS3 when it's opened. I'll add the push0 proIect function as well as the push0proIect alias. Fhen I save the profile script, and open up a new instance of the IS3 environment, the push0proIect command is available for use. #ruth be told, there are four profile scripts that are available to your PowerShell session. If I take the profile variable, type it through the select obIect command and use the star parameter to indicate that I want to see all of the property names and values on that obIect.

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

>dd new menu item to help menu$

Split Path#9oin Path

Anda mungkin juga menyukai