You run a nightly job that dumps a
bunch of text files on a certain folder and you want Windows PowerShell to go through
all the files in that folder and change them from a .TXT file extension to a .BAK. One line
of PowerShell does the trick:
Get-ChildItem E:\Logs\* -include *.txt | foreach {move-item $_
($_ -replace(".txt",".bak"))}
You leverage the Get-ChildItem cmdlet (alias DIR) against the E:\Logs directory
to look for any file ending in .TXT. This data set is then piped to a Foreach loop, where
the Move-Item cmdlet changes the file extension to .BAK. Note how ($_ - replace
(".txt",".bak")) is used to generate the new filename, and then the results of the string
replacement are used as the destination name for the Move-Item cmdlet. If you??™ve ever
had the pleasure of writing a Windows Shell Script or even VBScript to perform a similar
function, you can appreciate how elegant this solution is; it??™s where PowerShell really begins
to shine.
Working with the Registry
You cannot be a Windows administrator and not have to deal with the Windows registry
at least once a day. After all, it is the central point for almost all configuration data regarding
your system and applications. Typically, you would use Regedit.exe to edit the
Automatic Variables
While $_ is a commonly used automatic variable, numerous automatic variables
are defined by the system. Here are a few of the most useful ones:
?–? $_ Contains the current pipeline object
?– $? Contains True if the last operation succeeded; otherwise False
?– $Args Contains an array of the parameters passed to a function
?– $foreach Refers to the enumerator in a Foreach loop
?– $Home User??™s home directory; equivalent to %homedrive%%homepath%
?– $LASTEXITCODE Contains the exit code of the last Win32 executable
execution
?– $PsHome Directory where Windows PowerShell is installed
?–? $Host Contains information about the current console host such as
version number
453 Chapter 13: Windows PowerShell
registry, or if you wanted to script it, you could use the command-line tool Reg.
Pages:
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484