如何从管道传递 2 个值?

How to pass 2 values from pipeline?

我正在尝试将包含多个 sheet 的 excel 文件转换为 csv 文件。

$currentDir = $PSScriptRoot

$csvPATH = Join-Path -Path $currentDir -ChildPath CSV_Files
New-Item -ItemType Directory -Force -Path $csvPATH | out-null

function Convert-ExcelSheetsToCsv {
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [ValidateNotNullOrEmpty()]
        [Alias('FullName')]
        [string]$Path,
        [Parameter(Mandatory = $false, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [bool]$AppendFileName
    )
    Begin {
        $excel = New-Object -ComObject Excel.Application -Property @{
            Visible       = $false
            DisplayAlerts = $false
        }
    }
    Process {
        $root = Split-Path -Path $Path
        $filename = [System.IO.Path]::GetFileNameWithoutExtension($Path)
        $workbook = $excel.Workbooks.Open($Path)
        foreach ($worksheet in $workbook.Worksheets) {
            if ($AppendFileName) {
                $name = Join-Path -Path $csvPATH <# $root #> -ChildPath "${filename}_$($worksheet.Name).csv"
            }
            else {
                $name = Join-Path -Path $csvPATH <# $root #> -ChildPath "$($worksheet.Name).csv"
            }

            try {
                $worksheet.SaveAs($name, 6) #6 to ignore formatting and covert to pure text, otherwise, file could end up containing rubbish
            } catch {
                Write-Error -Message "Failed to save csv! Path: '$name'. $PSItem"
            }
        }
    }
    End {
        $excel.Quit()
        $null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel)
    }
}

Get-ChildItem -Path $currentDir -Filter *.xlsx 0 | Convert-ExcelSheetsToCsv

这给我以下错误:

Get-ChildItem : A positional parameter cannot be found that accepts argument '0'.

或者如果我像这样在后面加上 0(表示错误):Get-ChildItem -Path $currentDir -Filter *.xlsx | Convert-ExcelSheetsToCsv 0

我收到这个错误:

Convert-ExcelSheetsToCsv : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the
input and its properties do not match any of the parameters that take pipeline input.

基本上,我试图有一个选项,如果 $AppendFileName 为假,则生成的 csv 文件将仅由 sheet 名称命名,这是 else 语句

$name = Join-Path -Path $csvPATH <# $root #> -ChildPath "$($worksheet.Name).csv"

需要指定位置。

[Parameter(Mandatory, ValueFromPipelineByPropertyName,Position=1)] [Parameter(Mandatory=$false,ValueFromPipeline,ValueFromPipelineByPropertyName,Position=0)]

然后:

Get-ChildItem -Path $currentDir -Filter *.xlsx | Convert-ExcelSheetsToCsv 0