《Learn Windows PowerShell in a Month of Lunches Third Edition》读书笔记—CHAPTER 22 Improving your script

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_41104353/article/details/82381933

22.1 Starting point

Starting point: Get-DiskInventory.ps1

此段脚本和之前的区别是将 Format-Table 改成了 Select-Object 。因为我们认为如果一个脚本输出的结果的格式是预定义好的,这样会不太好。假设有个人想要将结果输出到csv文件中,脚本输出的却是格式化的表格,这样就不太好了。所以我们应该给用户权限来自定义输出的格式。如上脚本可以这样:
PS C:\> .\Get-DiskInventory | Format-Table 来产生格式化的表格。
PS C:\> .\Get-DiskInventory | Export-CSV disks.csv 来将结果写入csv文件。

技巧就是用Select-Object输出对象,而不是格式化的显示。

22.2 Getting PowerShell to do the hard work

我们可以在脚本中添加一行 [CmdletBinding()] 来支持一系列有用的PowerShell功能。
Making Get-DiskInventory.ps1 an advanced script

注意 [CmdletBinding()] 必须在脚本的第一行,在上图中就是紧跟着注释的后面。加上了这一句后,我们就可以使用高级脚本,下面将一一介绍。

22.3 Making parameters mandatory

我们可能对 -ComputerName 参数的默认值不太满意,因为我们不知道别人是否需要。这个时候,我们就可以采用弹出框的方式来询问使用者。做到这点只需要在上图的基础上增加一行装饰器(decorator):
Giving Get-DiskInventory.ps1 a mandatory parameter

如果别人运行你的脚本的时候并没有提供一个强制的参数,PowerShell就会弹出一个框来要求他们填写参数。

我们可以对该装饰器增加更多参数来给出更多提示信息:
[Parameter(Mandatory=$True,HelpMessage="Enter a computer name to query")

我们对 Param() 分解看看:
Breaking down the Param() block syntax
注意这里的 Mandatory 参数只修改 -computerName ,对 -drivetype 并不产生影响。

22.4 Adding parameter aliases

如果觉得某个参数的名字别扭的话,如你觉得将 -computerName 改为 -hostname 更容易记忆,那么我们可以采取如下方式来为参数更名:
Adding a parameter alias to Get-DiskInventory.ps1

更改完后,我们可以运行 PS C:\> .\Get-DiskInventory -hostname SERVER2
我们可以注意到 computerName 参数的定义占了三行。当然,我们也可以写成一行:
[Parameter(Mandatory=$True)][Alias('hostname')][string]$computername

22.5 Validating parameter input

如果我们想要保证用户输入的值是在某个范围内的,可以像下面的脚本那样:
Adding parameter validation to Get-DiskInventory.ps1
这个新的装饰器告诉PowerShell -drivetype 参数只能接受2和3两个值,3是默认的。

我们可以使用 help about_functions_advanced_parameters 查看更多高级用法。

22.6 Adding the warm and fuzzies with verbose output

我们可以使用Write-Verbose对脚本运行时增添更多提示信息:
Adding verbose output to Get-DiskInventory.ps1

但是,我们运行的时候得注意,因为 PS C:\> .\Get-DiskInventory -computername localhost 这样是不会输出我们添加的部分。得写成 PS C:\> .\Get-DiskInventory -computername localhost -verbose 才行。

里面还有个小技巧是我们将变量 ($computername)写进了双引号内,这样输出就包含了变量的值。

猜你喜欢

转载自blog.csdn.net/sinat_41104353/article/details/82381933