迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 >

在 PowerShell 中注释代码

作者:迹忆客 最近更新:2024/03/04 浏览次数:

如果你使用过其他语言,例如 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.

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

在 Windows PowerShell 中获取命令行参数

发布时间:2024/03/04 浏览次数:358 分类:编程语言

本文将解释我们如何使用 PowerShell 的参数函数处理命令行参数,参数如何工作,我们如何使用 PowerShell 参数将值传递给参数,以及定义参数的基本方法是什么。

Windows PowerShell 中的 Base64 编码

发布时间:2024/03/04 浏览次数:332 分类:编程语言

本文将展示如何编码和解码 base64 字符串。Windows PowerShell 当前版本没有本机命令,因此我们将向你展示如何执行此操作的替代方法。

在 Windows PowerShell 中写入输出

发布时间:2024/03/04 浏览次数:259 分类:编程语言

本文将向你展示如何在 Windows PowerShell 中编写或打印输出。本文还将区分多个 write cmdlet 并解释它们的意义。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便