> For the complete documentation index, see [llms.txt](https://docs.realmjoin.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.realmjoin.com/ja/dev-reference/report-functions/publish-rjrbfilestostoragecontainer.md).

# Publish-RjRbFilesToStorageContainer

Azure Automation runbook から Azure Storage コンテナーにローカル ファイルをアップロードし、期限付き SAS ダウンロード リンクを返します。

## 概要

`Publish-RjRbFilesToStorageContainer` RealmJoin のレポート用 runbook から Azure Blob Storage 経由でレポート ファイル（CSV、XLSX、ZIP、…）を配信するための標準ヘルパーです。1つ以上のローカル ファイルを対象コンテナーにアップロードし、各 blob について有効期限付きの SAS ダウンロード リンクを返します。レポートメール、Teams メッセージ、または runbook 出力に含めるのに適しています。

主な特徴:

* **なし `Az.Storage` 依存関係** — blob 操作は Azure Storage REST API に直接対して実行されます（コンテナーの作成、アップロード、SAS Token 生成）。これにより、以下の間でよく知られているアセンブリ競合が解消されます `Az.Storage` と `ExchangeOnlineManagement` これは混在した reporting runbook で顕在化します。
* **自動接続** — もし `Az` context が有効でない場合、関数は透過的に `Connect-RjRbAzAccount`を呼び出します。オプションの `-SubscriptionId` スイッチにより、いずれのストレージ操作より前に context を切り替えます。
* **コンテナーの自動作成** — 対象コンテナーがまだ存在しない場合はその場で作成されます。既存のコンテナー（HTTP 409）は成功として扱われます。
* **HttpClient ベースのアップロード** — 使用します `System.Net.Http.HttpClient` を直接使います。Azure Automation の `Invoke-RestMethod` インターセプターが必要なカスタムヘッダー（`x-ms-blob-type`）をバイナリ本文から取り除いてしまうためです。
* **読み取り専用の SAS リンク** — 返される各 URL は storage account key で署名され、単一の blob にスコープされ、HTTPS のみで、次の期間有効です `LinkExpiryDays` 日（既定 6 日）。

通常の runbook が使用する中心的なストレージ設定（リソース グループ、アカウント名、有効期限の日数、blob 名のプレフィックス）は RealmJoin のカスタマイズ JSON にあり、次の文書で説明されています。 [Runbook Report Settings — Storage Account Delivery](https://docs.realmjoin.com/ja/zi-dong-hua/runbooks/runbook-report-settings.md#storage-account-delivery)。この文書は、runbook から関数を呼び出す方法に焦点を当てています。

## 前提条件

### Azure Storage Account

既存の Azure Storage Account（汎用 v2 推奨）が必要です。対象コンテナーは事前に存在している必要はありません。初回使用時に自動的に作成されます。

### Azure RBAC on the Storage Account

Automation Account の managed identity（または runbook で使用する Service Principal）には、Storage Account に対して次の権限が必要です:

| アクション                                               | 対象:                                  |
| --------------------------------------------------- | ------------------------------------ |
| `Microsoft.Storage/storageAccounts/read`            | Storage Account の読み取り                |
| `Microsoft.Storage/storageAccounts/listKeys/action` | SharedKey 署名と SAS 生成に使用するアカウント キーの取得 |

組み込みロールを割り当ててください **Reader and Data Access** Storage Account に対して: これは両方をカバーする最小の組み込みロールです。コンテナー作成、アップロード、SAS 生成はアカウント キーで認可されるため、追加の Azure RBAC 権限は不要です。 **Storage Account Contributor** でも問題ありませんが、さらに Storage Account の管理と削除も許可されます。 **Storage Blob Data Contributor** 単独でも *は* 十分です。なぜなら、関数は AAD ベースの blob 操作を使わず、アカウント キーで要求に署名するためです。

関数はアカウント キーで認証するため、Storage Account では shared key access を許可する必要があります（`allowSharedKeyAccess` は無効にしては `false`）。このキーは Storage Account 内のすべてのデータへのアクセスを許可するため、レポート専用の Storage Account を推奨します。

### モジュール接続

この関数には `Az.Accounts` モジュールが runbook 環境で必要です（`Get-AzContext`, `Set-AzContext`, `Connect-AzAccount`, `Invoke-AzRestMethod`）。利用側の runbook で明示的に宣言してください:

```powershell
#Requires -Modules @{ModuleName = "RealmJoin.RunbookHelper"; ModuleVersion = "0.8.6" }
#Requires -Modules @{ModuleName = "Az.Accounts"; ModuleVersion = "5.3.4" }
```

もし `Az.Accounts` 実行時に利用できない場合、関数は明確なエラーメッセージとともに即座に失敗します — 事前に `Get-AzContext` を確認し、次をスローします *"Publish-RjRbFilesToStorageContainer requires the 'Az.Accounts' module. Add #Requires -Modules @{ModuleName = 'Az.Accounts'; ModuleVersion = '5.3.4'} to the calling runbook."* Azure 呼び出しの前に行われます。

> **なぜ `Az.Accounts` 〜として宣言されていないのか `RequiredModules` エントリとして `RealmJoin.RunbookHelper.psd1`?**
>
> `Az.Accounts` 意図的に次の下にのみ記載されています `ExternalModuleDependencies` （情報提供用）および *は* の下で。 `RequiredModules` （で強制される `Import-Module` 時点）:
>
> * **使った分だけ支払うためです。** 多くの runbook は Graph ベースのヘルパー（例: `Send-RjRbReportEmail` なしでは `-UseNativeGraphRequest`、または `Invoke-RjRbRestMethodGraph`）だけを使用し、Az.\* cmdlet には一切触れません。Promoting `Az.Accounts` を `RequiredModules` すると、コードパスのどこにも必要がなくても、利用側のすべての runbook にそのモジュールを同梱させることになり、Azure Automation のコールド スタート時間が目に見えて増加します。
> * **バージョン競合を避けるためです。** 厳密な `RequiredModules` 制約はインポート時に自動解決を引き起こし、特定の `Az.Accounts` バージョンを引き込んで、runbook 自体が固定しているものと衝突する可能性があります（Az.\* のサブモジュールは悪名高いほどバージョンに敏感です）。runbook に独自の `#Requires -Modules` を宣言させることで、バージョン選択を呼び出し元に委ねられます。
> * **runbook ごとの裁量です。** Azure Automation では、モジュール要件を宣言する標準的な場所は、runbook レベルの `#Requires`であり、ヘルパー モジュール レベルではありません。ヘルパー モジュールは依存関係を情報として（マニフェスト内の ExternalModuleDependencies により）および上記の実行時チェックにより示すため、設定ミスはバージョン競合を静かに隠すのではなく、実行可能なメッセージとともに明確に失敗します。 `ExternalModuleDependencies` 必要であり、前述のアセンブリ競合を避けるため、同じ runbook で一緒にインポートすべきではありません。

`Az.Storage` ある **は** 最低限の呼び出しには、ローカル ファイル パス、コンテナー名、リソース グループ、そして storage account 名が必要です:

## クイック スタート

The minimum viable call requires the local file path(s), the container name, the resource group and the storage account name:

```powershell
$csvPath = Join-Path $env:TEMP 'devices.csv'
$exportData | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8

$results = Publish-RjRbFilesToStorageContainer `
    -FilePaths          $csvPath `
    -ContainerName      'reports' `
    -ResourceGroupName  'rg-reports' `
    -StorageAccountName 'stcontosoreports'

$results | Format-Table BlobName, EndTime, SASLink
```

これにより `devices.csv` 対象の `reports` コンテナーに `stcontosoreports` アップロードし、blob 名、SAS の有効期限タイムスタンプ、そして既定の 6 日間有効な、すぐ共有できるダウンロード URL を含む 1 つのオブジェクトを返します。

## パラメーター

### 必須

| パラメーター               | 型          | 説明                                                                                                                                        |
| -------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `FilePaths`          | `string[]` | アップロードするローカル ファイル パスを 1 つ以上指定します。各パスは既存のファイルを指していなければなりません（`Test-Path -PathType Leaf`）；いずれかのエントリが欠けている場合、関数は事前に例外をスローします。                 |
| `ContainerName`      | `string`   | 対象の blob コンテナー。存在しない場合は自動的に作成されます。Azure のコンテナー命名規則（小文字、3〜63 文字、英数字＋ハイフン）に従う必要があります。コンテナー名は *runbook ごとの* 決定事項であり、中央設定ではなく runbook で設定します。 |
| `ResourceGroupName`  | `string`   | Storage Account を含むリソース グループ。通常は中央設定の `RJReport.StorageAccount.ResourceGroup`.                                                            |
| `StorageAccountName` | `string`   | Azure Storage Account の名前。通常は中央設定の `RJReport.StorageAccount.StorageAccountName`.                                                          |

### 任意

| パラメーター              | 型        | 既定値         | 説明                                                                                                                                       |
| ------------------- | -------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `SubscriptionId`    | `string` | 現在の context | Storage Account をホストしている Azure サブスクリプション。指定した場合、 `Set-AzContext -Subscription` は、いずれのストレージ操作の前にも呼び出されます。省略すると現在の `Az` context を使用します。    |
| `LinkExpiryDays`    | `int`    | `6`         | SAS リンクの有効期間（日）。次の範囲に検証されます: `[1, 3650]`。同一呼び出し内のすべての blob に同じ有効期限タイムスタンプが適用されます。通常は中央設定の `RJReport.StorageAccount.LinkExpiryDays`.      |
| `AddBlobNamePrefix` | `bool`   | `$false`    | 次の場合、 `$true`により、blob 名の先頭に次が付加されます: `yyyyMMdd-HHmmss-` （次の時刻のタイムスタンプ `Get-Date` をアップロード時に使用して、繰り返し実行時の上書きを防ぎます。元のファイル名はサフィックスとして保持されます。 |

> **注:** これらのパラメーターと、推奨既定値を含む中央の RealmJoin カスタマイズ JSON との対応は、次に文書化されています: [Runbook Report Settings — Storage Account Delivery](https://docs.realmjoin.com/ja/zi-dong-hua/runbooks/runbook-report-settings.md#storage-account-delivery).

## 使用例

### 推奨 runbook パターン

これはレポート用 runbook で使用される標準パターンです。ストレージ設定は中央の RealmJoin カスタマイズから次を介して取得されます: `Use-RJInterface -Type Setting`、コンテナーは runbook ごとにハードコードされ、設定が欠けている場合は実行可能なメッセージとともに runbook が中断します:

```powershell
#Requires -Modules @{ModuleName = "RealmJoin.RunbookHelper"; ModuleVersion = "0.8.6" }
#Requires -Modules @{ModuleName = "Az.Accounts"; ModuleVersion = "5.3.4" }

param(
    [string] $ContainerName = "my-runbook-output",

    [ValidateScript( { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process; Use-RJInterface -Type Setting -Attribute "RJReport.StorageAccount.ResourceGroup" } )]
    [string] $ResourceGroupName,

    [ValidateScript( { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process; Use-RJInterface -Type Setting -Attribute "RJReport.StorageAccount.StorageAccountName" } )]
    [string] $StorageAccountName,

    [ValidateScript( { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process; Use-RJInterface -Type Setting -Attribute "RJReport.StorageAccount.LinkExpiryDays" } )]
    [ValidateRange(1, 3650)]
    [int] $LinkExpiryDays = 6
)

Connect-RjRbAzAccount

if ((-not $ResourceGroupName) -or (-not $StorageAccountName)) {
    "## Storage Account へエクスポートするには、RJ Runbooks Customization を使用してください"
    "## （ https://portal.realmjoin.com/settings/runbooks-customizations ）で次を構成してください:"
    "##   - RJReport.StorageAccount.ResourceGroup"
    "##   - RJReport.StorageAccount.StorageAccountName"
    throw "Storage Account 設定がありません。"
}

# … エクスポート ファイルを作成 …
$exportPath = "myReport.csv"

$uploadResults = Publish-RjRbFilesToStorageContainer `
    -FilePaths          @($exportPath) `
    -ContainerName      $ContainerName `
    -ResourceGroupName  $ResourceGroupName `
    -StorageAccountName $StorageAccountName `
    -LinkExpiryDays     $LinkExpiryDays `
    -AddBlobNamePrefix  $true

$uploadResult = $uploadResults[0]
"## エクスポートを作成しました。"
"## リンクの有効期限: $($uploadResult.EndTime)"
$uploadResult.SASLink | Out-String
```

このパターンを採用する際に守るとよい慣例がいくつかあります:

* 3 つの中心設定（`ResourceGroup`, `StorageAccountName`, `LinkExpiryDays`）は runbook パラメーターとして公開され、次を介して紐付けられます: `Use-RJInterface -Type Setting`、ただし通常は *非表示* runbook カスタマイズ内で（`"Hide": true`）ユーザーには見えないようにします。
* コンテナー名は runbook ごとにハードコードされ（多くの場合、 `param` の既定値経由）、ライフサイクル ポリシーとアクセス制御をエクスポート種類ごとに調整できるようにします — これは意図的に *は* 中央設定ではありません。
* `AddBlobNamePrefix $true` は、毎回固定のファイル名を生成する定期エクスポートに対する安全な既定値です。
* 関数は runbook のメイン `try { … } catch { throw $_ } finally { Disconnect-AzAccount … }` ブロック内で呼び出されるため、部分的な失敗は Automation ジョブに伝播し、成功時であっても Az context は解放されます。

### 1 回の呼び出しで複数ファイル

`FilePaths` 配列を受け入れます。各ファイルは順番にアップロードされ、アップロードされた各 blob に対して結果オブジェクトが返されます。

```powershell
$results = Publish-RjRbFilesToStorageContainer `
    -FilePaths          @($csvPath, $xlsxPath) `
    -ContainerName      'reports' `
    -ResourceGroupName  $ResourceGroupName `
    -StorageAccountName $StorageAccountName

foreach ($r in $results) {
    "アップロード済み $($r.BlobName) — $($r.EndTime) までダウンロード可能: $($r.SASLink)"
}
```

### カスタム リンク有効期間と明示的なサブスクリプション

```powershell
Publish-RjRbFilesToStorageContainer `
    -FilePaths          $exportPaths `
    -ContainerName      'quarterly-reports' `
    -ResourceGroupName  $ResourceGroupName `
    -StorageAccountName $StorageAccountName `
    -SubscriptionId     '00000000-0000-0000-0000-000000000000' `
    -LinkExpiryDays     30
```

runbook が複数のサブスクリプションにまたがる場合や、下流の受信者に既定の 6 日より長い期間が必要な場合に有用です。

### 組み合わせると `Send-RjRbReportEmail`

よくあるパターンは、大きなデータを blob storage にアップロードし、SAS リンクをレポートメールに埋め込んで、メールのサイズを 4 MB の Graph `sendMail` 制限より十分小さく保つことです:

```powershell
$uploaded = Publish-RjRbFilesToStorageContainer `
    -FilePaths          $csvPath `
    -ContainerName      'reports' `
    -ResourceGroupName  $ResourceGroupName `
    -StorageAccountName $StorageAccountName `
    -AddBlobNamePrefix  $true

$linkLine = "[Download {0}]({1}) (valid until {2:yyyy-MM-dd HH:mm} UTC)" -f `
    $uploaded[0].BlobName, $uploaded[0].SASLink, $uploaded[0].EndTime.ToUniversalTime()

$reportMd = @"
# デバイス一覧

完全なデバイス一覧はダウンロードできます:

$linkLine
"@

Send-RjRbReportEmail `
    -EmailFrom       $emailFrom `
    -EmailTo         'it-reports@contoso.com' `
    -Subject         "Device Inventory — $(Get-Date -Format 'yyyy-MM-dd')" `
    -MarkdownContent $reportMd
```

参照 [Send-RjRbReportEmail](https://docs.realmjoin.com/ja/dev-reference/report-functions/send-rjrbreportemail.md) このパターンのメール側に対して使用します。

## 動作とエラー処理

### 事前のファイル検証

Azure 呼び出しの前に、関数は次を順に確認します: `FilePaths` そして次をスローします `File '<path>' が見つかりませんでした。` 最初に見つかった欠落エントリに対してです。これにより、呼び出し元がタイプミスを渡した場合の部分的なアップロードを防げます。

### Azure context の解決

`Get-AzContext` が最初にチェックされます。context が存在しないか、context に `Account` がない場合（例: 新しい runbook 実行）、関数は `Connect-RjRbAzAccount` を呼び出して managed identity を認証します。もし `-SubscriptionId` が指定されている場合、 `Set-AzContext -Subscription` が次に呼び出されます。

### コンテナーの作成

コンテナーは次の `PUT …?restype=container` リクエストで作成されます:

* **HTTP 201** — コンテナーが作成されました。
* **HTTP 409** — コンテナーは既に存在します。成功として扱われます。
* **その他のステータス** — 関数は次をスローします `コンテナーの作成に失敗しました (<status>): <body>`。HTTP 403 で `KeyBasedAuthenticationNotPermitted` が返る場合、storage account で shared key access が無効です。

### アップロード失敗

各ファイルは次を介してアップロードされます `HttpClient.SendAsync`。成功以外のステータスの場合、呼び出しは次で終了します `Blob アップロードに失敗しました (<status>): <body>`。Azure Storage が返した生のエラーも含まれます。同じ呼び出しですでにアップロード済みの前のファイルは storage account に残ります。部分的なアップロードが許容できない場合、呼び出し元は try/catch で呼び出しを包み、クリーンアップを実行したほうがよいでしょう。

### キー取得失敗

`Invoke-AzRestMethod` ARM を呼び出すために使用されます `listKeys` エンドポイントです。レスポンス ステータスが 200 以外の場合、関数は次をスローします `リソース グループ '<rg>' 内の '<account>' の storage account キーの取得に失敗しました。ステータス: <status>`。最も一般的な原因は次のとおりです:

* 不足 `Microsoft.Storage/storageAccounts/listKeys/action` managed identity に対して。
* サブスクリプション context が正しくない（次と組み合わせて確認してください `-SubscriptionId`).
* の টাইपो `StorageAccountName` または `ResourceGroupName`.
* 中央設定が `RJReport.StorageAccount.ResourceGroup` / `RJReport.StorageAccount.StorageAccountName` 未設定 — 次を参照してください [Runbook レポート設定](https://docs.realmjoin.com/ja/zi-dong-hua/runbooks/runbook-report-settings.md#storage-account-delivery).

### SAS Token の特性

生成される token は次を使用します:

* `sv=2023-11-03` （署名付きバージョン）
* `sr=b` （blob スコープ）
* `sp=r` （読み取り専用）
* `spr=https` （HTTPS のみ）
* `st` は 5 分前に設定され（時計のずれ許容）、 `se` を `LinkExpiryDays` は呼び出し時刻からのものです。

token は storage account key で署名されます。 **リンクを持つ人は、有効期限まで blob をダウンロードできます** — 返された SAS URL は秘密情報として扱ってください。

## 出力

成功した各アップロードは次を生成します `PSCustomObject` 。次のプロパティを持ちます:

| プロパティ      | 型          | 説明                                                                            |
| ---------- | ---------- | ----------------------------------------------------------------------------- |
| `BlobName` | `string`   | コンテナー内の最終的な blob 名。必要に応じてタイムスタンプ プレフィックスを含みます `AddBlobNamePrefix` ある `$true`. |
| `EndTime`  | `datetime` | ローカル時刻の SAS 有効期限（URL 内には UTC としてもエンコードされます）。                                  |
| `SASLink`  | `string`   | 埋め込み SAS token を含む完全修飾 HTTPS ダウンロード URL。                                      |

結果は次と同じ順序で返されます `FilePaths`。単一ファイルをアップロードする場合でも戻り値は配列です。インデックス指定（`$results[0]`）するか、次で反復してください `foreach` 。スカラーとして扱わないでください。

## 関連項目

* [Runbook Report Settings — Storage Account Delivery](https://docs.realmjoin.com/ja/zi-dong-hua/runbooks/runbook-report-settings.md#storage-account-delivery) — レポート用 runbook で使用される storage account、リンク有効期限、blob 名プレフィックスの中央設定。
* [Send-RjRbReportEmail](https://docs.realmjoin.com/ja/dev-reference/report-functions/send-rjrbreportemail.md) — メール経由でレポートを配信するための補助ヘルパー。メール本文を小さく保つため、通常はこの関数と組み合わせて使用します。
* Microsoft Docs: [Shared Key で認可する](https://learn.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key) — このヘルパーで使用する署名方式。
* Microsoft Docs: [サービス SAS を作成する](https://learn.microsoft.com/en-us/rest/api/storageservices/create-service-sas) — 返される SAS token 形式 `SASLink`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.realmjoin.com/ja/dev-reference/report-functions/publish-rjrbfilestostoragecontainer.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
