在 PowerShell 中注释代码

如果你使用过其他语言,例如 Bash、Python 和 Ruby,则在 Windows PowerShell 中注释掉将是类似的。

本文将讨论可用于在 Windows PowerShell 中注释代码的所有用例。

使用注释符号 (#) 的 PowerShell 单行注释

从一开始,PowerShell V1.0 就已经发布并发布给公众,具有注释代码的功能。我们使用符号(#)注释代码。我们用许多名称来称呼这个符号,例如数字符号或哈希,但微软官方将其称为注释符号。

单个注释符号 (#) 将注释掉从第一个 # 到行尾的代码。当然,你也可以将多个注释符号放在一行中。

示例代码:

#######################################################
# Examples of one-line comments in Windows PowerShell #
#######################################################
Get-Process -Name *host* #### You could put more.
Get-Process -Name *host* # | Stop-Service # You can use it to comment out a part of a line.
# Get-Process -Name *host* # This will comment out the whole line.

注释代码时,最好在注释符号和代码之间留一个空格。一些 cmdlet 使用注释符号,但不用于注释代码。例如,#REQUIRES cmdlet 是一个众所周知的 PowerShell 语句,它将阻止脚本运行,除非满足模块或先决条件管理单元。

示例代码:

Get-Module AzureRM.Netcore | Remove-Module
#REQUIRES -Modules AzureRM.Netcore

使用这些最佳实践,我们可以避免脚本中出现不必要的错误。

PowerShell 使用注释块注释多行代码

要在不使用每行多个注释符号的情况下注释多行代码,我们可以方便地用小于 (<) 和大于 (>) 符号将我们的注释符号括起来。我们称之为注释块。

带有小于号 (<#) 的注释符号将作为我们注释块的开始标记,而带有大于号的注释符号将用作结束标记 (#>)。

示例代码:

<#
Get-Process -Name *host*
Stop-Service -DisplayName Windows*Update -WhatIf
#>

值得注意的是,你可以在注释块之间插入单个注释符号。

示例代码:

<#
Get-Process -Name 'host1'
#Tested up until this point
Stop-Service -DisplayName Windows*Update -WhatIf
#>

但是,通过插入一组新的注释块标签来嵌套注释块将导致错误。

示例代码:

<#
Nope, these are not allowed in PowerShell.
<# This will break your first multiline comment block... #>
...and this will throw a syntax error. #This line will execute the throw cmdlet
#>

或者,按下 Ctrl+J 并单击 Comment Block 将在你的脚本中生成一个代码块。

使用 Exit 命令的 PowerShell 边缘案例场景

请记住,Exit 命令将终止并关闭你的脚本环境。因此,在 Exit 命令之后写入的任何内容都不会执行。我们称之为边缘案例场景。在 Exit 命令之后写一些东西是可能的,但不推荐,因为其他脚本环境可能会误读这些额外的行并导致错误。

示例代码:

Get-Process -Name 'host1'
exit
Anything beyond the `<# exit #>` line is not executed inside the PowerShell scripting environment. However, as mentioned before, this is not recommended despite being possible.