Тот же код PowerShell работает как отдельный файл, а не как функция - PullRequest
0 голосов
/ 27 сентября 2019

Я написал некоторый код PowerShell, который выполняется, как и ожидалось, когда он изолирован как отдельный файл .ps1.

$unredacted = @()
$redacted = @()

$files = Get-ChildItem -Path \test\1234 -Filter *.tif | Sort-Object -Property Name

$files -match '(.*)_redacted' | ForEach-Object {
    $base = $_.BaseName
    $unredacted += ($base.substring(0, $base.Length - 9) + $_.Extension)
    $redacted += $_.Name
}

$i = 0
$redacted_filesets = $unredacted | ForEach-Object {
    $unredactedCurrent = $_
    $redactedCurrent = $redacted[$i]
    $properties = @{
        Unredacted = $unredactedCurrent
        Redacted   = $redactedCurrent
    }
    New-Object -TypeName PSObject -Property $properties
    $i++
}

Return $redacted_filesets

Однако, когда я помещаю этот код в файл библиотеки функций и задаю путь параметромтак что я могу позвонить из других мест, он больше ничего не возвращает.Когда я делал этот же процесс в прошлом, я смог получить ожидаемый доход.

function Find-Redacted-Filesets {
    <#
        .SYNOPSIS
        Find pairs of unredacted and redacted files of the same item. 
        .DESCRIPTION
        Find all the tif files in the path and sort them by name, identify the redacted files and add filenames for redacted and unredacted files to arrays. Use the arrays to create a PSObject with all the redacted filesets.
        .PARAMETER path
        The path to the directory holding files to scan for redacted filesets.
        .EXAMPLE
        Find-Redacted-Filesets -path \test\1234
        .INPUTS
        System.String
        .OUTPUTS
        System.Object
    #>
    [cmdletbinding()]
    Param(
        [Parameter()]
        [string]
        $path
    )

    $unredacted = @()
    $redacted = @()

    $files = Get-ChildItem -Path $path -Filter *.tif -Recurse | Sort-Object -Property Name

    $files -match '(.*)_redacted' | ForEach-Object {
        $base = $_.BaseName
        $unredacted += ($base.substring(0, $base.Length - 9) + $_.Extension)
        $redacted += $_.Name
    }

    $i = 0
    $redacted_filesets = $unredacted | ForEach-Object {
        $unredactedCurrent = $_
        $redactedCurrent = $redacted[$i]
        $properties = @{
            Unredacted = $unredactedCurrent
            Redacted   = $redactedCurrent
        }
        New-Object -TypeName PSObject -Property $properties
        $i++
    }
    Return $redacted_filesets
}

И вызвать его из другого скрипта .ps1: . \util\lib.ps1 Find-Redacted-Filesets -path \test\1234.

Я не могу понять, в чем здесь разница или почему я не получаю возвращенный объект, когда предоставляю тот же путь к функции.Чего мне не хватает?

1 Ответ

0 голосов
/ 27 сентября 2019

@ x0n был ответ в комментарии выше.. \util\lib.ps1 Find-Redacted-Filesets -path \test\1234 пришлось разбить на две строки.

. \util\lib.ps1
Find-Redacted-Filesets -path \test\1234
...