gpt4 book ai didi

linq - Powershell 相当于 ".Single()"对于 C#/Java 程序员

转载 作者:行者123 更新时间:2023-12-01 00:13:35 25 4
gpt4 key购买 nike

我正在为我的 CI 编写一些脚本,并且我注意到我在断言我的过滤器的唯一性方面做得不好。例如,一个脚本假设

$availableZip = $(Get-ChildItem -Path .\ -Filter "*SomeName*.zip" -Recurse).FullName

将提供一个唯一的条目,但它可能不提供条目,也可能提供多个条目。

这当然可以通过一些 If-Else 检查在下游处理,但我想做的是优雅地插入 PowerShell 为我生成错误,例如
$availableZip = $(Get-ChildItem -Path .\ -Filter "*SomeName*.zip" -Recurse | Where -Single).FullName

这样 Where -Single会抛出某种 SetIsEmptyExceptionSetContainsMultipleElementsException ,所有 PowerShell 装备都专门指向这一行,甚至可能包括重复的成员。

Where-Object : value contains multiple elements where only one is allowed, available elements: firstDirectory\SomeSoftware.zip, Another-SomeSoftware.zip at C:\Users\geoff\Code\Project\MyScript.ps1:33 char:73
+ ...ChildItem -Path .\ -Filter "SomeSoftware.zip" -recurse | Where -Single).FullName
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], SingletonSetContainsMultipleElementsException
+ FullyQualifiedErrorId : TooManyElements,Microsoft.PowerShell.Commands.WhereObjectCommand



我有内置的方法吗?是否有一些我可以使用的 PowerShell 技巧,或者我应该使用一个带有私有(private)函数的小模块(如果是,那么最优雅的实现是什么?)

最佳答案

你总是可以像下面这样使用 Linq。我试图通过首先获取 zip 文件夹的名称来提高效率。

[string[]]$zips = @(Get-ChildItem -Path .\ -Filter "*SomeName*.zip" -Recurse -Name)

[string]$availableZipName = [System.Linq.Enumerable]::Single($zips)

$availableZip = Get-ChildItem -Path $availableZipName -Recurse

下面我把它放到一个函数中,方便使用。
function Get-AvailableZip (
[ValidateScript({ Test-Path $_ })]
[string]$Path,
[ValidateNotNullOrEmpty()]
[string]$Filter
)
{
[string[]]$zips = @(Get-ChildItem -Path $Path -Filter $Filter -Recurse -Name);

[string]$availableZipName

$availableZip = $null

try
{
$availableZipName = [System.Linq.Enumerable]::Single($zips)

$availableZip = Get-ChildItem -Path "$Path\$availableZipName" -Recurse
}
catch [System.InvalidOperationException]
{


if ($_.Exception.Message -eq "Sequence contains more than one element")
{
Write-Error -Message ([Environment]::NewLine + $_.Exception.Message + [Environment]::NewLine + "Files Found:" + [Environment]::NewLine + [string]::Join([Environment]::NewLine, $zips)) -Category LimitsExceeded -Exception ($_.Exception)
}
else
{
if ($_.Exception.Message -eq "Sequence contains no elements")
{
Write-Error -Message ([Environment]::NewLine + $_.Exception.Message) -Category ObjectNotFound -Exception ($_.Exception)
}
else
{
throw
}
}
}

return $availableZip;
}

用法:
Get-AvailableZip -Path ".\" -Filter "*SomeName*.zip"

关于linq - Powershell 相当于 ".Single()"对于 C#/Java 程序员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55639439/

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