3. PowerShell Variables
PowerShell variables work much like variables in other scripting languages: they hold data. A variable name starts with a
dollar sign and what follows can be any string of characters. But what
makes variables in PowerShell particularly useful is that they can
capture the output of Cmdlets, and then be put in place of static
information in subsequent Cmdlets, like this:
$url = "http://www.nytimes.com/services/xml/rss/nyt/Science.xml"
$content = [xml](new-object System.Net.WebClient).DownloadString($url)
$content.rss.channel.item | select title -first 8
The first line fills the $url
variable with the address of a web site (specifically, an RSS feed for
the purposes of this example). The next line downloads the file at the $url address and sends it to the $content
variable. And the last line uses a pipe (discussed earlier) to first
process the news feed and then show only the first eight headlines.
You can also assign a variable to a command, or more importantly, a series of commands, like this:
$showtemp = Get-ChildItem 'C:\Users\Administrator\AppData\Local\Temp' -rec
then, to execute the command (complete with all the juicy command-line parameters), just type:
$showtemp
and (in this case), you'll see a listing of all the files in your Temp folder.
Variables can also be used with object references, just like in WSH scripts . PowerShell even makes use of some of the same objects as WSH, like this one:
$WshShell = New-Object -ComObject WScript.Shell
This means you can use this object to do things like access the Registry or create shortcuts. For instance, once the $WshShell object has been initialized, try this:
$lnk = $WshShell.CreateShortcut("$Home\Desktop\Solitaire.lnk")
$lnk.TargetPath = "%ProgramFiles%\Microsoft Games\Solitaire\Solitaire.exe"
$lnk.Save( )
which creates another object reference, $lnk, applies characteristics to it, and then saves it to a file. Note some subtleties:
The preset $Home variable conveniently contains the full path of the current user's home folder.
The
quotation marks are significant in that if you were to substitute the
"double" quotes with 'single' quotes, PowerShell would not interpret
your variables, but rather leave them literally as you've typed them.
The %ProgramFiles%
environment variable—a separate entity from PowerShell variables.
See the PowerShell documentation for more ins and outs of variables and object references.
4. PowerShell Scripts
Like
the WSH scripts or DOS batch files, a PowerShell script is just a text
file with a list of commands. Just type the commands into a Notepad
window or other text editor, and save it to a file with the .ps1 filename extension.
Unfortunately,
you can't run PowerShell scripts until you jump through a few hoops to
disable some of the security safeguards. The first step is to check the
execution policy by typing:
Get-ExecutionPolicy
If the reply you get is Restricted (the default), then you need to type this command to allow script execution:
Set-ExecutionPolicy RemoteSigned
To run a script from
an open PowerShell window, type the name of the script file, complete
with its path and filename extension, like this:
$home\Desktop\MakeShortcut.ps1
Unlike the Command Prompt,
you can't leave off the path if the script is in the same folder as the
working folder. For instance, this doesn't work:
MakeShortcut.ps1
but this does:
.\MakeShortcut.ps1
The single dot (.) represents the current folder, and is necessary when launching scripts from the PowerShell command line.
Also,
and presumably for security reasons, you can't run PowerShell scripts
by double-clicking them until you make a change to your system. To
enable script launching, right-click a .ps1 file, select Open With → Choose Default Program, click Select a program from a list of installed programs, and then click OK. Click Browse, locate the PowerShell executable (usually C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe), and click OK.
By
default, the PowerShell window closes when it's done executing a
script, but you can change this by modifying the file type and adding the -NoExit option to the powershell.exe command line. |
|
Thereafter, you can double-click any .ps1 file to run the script.
5. Automate Scripts with the Task Scheduler
Vista's
Task Scheduler is fairly simple, allowing you to schedule any program
or—any script to run at a
specific time or regular intervals.
To open Task Scheduler, open your Start menu, type taskschd.msc /s in the Search box, and press Enter. (Omit the /s
parameter to jump to the Task Scheduler Library instead of showing the
summary page by default.) The Task Scheduler tool in Windows Vista (Figure 2) is complex and somewhat unfriendly, which is surprising since it replaces the simpler (and more feeble) Scheduled Tasks folder in earlier versions of Windows.
What's
nice about Task Scheduler is that it's actually a technology that is
somewhat well integrated into the operating system. Any application can
create a schedule for itself, and you can plainly see those that are in
effect simply by opening Task Scheduler and selecting the Task Scheduler Library
folder. For the more forgetful among us, you can use it to schedule
backups once a week, remind you to stand up and stretch once an hour, or
even fire up Media Center when your favorite TV show is about to air.
To create a new schedule, click the Create Basic Task link in the Actions pane to your right, and then answer the questions as follows:
Create a Basic Task
Type the name of the task to appear in your task library; the description is optional.
Trigger
Choose when to run the task: Daily, Weekly, Monthly, One time, When the computer starts, When I log on, or When a specific event is logged.
Daily, Weekly, etc.
Specify your criteria for the trigger you chose. For instance, if you selected Daily, you'll be asked what time of day to carry out the task, and for how many days in a row.
Action
Here's where you specify what to do. If you want Task Scheduler to run a script, select Start a program, click Next, and then specify the full path and filename of the script to run.
Finish
This one speaks for itself.
Or, if you don't like wizards, you can click the Create Task link instead to jump right to the Properties window shown in Figure 3. Here, only two pieces of information are required: the Name (under the General tab) and at least one action (under the Actions tab). But if you want Task Scheduler to ever run your task, you need to add your criteria (Daily, Weekly, etc.) under the Triggers tab. Click OK when you're done.
The Task Scheduler Library is a little confusing, especially if you're used to the Scheduled Tasks folder in earlier versions of Windows. Only on the Summary page—select Task Scheduler (Local) in the folder pane on the left—are all your active tasks shown in one place, and it's at the bottom of the window.
In the Actions pane on the right, click the View link and then select Show Hidden Tasks to make sure you're seeing everything Task Scheduler is doing. |
|
In
the Active Tasks pane, you can double-click any task to jump to its
entry in the hierarchical library, or click the tiny arrow next to the Task Scheduler Library
folder on your left to expand the branches and browse the categories.
Once you're in the library, highlight a task to view its details in the
pane below, or double-click it to edit its properties.
You can also create a new task on the fly from the Command Prompt (or the Address Bar, for that matter). Use the at command, like this:
at 11:15 /interactive c:\scripts\myscript.vbs
Naturally, you'll want to replace 11:15 with the time you actually want the task to run, and replace c:\scripts\myscript.vbs with the full path and filename of the application or script you wish to schedule. You can also use the /every option to specify a repeating day or date, or the /next option to specify only a single day:
at 15:45 /interactive /every:tuesday,thursday c:\scripts\myscript.vbs
at 15:45 /interactive /next:saturday c:\scripts\myscript.vbs
Type at /? at the Command Prompt for more options. To specify which user account is responsible for running tasks created with the at command, open Task Scheduler, click Task Scheduler (Local) on the left, and then click the AT Service Account Configuration link in the Actions pane to your right.
Task
Scheduler does have its pitfalls. For one, it's a rather passive
service, and while that's an aspect I like, at least ideologically, it
means that tasks can very easily be missed. Your scheduled tasks will
not be performed if your computer is turned off, if Windows isn't
running (or has crashed), or if the Task Scheduler service isn't running
for some reason. Also, some tasks will only run if you're logged in,
and then only if you're running on AC power (not on a battery). These
may be obvious, but they can be easy to forget, and Windows won't
necessarily tell you whether it missed any tasks; for this, you'll need
to check the event log.
If
you're using a laptop, and are worried that some of your tasks aren't
being performed when you're running off a battery, you can change this
on a task-by-task basis. First, edit a task by double-clicking it, and
then choose the Conditions tab.Turn off the Start the task only if the computer is on AC power option to run it regardless of the power source. If you put your PC to sleep frequently, you may also want to turn on the Wake the computer to run this task option. (Naturally, use these options only for vital tasks to prevent needlessly draining your battery.) Click OK when you're done. |
|
The
use of a scheduler opens up some interesting possibilities. Scheduling
helps with repetitive chores, such as running Disk Defragmenter or
synchronizing network files; it also helps by taking care of things you
may not remember to do yourself, such as backing up or checking the
amount of disk space and sending you a text message on your cell phone
when it drops below a certain point. And on the flip side of the coin,
Task Scheduler is likely doing some things you don't want or need it to
do; it's wise to periodically check this tool and eliminate tasks that
might be degrading performance or compromising your PC's security.