Powershell多行命令中可以使用注释吗?

问题描述 投票:0回答:4

在 Powershell ISE 中调试和测试多行命令多年来一直困扰着我。我喜欢使用多行命令,因为它们很容易阅读,但它们使调试变得更加困难。例如,我使用以下命令来获取早于

$days
的文件夹(顺便说一下,这是有效的)。

$dirs = Get-ChildItem $targetDir -Directory -exclude *.ps1 `
    | Where CreationTime -gt (Get-Date).AddDays(-1 * $days) `
    | Sort-Object -Property LastWriteTime

我想将

AddDays
更改为
AddMinutes
以测试不同的结果集,但我想保留原始行,以便我可以轻松地来回切换。下面我复制了要保留的行并将其注释掉,并在新行上将
AddDays
更改为
AddMinutes
添加
#
会破坏多行功能。有没有一种简单的方法可以解决这个问题,我不必剪切复制的行并将其“移出”命令?或者有没有办法将命令拆分/取消拆分为多行或从多行中拆分出来?

$dirs = Get-ChildItem $targetDir -Directory -exclude *.ps1 `
#    | Where CreationTime -gt (Get-Date).AddDays(-1 * $days) `
    | Where CreationTime -gt (Get-Date).AddMinutes(-1 * $days) `
    | Sort-Object -Property LastWriteTime

(由于注释掉行,上面不起作用)

powershell powershell-ise
4个回答
7
投票

使用多行注释语法而不是#。

<# comment #> 

这应该允许您在多行命令中注释文本。

但是,这仅在您使用 Powershell 2.0 时才有效


6
投票

你的问题是[讨厌的、讨厌的]反引号。 [grin] powershell 知道 管道后面还有更多内容...因此,如果将管道放在正在传输的段的末尾,则无需添加反引号。像这样...

$dirs = Get-ChildItem $targetDir -Directory -exclude *.ps1 |
    # Where CreationTime -gt (Get-Date).AddDays(-1 * $days) |
    Where CreationTime -gt (Get-Date).AddMinutes(-1 * $days) |
    Sort-Object -Property LastWriteTime

6
投票

由于 powershell 期望在

|
,

之后继续 作为一行中的最后一个字符,您不需要反引号和
您可以采用不同的格式,然后较长管道中的单行注释仍然有效:

$dirs = Get-ChildItem $targetDir -Directory -exclude *.ps1 |
#   Where CreationTime -gt (Get-Date).AddDays(-1 * $days) |
    Where CreationTime -gt (Get-Date).AddMinutes(-1 * $minutes) |
    Sort-Object -Property LastWriteTime

4
投票

试试这个,它可以作为多行注释示例包含进来

$dirs = Get-ChildItem $targetDir -Directory -exclude *.ps1 `
<#    | Where CreationTime -gt (Get-Date).AddDays(-1 * $days) #> `
    | Where CreationTime -gt (Get-Date).AddMinutes(-1 * $days) `
    <# also comments explaining what you are doing can be included #> `
    | Sort-Object -Property LastWriteTime
© www.soinside.com 2019 - 2024. All rights reserved.