如何在 PowerShell 中註解程式碼

  1. PowerShell 單行註解使用註解符號(#
  2. PowerShell 使用註解區塊註解多行
  3. PowerShell 邊緣情況場景使用 Exit 命令
如何在 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,將在您的腳本中生成註解區塊。

PowerShell 邊緣情況場景使用 Exit 命令

請記住,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