在 PowerShell 中如何注释代码

  1. 使用注释符号(#)进行 PowerShell 单行注释
  2. 使用注释块在 PowerShell 中注释多行代码
  3. 通过使用 Exit 命令的 PowerShell 边缘情况
在 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
#>

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

示例代码:

<#
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.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn