Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
1,68 MB
Nội dung
Introduction to Windows PowerShell Scripting CHAPTER 13
403
FIGURE 13-4 The dir command produces a directory listing of files and folders.
To create a directory, you can use the md command and supply the name of the directory
you need to create. As soon as a directory is created, you can create a text file by using the
redirection arrows to capture the results of a command, such as the dir command that was
used earlier. These results are shown in Figure 13-5.
FIGURE 13-5 To create a new directory, use the md command.
No feedback is displayed in Windows PowerShell when creating a file by redirection. The
text file that was created in the previous command is shown in Figure 13-6.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 13 Overview of Management Tools
404
FIGURE 13-6 The text file of a directory listing created by using the redirection operator
The last thing that might have to be done is to delete a text file and a folder. To do this, you
use the del command (the Windows PowerShell alias for the Remove-Item cmdlet) to delete
both the file and the folder. The first thing that you might need to do is to change your working
directory to the C:\HsgTest folder that was created earlier in this chapter via the md command
(see Figure 13-5). To do this, you use the cd command. After you are in the directory, you can
obtain another directory listing by using the dir command. Next, you use the del command to
delete the Directory.txt file. As shown in Figure 13-7, the file name is preceded by the “.\” charac-
ters. This means that you are interested in the file in the current directory. When you type the
first few letters of the file name and press the Tab key, “.\” is added to the file name automati-
cally as the complete file name is expanded. This enables you to avoid typing the complete file
name. The feature, known as a tab expansion, is a great time saver.
FIGURE 13-7 Use the del command to delete a file or a folder.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Introduction to Windows PowerShell Scripting CHAPTER 13
405
Using the Pipeline to Read Text Files
A common scripting task faced by IT professionals is reading text files. This usually
involves using a script similar to the SearchTextFileForSpecificWord.vbs script. In the
SearchTextFileForSpecificWord.vbs script, you create an instance of the Scripting.FileSystemObject,
open the file, and store the resulting TextStream object in the file variable. You then use the
Do…Until…Loop statement to work your way through the text stream. Inside the loop, you
read one line at a time from the text stream. As soon as you find a specific line, you use the
InStr statement to see whether you can find a specific word. If it does, you display the sen-
tence to the screen. The SearchTextFileForSpecificWord.vbs script is shown here.
SearchTextFileForSpecificWord.vbs
filepath = "C:\fso\testFile.txt"
word = "text"
set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile(filepath)
Do Until file.AtEndOfStream
line = file.ReadLine
If InStr(line, word) Then
WScript.Echo line
End If
Loop
The technique of using the ReadLine method is very efficient, and it is the recommended
way to work with large files from within VBScript. The other way of reading content from a
text file in VBScript is the ReadAll method. The problem with using the ReadAll method is that
it stores the contents of a text file in memory. This is not a problem if the file is small, but for
a large file, it consumes a large amount of memory. In addition to the memory consumption
issue, if you plan on working with the file one line at a time, which is one of the main reasons
for reading a text file, you now have to figure out artificial methods to work your way through
the file. With the ReadLine method and the TextStream object, you stream the file and it never
is stored in memory. The TextStream object from VBScript is similar to pipelining in Windows
PowerShell.
With Windows PowerShell, you do not have to write a script to do the same thing that the
SearchTextFileForSpecificWord.vbs script does. You can, in fact, perform the operation in just
three lines of code, as shown here.
PS C:\> $filepath = "C:\fso\TestFile.txt"
PS C:\> $word = "test"
PS C:\> Get-Content -Path $filepath | ForEach-Object {if($_ -match $word){$_}}
When you run these commands, you will see the output shown in Figure 13-8.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 13 Overview of Management Tools
406
FIGURE 13-8 Script-like commands can be typed directly into the Windows PowerShell console.
Before you go any further, examine TestFile.txt in Figure 13-9. This will give you a better
idea of what you are working with.
FIGURE 13-9 TestFile.txt contains several lines of text.
The first two lines that were typed into the Windows PowerShell console assign
string values to variables. This serves the same purpose as the first two lines of the
SearchTextFileForSpecificWord.vbs script. The last line typed in the Windows PowerShell
console is actually two separate commands. The first one reads the contents of the text file.
This is the same as creating an instance of the Scripting.FileSystemObject, opening the text
file by using the Do…While…Loop construction, and calling the ReadLine method. Here is the
Get-Content command.
Get-Content -Path $filepath
The results of the Get-Content cmdlet are pipelined to the ForEach-Object cmdlet. The
ForEach-Object cmdlet enables you to work inside the pipeline to examine individual lines as
they come across the pipe. The variable $_ is an automatic variable that is created when you
are working with a pipeline. It is used to enable you to work with a specific item when it is
located on the pipeline. In VBScript, you used the If…Then…End If construction. In Windows
PowerShell, you use an If(…){…} construction. The two serve the same purpose, however—
decision making. In VBScript, the condition that is evaluated goes between the If and the
Then statement. In Windows PowerShell, the condition that is evaluated goes between
parentheses. In VBScript, the action that is taken when a condition is matched goes between
the Then and the End If statements. In Windows PowerShell, the action that is matched goes
between a pair of braces.
In VBScipt, you used the Instr function to look inside the sentence to see whether a match
could be found. In Windows PowerShell, you use the –match operator. In VBScript, you use
the Wscript.Echo command to display the matching sentence to the screen, and in Windows
PowerShell, you only need to call the $_ variable and it is displayed automatically.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Introduction to Windows PowerShell Scripting CHAPTER 13
407
Of course, you do not have to use the Get-Content cmdlet if you do not want to, because
Windows PowerShell has a cmdlet called Select-String, which will look inside a text file and
retrieve the matching lines of text. The three lines of code seen earlier can therefore be short-
ened to this one-line command.
PS C:\> Select-String -Path C:\fso\TestFile.txt -Pattern "text"
The results of this command are shown in Figure 13-10.
FIGURE 13-10 The Select-String cmdlet reads a file and searches content at the same time.
diReCt FRoM tHe SoURCe
Command Output
James O’Neill, Evangelist
Developer and Platform Group
S
omething that takes some getting used to in Windows PowerShell is that any-
thing that PowerShell generates is treated as output (and the possible input to
a later command in a pipeline) unless you explicitly say you want to do something
else with it. Thus, you never need to use an echo, print, or write command. Windows
PowerShell does have commands to do these things, although many of them are
redundant. Write-Host is useful to force something to go to the console without be-
ing redirected. In other words, an external command like TaskList.exe generates text
and sends it to standard output as part of the command. A cmdlet like Get-Process
returns .NET process objects. Windows PowerShell loads formatting information
from PS1XML files, and when it has no other instructions, it checks to see whether
there is known formatting to apply to the object and uses that to send output to
standard output. Sometimes that standard formatting won’t work, and you want
to apply your own formatting. Windows PowerShell can output objects to comma-
separated variable (CSV) files or convert them to HTML tables, which can save a lot
of programming effort, but the most commonly used commands are Format-List
and Format-Table.
One of the things that you will really like to do with Windows PowerShell is to use the
formatting cmdlets. There are three formatting cmdlets that are especially helpful. They are
listed here, in the reverse order in which you will use them:
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 13 Overview of Management Tools
408
n
Format-Wide
n
Format-Table
n
Format-List
Consider the Format-Wide cmdlet. Format-Wide is useful when you want to display a
single property across multiple columns. This might happen because you want to have a list
of all process names that are currently running on the workstation. Such a command would
resemble the following.
PS C:\> Get-Process | Format-Wide -Property name –AutoSize
The first thing you do is use the Get-Process cmdlet to return all the processes that are
running on the computer. You next pipe the process objects to the Format-Wide cmdlet. You
use the –property parameter to select the name of each process, and you use the –autosize
parameter to tell Format-Wide to use as many columns as possible in the Windows Power-
Shell console without truncating any of the process names. You can see the results of this
command in Figure 13-11.
FIGURE 13-11 The Format-Wide cmdlet displays a single property.
If you are interested in displaying between two and four properties from the processes,
you can use the Format-Table cmdlet. The command might resemble the following.
PS C:\> Get-Process | Format-Table -Property Name, Path, Id –AutoSize
You first use the Get-Process cmdlet and then you pipeline the process objects to the
Format-Table cmdlet. You select three properties from the process objects: name, path, and
Id. The Format-Table cmdlet also has an –autosize parameter exactly as the Format-Wide
cmdlet does. This helps to arrange the columns in such a way that you do not waste space
inside the console. As shown in Figure 13-12, because of the length of some paths to process
executables, the –autosize parameter had no effect in this example, and the ID column was
removed. As a best practice, you always should include the parameter when you are unsure
what the output will actually resemble.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Introduction to Windows PowerShell Scripting CHAPTER 13
409
FIGURE 13-12 The Format-Table cmdlet makes it easy to create tables.
The format cmdlet that you will use the most is Format-List, because it is the best way to
display lots of information. It is also a good way to see what kind of data might be returned
by a particular command. Armed with this information, you then determine whether you
want to focus on a more select group of properties and perhaps output the data as a table or
just leave it in a list. When you use the Format-List cmdlet, you will usually use the wildcard *
to select all the properties from the objects. Here is an example of obtaining all the property
information from all your processes.
PS C:\> Get-Process | Format-List -Property *
This command displays information that scrolls off the display. A small sampling of the
information is shown in Figure 13-13.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 13 Overview of Management Tools
410
FIGURE 13-13 The Get-Process cmdlet displays process information.
There is so much information that all the properties and their values for a single process
will not fit on a single screen. When you work with the Format-List cmdlet, if you want to
look through all the data, you can pipeline the information to the more function. This works
in the same manner as the more command does in the command shell. If you use shortcut
names, or aliases, you have a very compact command at your disposal. As shown here, gps is
an alias for the Get-Process cmdlet. The fl command is an alias for Format-List. Because the
first parameter of the Format-List cmdlet is the –property parameter, you can leave it out of
the command. You then pipeline the results to more, which will cause the information to be
displayed one page at a time. This command is shown here.
PS C:\> gps | fl * | more
Additional Pipeline Techniques
The use of the pipeline is a fundamental Windows PowerShell technique. It is, therefore,
important to examine different ways to use the pipeline. In this section, you will examine the
use of the pipeline to avoid positional errors. You will also see how to use the pipeline to filter
result sets and make decisions on the data that crosses the pipeline.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Introduction to Windows PowerShell Scripting CHAPTER 13
411
Use the Pipeline to Avoid Positional Errors
If you want to obtain information about the Notepad process (assuming that Notepad is actu-
ally running), you use the Get-Process cmdlet, as seen here.
Get-Process Notepad
You do not have to specify the name parameter if you do not want to because the name
parameter is the default with Get-Process. You can, of course, type the name parameter and
obtain information about the Notepad process as shown here.
PS C:\> Get-Process -name notepad
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
47 2 976 3512 59 0.10 3960 notepad
To stop the Notepad process, you use the Stop-Process cmdlet. If, however, you are not
used to using the name parameter with the Get-Process cmdlet, you will receive a surprise
when you try the same syntax with Stop-Process. The result of this is seen here.
PS C:\> Stop-Process notepad
Stop-Process : Cannot bind parameter 'Id'. Cannot convert value "notepad" to type
"System.Int32". Error: "Input string was not in a correct format."
At line:1 char:13
+ Stop-Process <<<< notepad
+ CategoryInfo : InvalidArgument: (:) [Stop-Process],
ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.
Commands.StopProcessCommand
The reason for the error is that the name parameter occupies the first position for the
Get-Process cmdlet and the id parameter is the first-position parameter for the Stop-Process
cmdlet. When you did not use any named parameters, the Stop-Process cmdlet looked for a
process with the process ID of notepad, which is not an integer, and this caused the error. The
name parameter is a named parameter in the Stop-Process cmdlet. This means if you want to
use the name of a process to stop, you must specify the name parameter, as seen here.
Stop-Process -name notepad
To avoid these kinds of errors, you can always use the parameters (which is a best practice
when you write scripts), or you can use the pipeline. The advantage of using the pipeline is
that you do not have to worry about all the parameters. You can use Windows PowerShell to
find the process that you are interested in and pipeline the results of the first command to the
second command that will stop the process, as seen here.
Get-Process notepad | Stop-Process
A session that starts an instance of Notepad and identifies the Notepad process is seen in
Figure 13-14.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 13 Overview of Management Tools
412
FIGURE 13-14 Using the pipeline simplifies parameter complications.
You can use wildcard characters to identify processes. This technique can be both danger-
ous and useful. Here is an example of using wildcard characters to simplify finding all the
Notepad processes.
PS C:\> Get-Process note*
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
47 2 976 3464 59 0.05 2056 notepad
47 2 976 3488 59 0.09 3292 notepad
You can then pipeline the result to the Stop-Process cmdlet and stop all the instances of
the Notepad process that are running on the computer, as seen here.
Get-Process note* | Stop-Process
An example of working with processes by using wildcard characters is seen in Figure 13-15.
FIGURE 13-15 By using wildcard characters, it is easy to identify processes.
Using the wildcard characters can be dangerous if you are not careful, however. An example
of such a dangerous command is seen in the following code, which would obtain a list of
all the processes that are running on the computer and pipeline them to the Stop-Process
cmdlet. This will stop every process that is running on the computer, which for most operat-
ing systems will cause the computer to shut down (on Windows Vista and later versions, this
command must be run by someone with administrative rights).
Get-Process * | Stop-Process
Of course, if you want to shut down the operating system, it is best to use the shutdown
method from the Win32_OperatingSystem WMI class.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... graphical version of Windows PowerShell is called Windows PowerShell ISE Running Windows PowerShell Scripts To run the script, if you are running Windows XP or Windows Server 2003, you can open the Windows PowerShell console and drag the file to the console In Windows Vista, the capability of dragging to a command line was removed due to potential security implications To replace it, Windows Vista introduced... As Path from the action menu shown in Figure 13-22 Introduction to Windows PowerShell Scripting Chapter 13 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 421 Figure 13-22 Windows Vista introduced the Copy As Path command to simplify working with long paths inside the Windows PowerShell console Windows 7 has fixed dragging and dropping to the console, and it keeps the... the root drive is seen here PS C:\> Get-ChildItem | Where-Object { $_.mode -like 'd*' } Introduction to Windows PowerShell Scripting Chapter 13 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 4 17 The results of the list directory command are seen in Figure 13- 17 Figure 13- 17 By using wildcard characters, you can separate directories from files If you want to replicate the... maintains formatting seen on the Windows PowerShell console 420 Chapter 13 Overview of Management Tools Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark This concludes our overview of using Windows PowerShell to simplify working with directories and files Scripting Fundamentals In its most basic form, a Windows PowerShell script is a collection of Windows PowerShell commands,... System.Type GetType() ToString Method System.String ToString() LastWriteTime NoteProperty System.DateTime LastWriteTime=8/ 17/ 2008 1:23:10 PM Name 418 NoteProperty System.String Name=19287a2cfb60a3bbcca7 Chapter 13 Overview of Management Tools Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Understanding Cmdlet Output Objects It is important to understand the object that is... and understand it; with the quotation marks, PowerShell thinks it is a string constant To tell Windows PowerShell to execute a string as a command, prefix it with an ampersand (&) 422 Chapter 13 Overview of Management Tools Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark In Windows PowerShell, when you want to print a string in the console, you put it in quotation marks... policy available to you, you may be wondering which one is appropriate for you The Windows PowerShell team recommends the RemoteSigned setting, stating that it is “appropriate for most circumstances.” Remember that, even though deIntroduction to Windows PowerShell Scripting Chapter 13 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 423 scriptions of the various policy settings... basis Note that unlike batch files, Windows PowerShell scripts are not run automatically by double-clicking them in Windows Explorer, and scripts that you download will be flagged as such unless you remove the flag When you use the Set-ExecutionPolicy cmdlet to change the script execution policy in Windows PowerShell 1.0, the change occurs silently and without incident In Windows PowerShell 2.0, the behavior... command This is seen in Figure 13-24 Figure 13-24 In Windows PowerShell 2.0, the Set-ExecutionPolicy cmdlet requires confirmation If you do not want to see the confirmation message when you change the script execution policy in Windows PowerShell 2.0, use the –force parameter to make the behavior the same as it was in Windows PowerShell 1.0 Unfortunately, Windows PowerShell 1.0 does not have a –force parameter... fail A batch file command that will change the script execution policy on Windows PowerShell 2.0 is seen in the following code 424 Chapter 13 Overview of Management Tools Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark ChangeScriptExecutionPolicyPs2.bat REM ChangeExecutionPolicyPs2.bat REM Ed Wilson, 4/ 27/ 2009 REM Sets the script execution policy to remotesigned Other values: .
Next
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Introduction to Windows PowerShell Scripting CHAPTER 13
4 17
In Windows PowerShell,. LastWriteTime=8/ 17/ 2008 1:23:10 PM
Name NoteProperty System.String Name=19287a2cfb60a3bbcca7
Please purchase PDF Split-Merge on www.verypdf.com to remove