当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell - 多行注释

作者:精品下载站 日期:2024-12-14 05:24:56 浏览:12 分类:玩电脑

PowerShell - 多行注释


[玩转系统] PowerShell - 多行注释

使用 标签

在注释开头使用 标记在 PowerShell 脚本中创建多行注释。评论块内的所有行都是评论的一部分。

多行评论:

<#
Hello, this is 1st line of multiline comments,
this is 2nd line,
this is 3rd line.
#>

在编程中,我们使用注释块来提供有关代码的解释或详细信息。注释用于记录程序,以便每个程序员/开发人员都可以轻松理解它。让我们在示例中使用多行注释来了解如何在代码中使用它们:

多行评论:

<#  
This PowerShell script is
used to print the first ten 
whole numbers
#>

0..9 | % { write " $_" }

输出 :

 0
 1
 2
 3
 4
 5
 6
 7
 8
 9

在上面的示例中,在脚本中添加了一个以 结尾的多行注释块,该注释块描述了打印 09

注意:经过适当注释的代码很容易让开发人员和维护人员理解。

我们可以使用#对单行进行注释。在 PowerShell 2.0 或更早版本中,添加多行注释的唯一选项是在我们不希望 PowerShell 解释器读取的每一行的开头使用 #

这意味着如果代码解释有十行或更多行,我们必须在每行的开头放置十次#。像这样:

多行评论:

# Hello, we are at 1st line of multiline comments,
# we are at 2nd line,
# we are at 3rd line.
# we are at 4th line.
# we are at 5th line.

每行前面一遍又一遍地写#是不是很乏味?但按如下方式编写单行注释是有益的。

单行评论:

# This is the single-line comment in PowerShell.

让我们使用单行注释重写上一节中编写的示例。

单行评论:

# This PowerShell script is used to print the first ten whole numbers
0..9 | % { write " $_" }

输出 :

0
1
2
3
4
5
6
7
8
9

这里使用单行注释来解释代码。请注意,语法或表达式不会在注释块内执行。我们看下面的例子:

多行评论:

<#
Get-Location
#>

我们没有收到上述代码片段中的任何输出,因为 Get-Location 位于注释块中。为什么?这是因为 PowerShell 在执行过程中遇到 # 关键字或 关键字之间的任何内容时都会跳过代码部分。

使用快捷键

在 Visual Studio 中编写 PowerShell 脚本时使用快捷键添加多行注释。

使用快捷键:

Hello, we are in 1st line of multiline comments,
We are at the 2nd line,
We are at the 3rd line.
We are at the 4th line.
We are at the 5th line.

假设我们想对上面几行进行注释。为此,我们将首先选择行,然后按 ALT + SHIFT + A。它将用 将选定的行括起来,作为 。请参阅以下示例。

输出 :

<# 
Hello, we are in 1st line of multiline comments,
We are at the 2nd line,
We are at the 3rd line.
We are at the 4th line.
We are at the 5th line.
#>

这就是 PowerShell 中多行注释的全部内容。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯