gpt4 book ai didi

powershell - 是否可以简化这个 PowerShell 关闭的想法?

转载 作者:行者123 更新时间:2023-12-04 07:38:58 25 4
gpt4 key购买 nike

在下面的想法中,我认为语法 | & $LogIt有点乱。它(IMO)肯定比拥有大量 | Out-File -FilePath thelog.log -Append 更好洒在脚本中。我发现剪切粘贴并忘记更改日志文件名太容易了。更糟糕的是忘记“初始化”(不是 -Append )日志 一次 .
我是否错过了另一个有助于实现此闭包背后的想法的 PowerShell 概念?

function MakeLogFile([string]$filename)
{
Get-Date | Out-File -FilePath $filename

{
param(
[ Parameter(ValueFromPipeline=$true,Mandatory=$true) ]
[string] $in
)
process {
$in | Out-File -FilePath $filename -Append
}
}.GetNewClosure()

}

$LogIt = MakeLogFile thelog.log

&$LogIt "monkey"

"1" | & $LogIt
"2" | & $LogIt
此示例未显示 MakeLogFile 中的一些其他“功能”集中我的问题。

最佳答案

将结果闭包分配给 function: 中的项目驱动器 - 这将与您使用 function 定义它具有相同的效果。关键字,因此您不再需要使用显式调用运算符:

function New-LogFile
{
param([string]$filename)

Get-Date | Out-File -FilePath $filename
{
param(
[ Parameter(ValueFromPipeline=$true,Mandatory=$true) ]
[string] $in
)
process {
$in | Out-File -FilePath $filename -Append
}
}.GetNewClosure()
}

# Assign closure to function: drive item
${function:Out-Log} = New-LogFile path\to\file.log

# Now we can call it like any other function
1..5 |Out-Log

关于powershell - 是否可以简化这个 PowerShell 关闭的想法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67588959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com