Pular para o conteúdo principal

10 fundamental concepts for PowerShell scripting

10 fundamental concepts for PowerShell scripting: "

PowerShell scripts offer a handy way to automate various chores. Here are some key concepts that will help beginners as they start developing PowerShell scripts.


Note: This article is also available as a PDF download.


1: PS1 files


A PowerShell script is really nothing more than a simple text file. The file contains a series of PowerShell commands, with each command appearing on a separate line. For the text file to be treated as a PowerShell script, its filename needs to use the .PS1 extension.


2: Execution permissions


To prevent the execution of malicious scripts, PowerShell enforces an execution policy. By default, the execution policy is set to Restricted, which means that PowerShell scripts will not run. You can determine the current execution policy by using the following cmdlet:


Get-ExecutionPolicy

The execution policies you can use are:



  • Restricted - Scripts won’t run.

  • RemoteSigned - Scripts created locally will run, but those downloaded from the Internet will not (unless they are digitally signed by a trusted publisher).

  • AllSigned - Scripts will run only if they have been signed by a trusted publisher.

  • Unrestricted - Scripts will run regardless of where they have come from and whether they are signed.


You can set PowerShell’s execution policy by using the following cmdlet:


Set-ExecutionPolicy <policy name>

3: Running a script


For years now, if you wanted to run an executable file from the command line the practice was to navigate to the file’s path and then type the name of the executable file. However, this age-old method doesn’t work for PowerShell scripts.


If you want to execute a PowerShell script, you will usually have to type the full path along with the filename. For example, to run a script named SCRIPT.PS1, you might type:


C:\Scripts\Script.ps1

The big exception is that you can execute a script by simply typing its name if the folder containing the script is in your system’s path. There is also a shortcut you can use if you are already in the folder containing the script. Instead of typing the script’s full path in such a situation, you can enter .\ and the script’s name. For example, you might type:


.\Script.ps1

4: Pipelining


Pipelining is the term for feeding one command’s output into another command. This allows the second command to act on the input it has received. To pipeline two commands (or cmdlets), simply separate them with the pipe symbol (|).


To help you understand how pipelining works, imagine that you want to create a list of processes that are running on a server and sort that list by process ID number. You can get a list of processes by using the Get-Process cmdlet, but the list will not be sorted. However, if you pipeline the cmdlet’s output into the Sort-Object ID command, the list will be sorted. The string of commands used looks like this:


Get-Process | Sort-Object ID

5: Variables


Although you can use pipelining to feed one command’s output into another command, sometimes pipelining alone won’t get the job done. When you pipeline a command’s output into another command, that output is used immediately. Occasionally, you may need to store the output for a while so that you can use (or reuse) it later. This is where variables come into play.


It’s easy to think of a variable as a repository for storing a value, but in PowerShell, a variable can store a command’s full output. For example, suppose you want to store the list of processes running on a server as a variable. To do so, you could use this line of code:


$a = Get-Process

Here, the variable is named $a. If you want to use the variable, simply call it by name. For example, typing $a prints the variable’s contents on the screen.


You can assign a variable to the final output of multiple commands that have been pipelined together. Just surround the commands with parentheses. For example, to sort the running processes by process ID and then assign the output to a variable, you could use this command:


$a = (Get-Process | Sort-Object ID)

6: The @ symbol


By using the @ symbol, you can turn the contents of a list into an array. For example, take the following line of code, which creates a variable named $Procs that contains multiple lines of text (an array):


$procs = @{name='explorer','svchost'}

You can also use the @ symbol when the variable is used, to ensure that it is treated as an array rather than a single value. For instance, the line of code below will run the Get-Process cmdlet against the variable I defined a moment ago. In doing so, Windows will display all the processes used by Windows Explorer and Svchost. Notice how the @ symbol is being used in front of the variable name rather than the dollar sign that we usually see used:


Get-Process @procs

7: Split


The split operator splits a text string based on a character you designate. For example, suppose that you want to break a sentence into an array consisting of each individual word in the sentence. You could do so by using a command like this one:


'This is a test' -split ' '

The result would look like this:


This

is

a

test

8: Join


Just as split can split a text string into multiple pieces, the join operator can combine multiple blocks of text into one. For example, this line will create a text string consisting of my first name and last name:


'Brien','Posey' -join ' '

The space between the quotation marks at the end of the command tells Windows to insert a space between the two text strings.


9: Breakpoints


Running a newly created PowerShell script can have unintended consequences if the script contains bugs. One way to protect yourself is to insert breakpoints at strategic locations within your script. That way, you can make sure that the script is working as intended before you process the entire thing.


The easiest way to insert a breakpoint is by line number. For instance, to insert a break point on the 10th line of a script, you could use a command like this:


New-PSBreakpoint -Script C:\Scripts\Script.ps1 -Line 10

You can also bind a breakpoint to a variable. So if you wanted your script to break any time the contents of a$ changed, you could use a command like this one:


New-PSBreakpoint -Script C:\scripts\Script.ps1 -variables a

Notice that I didn’t include the dollar sign after the variable name.


There are a number of verbs you can use with PSBreakpoint including New, Get, Enable, Disable, and Remove.


10: Step


When debugging a script, it may sometimes be necessary to run the script line by line. To do so, you can use the Step-Into cmdlet. This will cause the script to pause after each line regardless of whether a breakpoint exists. When you are done, you can use the Step-Out cmdlet to stop Windows from stepping through the script. It is worth noting, however, that breakpoints are still processed even after the Step-Out cmdlet has been used.


Incidentally, if your script uses functions, you may be interested in the Step-Over cmdlet. Step-Over works just like Step-Into, except that if a function is called, Windows won’t step through it. The entire function will run without stopping.


Additional resources







"

Comentários

Postagens mais visitadas deste blog

Favigen, Favicon Generator

Favigen, Favicon Generator : " Favicons are small icons that help identify websites. They are used as a visual representation of a website both in the web browser and at many online services. The three most prominent locations of favicons are the browser’s address bar, the tabbar and the bookmarks folder. Many webmasters like to create custom favicons to add that custom identifier to their website. Favicons can be created in many image and icon editors, but also online. Favigen is a straightforward favicon generator that can turn an image into a favicon. All that it takes is to pick an image from the local hard drive first, select the dimensions of the favicon and click the submit button to make the service generate the favicon. Favigen supports several image formats, including jpg and png, and it does not seem to have size restrictions either. Available image dimensions range are 16×16, 32×32 and 64×64. The generated favicon is displayed directly on the page. A click on do...

A simple rsync script to back up your home directory

A simple rsync script to back up your home directory : " Backing up important data is obviously something we should all do. Unfortunately, it is not always easy to make it happen. We get lazy; we do not have the additional hardware for a backup server; it takes a long time and a lot of CDs to back up to optical media; we do not trust online backup services; backup schemes are difficult to set up and use — any of dozens of reasons can stand in our way. Still, we know we should be backing up our important data. Modern open source Unix-like operating systems offer a plethora of options for incredibly simple, effective backup schemes, however. If the problem is figuring out how to set one up, a simple rsync solution may be exactly what you need. The rsync utility is used to synchronize files between two systems. It does so by way of incremental copies, only copying from the source to the destination what has not already been copied there, saving time, network bandwidth, and syst...

Google Wave now open to the public: faster, Robots and Gadgets aplenty!

Google Wave now open to the public: faster, Robots and Gadgets aplenty! : " Filed under: Internet , Google If you somehow missed it, Google Wave is now a bonafide Labs project: rather than being an invite-only alpha, it's now a public beta test! If you don't already have an account, just head on over to Wave and use your regular Google login details. If you've not seen any of the Google Wave introductory videos , you should check them out -- they explain the whole thing a lot more succinctly than I ever could. Wave has also been enabled for Google Apps domains -- businesses could convert their internal communication to Waves today! Leading up to this public release there have a lot of changes. It's by no means finished, but Google Wave is now a lot faster . It's also more intuitive -- more useful -- and given the large number of Robots and Gadgets now reaching prime-time readiness, it feels like the mass adoption of Wave is imminent. Also, if you're an ol...