我有一个管道功能,可以在begin
块中分配一些需要在末尾处理的资源。我已经尝试在end
块中执行此操作但在函数执行中止时未调用,例如ctrl
+ c
。
如何修改以下代码以确保始终处置$sw
:
function Out-UnixFile([string] $Path, [switch] $Append) {
<#
.SYNOPSIS
Sends output to a file encoded with UTF-8 without BOM with Unix line endings.
#>
begin {
$encoding = new-object System.Text.UTF8Encoding($false)
$sw = new-object System.IO.StreamWriter($Path, $Append, $encoding)
$sw.NewLine = "`n"
}
process { $sw.WriteLine($_) }
# FIXME not called on Ctrl+C
end { $sw.Close() }
}
编辑:简化功能
答案 0 :(得分:5)
不幸的是,没有好的解决方案。确定性清理似乎是PowerShell中的明显遗漏。它可以像引入一个总是被调用的新cleanup
块一样简单,无论管道如何结束,但唉,即使版本5似乎也没有提供任何新东西(它引入了类,但没有清理机制)。 / p>
尽管如此,还是有一些不那么好的解决方案。最简单的是,如果您对$input
变量进行枚举而不是使用begin
/ process
/ end
,则可以使用try
/ finally
:
function Out-UnixFile([string] $Path, [switch] $Append) {
<#
.SYNOPSIS
Sends output to a file encoded with UTF-8 without BOM with Unix line endings.
#>
$encoding = new-object System.Text.UTF8Encoding($false)
$sw = $null
try {
$sw = new-object System.IO.StreamWriter($Path, $Append, $encoding)
$sw.NewLine = "`n"
foreach ($line in $input) {
$sw.WriteLine($line)
}
} finally {
if ($sw) { $sw.Close() }
}
}
这有一个很大的缺点,就是你的函数会占用整个管道直到一切都可用(基本上整个函数被视为一个大的end
块),如果你的函数是预期的,这显然是一个交易破坏者处理大量输入。
第二种方法是坚持使用begin
/ process
/ end
并手动处理Control-C作为输入,因为这确实是有问题的。但决不是仅有问题的位,因为在这种情况下你也想要处理异常 - end
基本上没有用于清理的目的,因为它只在整个管道中被调用已成功处理。这需要trap
,try
/ finally
和标志的混合组合:
function Out-UnixFile([string] $Path, [switch] $Append) {
<#
.SYNOPSIS
Sends output to a file encoded with UTF-8 without BOM with Unix line endings.
#>
begin {
$old_treatcontrolcasinput = [console]::TreatControlCAsInput
[console]::TreatControlCAsInput = $true
$encoding = new-object System.Text.UTF8Encoding($false)
$sw = new-object System.IO.StreamWriter($Path, $Append, $encoding)
$sw.NewLine = "`n"
$end = {
[console]::TreatControlCAsInput = $old_treatcontrolcasinput
$sw.Close()
}
}
process {
trap {
&$end
break
}
try {
if ($break) { break }
$sw.WriteLine($_)
} finally {
if ([console]::KeyAvailable) {
$key = [console]::ReadKey($true)
if (
$key.Modifiers -band [consolemodifiers]"control" -and
$key.key -eq "c"
) {
$break = $true
}
}
}
}
end {
&$end
}
}
详细,这是最短的&#34;正确&#34;解决方案,我可以想出来。它确实通过扭曲来确保Control-C状态正确恢复,我们从不尝试捕获异常(因为PowerShell在重新抛出它们方面很糟糕);如果我们不关心这些细节,解决方案可能会稍微简单一些。我甚至都不想尝试对性能做出声明。 : - )
如果有人对如何改善这一点有所了解,我全都耳朵。显然,检查Control-C可以考虑到函数,但除此之外,似乎很难使它更简单(或至少更具可读性)因为我们被迫使用begin
/ {{1 } / process
模具。
答案 1 :(得分:1)
可以在C#中编写它,可以实现IDisposable - 在ctrl
- c
的情况下确认由powershell调用。
如果有人在PowerShell中提出某种方法,我会将问题保持打开状态。
using System;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Text;
namespace MarcWi.PowerShell
{
[Cmdlet(VerbsData.Out, "UnixFile")]
public class OutUnixFileCommand : PSCmdlet, IDisposable
{
[Parameter(Mandatory = true, Position = 0)]
public string FileName { get; set; }
[Parameter(ValueFromPipeline = true)]
public PSObject InputObject { get; set; }
[Parameter]
public SwitchParameter Append { get; set; }
public OutUnixFileCommand()
{
InputObject = AutomationNull.Value;
}
public void Dispose()
{
if (sw != null)
{
sw.Close();
sw = null;
}
}
private StreamWriter sw;
protected override void BeginProcessing()
{
base.BeginProcessing();
var encoding = new UTF8Encoding(false);
sw = new StreamWriter(FileName, Append, encoding);
sw.NewLine = "\n";
}
protected override void ProcessRecord()
{
sw.WriteLine(InputObject);
}
protected override void EndProcessing()
{
base.EndProcessing();
Dispose();
}
}
}
答案 2 :(得分:1)
以下是&#34;使用&#34;的实现。对于PowerShell(来自Solutionizing .Net)。 using
是PowerShell中的保留字,因此是别名PSUsing
:
function Using-Object {
param (
[Parameter(Mandatory = $true)]
[Object]
$inputObject = $(throw "The parameter -inputObject is required."),
[Parameter(Mandatory = $true)]
[ScriptBlock]
$scriptBlock
)
if ($inputObject -is [string]) {
if (Test-Path $inputObject) {
[system.reflection.assembly]::LoadFrom($inputObject)
} elseif($null -ne (
new-object System.Reflection.AssemblyName($inputObject)
).GetPublicKeyToken()) {
[system.reflection.assembly]::Load($inputObject)
} else {
[system.reflection.assembly]::LoadWithPartialName($inputObject)
}
} elseif ($inputObject -is [System.IDisposable] -and $scriptBlock -ne $null) {
Try {
&$scriptBlock
} Finally {
if ($inputObject -ne $null) {
$inputObject.Dispose()
}
Get-Variable -scope script |
Where-Object {
[object]::ReferenceEquals($_.Value.PSBase, $inputObject.PSBase)
} |
Foreach-Object {
Remove-Variable $_.Name -scope script
}
}
} else {
$inputObject
}
}
New-Alias -Name PSUsing -Value Using-Object
使用示例:
psusing ($stream = new-object System.IO.StreamReader $PSHOME\types.ps1xml) {
foreach ($_ in 1..5) { $stream.ReadLine() }
}
显然,这只是围绕Jeroen的第一个答案的一些包装,但对于那些在这里找到自己的方式的人可能会有用。