The
syntax may look a little messy to the uninitiated, but it would be much more
difficult to do this sort of thing in WSH and nearly impossible in a batch file.
PowerShell Variables
PowerShell variables work much like variables in other scripting languages
(see ???Use Variables to Store and Manipulate Information,??? earlier in this
chapter): 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 Power-
Shell 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
Windows PowerShell | 569
Scripting and
Automation
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.
Pages:
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792