我们如何在 powershell 中实现 %* ?

问题描述

当我尝试使用 powershell 在批处理脚本中执行 %* 时,它给了我一个错误。我需要为 %* 替换一些东西,以便它适用于以下代码片段:

%* ^| ForEach-Object { Write-Host $_ ; $filepath = 'loggerfile.log' ; $output_file =$(Get-Date).ToString() + ' ' + $_ ; Write-Output $output_file ^|  Out-File -FilePath $filepath  -Append -NoClobber}

解决方法

首先,知道为什么这不是有效代码:

%* $| ForEach-Object { Write-Host $_ ; $filepath = 'loggerfile.log' ; $output_file =$(Get-Date).ToString() + ' ' + $_ ; Write-Output $output_file ^|  Out-File -FilePath $filepath  -Append -NoClobber}

Get-Alias -Definition ForEach-Object | 
Format-Table -AutoSize
# Results
<#
CommandType Name                      Version Source
----------- ----                      ------- ------
Alias       % -> ForEach-Object                     
Alias       foreach -> ForEach-Object  
#>

这就是为什么你得到...

%*
%*: The term '%*' is not recognized as a name of a cmdlet,function,script file,or executable program.
Check the spelling of the name,or if a path was included,verify that the path is correct and try again.

...当你使用它时。

还有这个……

^

... 是一个终止符

第二,正如我上面评论的那样,你的代码不是单行的。你真正拥有的是这个......

ForEach-Object '*' ^| 
ForEach-Object { 
    Write-Host $PSItem 
    $filepath    = 'loggerfile.log'
    $output_file = $(Get-Date).ToString() + ' ' + $PSItem

    Write-Output $output_file ^|  
    Out-File -FilePath $filepath  -Append -NoClobber
}

...还有这个。

ForEach-Object '*' ^

根本无效。我很好奇你从哪里得到的。还有这个...

^|

... 因为这不是我在任何 PowerShell 文档、帮助文件、回购代码中见过的。这也不是本机任何东西的别名。

你是想这样做吗...

$^

这意味着 - 最后一个命令的第一个标记。但请注意,它“不”指的是整个命令。

| 管道当然是从它的左边到它右边的传递结果。你在期待什么...

ForEach-Object '*' ^| 

...做什么?即使你这样做了,那也是无效的,并且会出错。

ForEach-Object: You cannot call a method on a null-valued expression.

所以,你是想这样做吗...

%* $^

...这仍然是我 10 多年来从未见过的东西,我一直在搞乱 Monad/Windows PowerShell/PowerShell Core。

要了解您的代码在做什么,您需要执行两个步骤。

  1. 使用 PSSCriptANalyzer 根据 PowerShell 规则集验证您正在执行的操作

    Invoke-ScriptAnalyzer "$PWD\SomeScriptName.ps1"

  2. 跟踪执行,以便您可以看到堆栈。

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/trace-command?view=powershell-7.1

Trace-Command -Name metadata,parameterbinding,cmdlet -Expression {
%* ^| ForEach-Object { Write-Host $_ ; $filepath = 'loggerfile.log' ; $output_file =$(Get-Date).ToString() + ' ' + $_ ; Write-Output $output_file ^|  Out-File -FilePath $filepath  -Append -NoClobber}
} -PSHost

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...