概要

Process付きスクリプトブロックを再帰処理する例を示します。ここでは、ディレクトリ構造を再帰的に処理して、各ファイルの情報を取得するシナリオを考えます。

例: ディレクトリ内の全ファイルを再帰的に処理するスクリプト

このスクリプトは、指定されたディレクトリ内のすべてのファイルを再帰的に処理し、各ファイルのフルパスを出力します。

Step 1: 関数の定義

まず、再帰的にファイルを処理するための関数を定義します。

function Get-FileInformation {
    param (
        [string]$Path
    )
    # 指定されたパスのファイル情報を取得
    if (Test-Path $Path -PathType Container) {
        Get-ChildItem -Path $Path | ForEach-Object {
            # ディレクトリの場合、再帰的にこの関数を呼び出す
            Get-FileInformation -Path $_.FullName
        }
    } else {
        # ファイルの場合、ファイルのフルパスを出力
        $_.FullName
    }
}

Step 2: Process付きスクリプトブロックの定義

次に、再帰処理を行うためのProcess付きスクリプトブロックを定義します。

$scriptblock = {
    process {
        param ($item)
        Get-FileInformation -Path $item
    }
}

Step 3: パイプライン処理で再帰処理を実行

最後に、指定されたディレクトリ内のすべてのファイルとディレクトリをパイプラインで処理します。

# 開始ディレクトリのパス
$startPath = "C:\\\\example\\\\directory"

# 再帰処理の実行
Get-ChildItem -Path $startPath -Recurse -Directory | ForEach-Object -Process $scriptblock

全体のコード

上記のすべての部分を組み合わせると、再帰的にディレクトリ内のファイルを処理する完全なスクリプトが完成します。

function Get-FileInformation {
    param (
        [string]$Path
    )
    # 指定されたパスのファイル情報を取得
    if (Test-Path $Path -PathType Container) {
        Get-ChildItem -Path $Path | ForEach-Object {
            # ディレクトリの場合、再帰的にこの関数を呼び出す
            Get-FileInformation -Path $_.FullName
        }
    } else {
        # ファイルの場合、ファイルのフルパスを出力
        $_.FullName
    }
}

$scriptblock = {
    process {
        param ($item)
        Get-FileInformation -Path $item
    }
}

# 開始ディレクトリのパス
$startPath = "C:\\\\example\\\\directory"

# 再帰処理の実行
Get-ChildItem -Path $startPath -Recurse -Directory | ForEach-Object -Process $scriptblock

解説