《Learn Windows PowerShell in a Month of Lunches Third Edition》读书笔记—CHAPTER 21 You call this scriptin

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

21.3 Parameterizing commands

我们编写了一个叫 Get-DiskInventory.ps1 的程序,内容如下:

Get-WmiObject -class Win32_LogicalDisk -computername localhost 
-filter "drivetype=3" |
 Sort-Object -property DeviceID |
 Format-Table -property DeviceID,
 @{label='FreeSpace(MB)';expression={$_.FreeSpace / 1MB -as [int]}},
 @{label='Size(GB)';expression={$_.Size / 1GB -as [int]}},
 @{label='%Free';expression={$_.FreeSpace / $_.Size * 100 -as [int]}}

但是当我们把它分享给别人的时候,别人可能想要对某些参数的值进行修改。这个时候,他们就得阅读源码然后修改。如果他们对PowerShell的编程不那么熟悉的话,这就会很不方便。所以,我么最好还是提供一种更加正规的方式来修改。这个时候,我们就要确定命令运行时可能会改变的东西,然后将这些东西用变量替换,如:
Get-DiskInventory.ps1, with a parameterized command

21.4 Creating a parameterized script

更进一步的,我们可以使用 param() 在我们的变量声明周围。这将 $computername 定义为参数,将其值设为代码运行的默认值。
这里写图片描述

我们可以通过执行 PS C:\> .\Get-DiskInventory.ps1 -computername server-r2 来运行,其中的 .\ 代指当前目录

21.5 Documenting your script

在PowerShell编程中,我们使用 # 定义一行注释,使用 <# #> 结构定义多行注释。我们对 Get-DiskInventory.ps1 增添如下的注释。
Adding help to Get-DiskInventory.ps1

然后,我们在PowerShell中运行 help .\Get-DiskInventory -full 就可以得到此程序的帮助。

猜你喜欢

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