01デスクトップフローの[Run Python script]で台帳を集計する要確認

Power Automate for desktop の[Run Python script]で選べる版は、文書では Python 2.7 と Python 3.4(既定は 2.7)。print の出力が変数 PythonScriptOutput に入るので、集計結果を キー=値 の行で出してフローで使う。

考え方と手順
  1. [Python version]を Python 3.4 にする(既定は Python 2.7)。f 文字列など新しい構文は使わず、str.format で書く
  2. フローの変数は %LedgerPath% のように % で囲んでスクリプトに書く。実行時に値へ置き換わる
  3. フローの外で試すときは置き換えが起きないので、パスが無ければ見本のファイルを読む分岐を入れておく
  4. 結果は total=件数、open=件数 のような行で print し、フロー側で PythonScriptOutput を行と = で分ける
  5. 失敗の内容は ScriptError に入る。空でなければフローを止めて担当者に知らせる
Python手元で動く
# Run Python script (Power Automate for desktop). Set "Python version" to Python 3.4.
# Keep to old syntax: no f-strings; use str.format.
import csv
import io
import os
from collections import Counter

ledger_path = r"%LedgerPath%"  # replaced by the flow variable at run time
if not os.path.exists(ledger_path):
    ledger_path = "samples/ledger.csv"  # local test outside the flow

with io.open(ledger_path, encoding="utf-8-sig", newline="") as f:
    rows = list(csv.DictReader(f))

status = Counter(r["状態"] for r in rows)
open_rows = [r for r in rows if r["状態"] != "完了"]
print("total={0}".format(len(rows)))
print("open={0}".format(len(open_rows)))
for name, n in sorted(status.items()):
    print("status.{0}={1}".format(name, n))
実行結果(2026-09-12)
total=40
open=26
status.受付=5
status.完了=14
status.差戻し=11
status.確認中=10
Copilot に書かせる指示の例

Power Automate for desktop の[Run Python script](Python 3.4)で動く Python を書いて。フロー変数 %LedgerPath% の CSV(UTF-8、BOM 付き)を読み、状態ごとの件数と未完了の件数を key=value の行で print する。f 文字列は使わず、標準ライブラリだけで書くこと。

注意

文書は選べる版を示すが、どの実装で動くか、標準ライブラリ以外のパッケージが使えるかは書いていない。外部のモジュールは[Module folder paths]で場所を示す。% は変数の記法に使われるので、文字列の書式には % を使わず format を使う。このコードは venv の Python 3.12 で試しただけで、PAD の中では動かしていない。

利用条件
Power Automate for desktop(Windows)。無料ライセンスでも、デスクトップフローの作成とローカルでの有人実行ができると文書にある。
試験
手元で実行して確認(2026-09-12、Python 3.12.10 (venv) / Windows 11)
出典
Microsoft Learn「Scripting actions reference」
Microsoft Learn「Types of Power Automate licenses」
確認日
2026-09-12(第 1 版)
出典の該当箇所
To return values from Run Python script actions, use the print function.
Python 2.7, Python 3.4
To use Power Automate variables in scripting actions, use the percentage notation (%) and handle the variables the same way as hardcoded values.
as well as authoring and running desktop flows locally (attended)

02クラウドフローから呼ぶ HTTP トリガーの関数を Python で書く確認済

Python v2 モデルの @app.route で HTTP トリガーの関数を作り、フローから受けた JSON の行を集計して JSON で返す。承認レベルを function にすると、呼び出しに関数キーが要る。

考え方と手順
  1. func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION) で作る。承認レベルを明示しないときも function になる
  2. @app.route(route="summarize", methods=["POST"]) で受け、req.get_json() の rows を集計する
  3. 集計は summarize_rows() に分け、HttpRequest を組み立てる試験で確かめる
  4. JSON でない本文には 400 を返し、フロー側で失敗として扱えるようにする
  5. フローの HTTP アクションからは x-functions-key ヘッダーでキーを渡す(次の項)
Pythonサービスとして動かす
"""HTTP-triggered function: take ledger rows as JSON and return counts."""
import json
from collections import Counter

import azure.functions as func

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)


def summarize_rows(rows):
    status = Counter(r.get("状態", "") for r in rows)
    open_by_owner = Counter(r.get("担当者", "") for r in rows if r.get("状態") != "完了")
    return {"total": len(rows), "status": dict(status), "open_by_owner": dict(open_by_owner)}


@app.route(route="summarize", methods=["POST"])
def summarize(req: func.HttpRequest) -> func.HttpResponse:
    try:
        rows = req.get_json().get("rows", [])
    except ValueError:
        return func.HttpResponse("JSON body with 'rows' is required", status_code=400)
    body = json.dumps(summarize_rows(rows), ensure_ascii=False)
    return func.HttpResponse(body, mimetype="application/json")
実行結果(2026-09-12)
{"total": 40, "status": {"完了": 14, "受付": 5, "差戻し": 11, "確認中": 10}, "open_by_owner": {"担当A": 10, "担当B": 7, "担当C": 3, "担当D": 6}}
bad request: 400
Copilot に書かせる指示の例

Azure Functions の Python v2 モデルで、POST の JSON {"rows": [...]} を受けて、状態ごとの件数と担当者ごとの未完了件数を JSON で返す HTTP トリガーの関数を書いて。承認レベルは FUNCTION、集計は別の関数にし、JSON でなければ 400 を返すこと。

注意

関数キーは URL のクエリ(code)でも渡せるが、URL は共有や記録に残りやすいのでヘッダーを使う。フローからの同期の呼び出しには時間の上限があるので、重い処理は分ける。受け取る行に個人名などが含まれるときは、関数のログに本文を出さない。

利用条件
Azure Functions(Python の v2 プログラミングモデル)。azure-functions 1.25.0 で定義と集計を試験した。
必要なもの
azure-functions 1.25.0
試験
定義を読み込んで確認(サービスとしては起動していない)・集計・判定の部分を見本データで実行して確認(2026-09-12、Python 3.12.10 (venv) / Windows 11、azure-functions 1.25.0)
出典
Microsoft Learn「Azure Functions HTTP trigger」
確認日
2026-09-12(第 1 版)
出典の該当箇所
When a level isn't explicitly set, authorization defaults to the function level.
It can also be included in an x-functions-key HTTP header.

03フローの HTTP アクションで関数を呼ぶ: キーの渡し方と待ち時間要確認

クラウドフローの HTTP アクションで関数の URL に POST し、キーは x-functions-key ヘッダーで渡す。フローからの同期の要求は120秒で打ち切られるので、長い処理は非同期のポーリングか Until ループに分ける。

考え方と手順
  1. HTTP アクションの[Method]を POST、[URI]を https://<APP_NAME>.azurewebsites.net/api/summarize にする
  2. キーは code= のクエリか x-functions-key ヘッダーで渡せる。ここではヘッダーを使い、URL にキーを含めない
  3. [Body]に rows を JSON で渡し、返った JSON を後続のアクションで使う
  4. 同期の要求は120秒で打ち切られる。長い処理は非同期のポーリングか Until ループにする
  5. HTTP アクションも、1日のアクション数の上限に数えられる
HTTP
POST /api/summarize HTTP/1.1
Host: <APP_NAME>.azurewebsites.net
Content-Type: application/json
x-functions-key: <FUNCTION_KEY>

{"rows": [{"依頼ID": "R-2026-002", "状態": "受付", "担当者": "担当A"},
          {"依頼ID": "R-2026-004", "状態": "完了", "担当者": "担当A"}]}
注意

キーはフローの本文に直接打ち込まず、組織で決めた安全な保管場所から渡す。HTTP アクションのライセンス上の扱い(標準かプレミアムか)は、保存した公式ページでは確かめられなかったので、導入前に管理者に確認する。

利用条件
Power Automate のクラウドフロー。タイムアウトの値は Power Automate の制限のページによる。
試験
実行の対象外(設定・HTTP・数式)(2026-09-12)
出典
Microsoft Learn「Azure Functions HTTP trigger」
Microsoft Learn「Limits of automated, scheduled, and instant flows」
Microsoft Learn「Power Automate licensing FAQ」
確認日
2026-09-12(第 1 版)
出典の該当箇所
It can also be included in an x-functions-key HTTP header.
For longer-running operations, use an asynchronous polling pattern or an "Until" loop.
count toward your daily action limit

04[When an HTTP request is received]のフローを Python から起動する確認済

HTTP 要求で起動するフローの URL を環境変数に置き、Python の requests で JSON を POST する。既定は DRY_RUN で、送らずに内容だけを表示する。トリガーをテナント内の利用者に限る設定では、Bearer トークンを付ける。

考え方と手順
  1. トリガーの認証は3種類ある: Any user in my tenant(新しいフローの既定)、Specific users in my tenant、Anyone(旧来の設定で、URL を知る人は誰でも起動できる)
  2. フローの URL は sig= の署名を含むので、コードに書かず環境変数 FLOW_URL から読む
  3. テナント内に限る設定では、aud などの要求を満たすトークンを Authorization ヘッダーに付ける。aud の値は末尾の / まで一致させる
  4. DRY_RUN=0 のときだけ送り、応答の状態コードを表示する
  5. URL が漏れたら SAS キーを再生成する。再生成すると sig= の値が変わるので、それで成功を確かめる
Python手元で動く
"""Send JSON to a flow that starts with 'When an HTTP request is received' (DRY_RUN by default)."""
import json
import os

import requests

DRY_RUN = os.environ.get("DRY_RUN", "1") != "0"
FLOW_URL = os.environ.get("FLOW_URL", "")  # carries a SAS signature: keep it out of code and logs
BEARER = os.environ.get("FLOW_BEARER_TOKEN", "")  # needed when the trigger allows tenant users only


def build_request(rows):
    headers = {"Content-Type": "application/json"}
    if BEARER:
        headers["Authorization"] = "Bearer " + BEARER
    return headers, {"source": "python", "rows": rows}


def main():
    rows = [{"依頼ID": "R-2026-041", "文書名": "文書41(架空)", "状態": "受付"}]
    headers, body = build_request(rows)
    if DRY_RUN or not FLOW_URL:
        print("DRY_RUN: would POST", len(rows), "row(s); bearer token:", "Authorization" in headers)
        print(json.dumps(body, ensure_ascii=False))
        return
    r = requests.post(FLOW_URL, headers=headers, json=body, timeout=30)
    print("status:", r.status_code)


if __name__ == "__main__":
    main()
実行結果(2026-09-12)
DRY_RUN: would POST 1 row(s); bearer token: False
{"source": "python", "rows": [{"依頼ID": "R-2026-041", "文書名": "文書41(架空)", "状態": "受付"}]}
Copilot に書かせる指示の例

requests で、環境変数 FLOW_URL の Power Automate フロー(When an HTTP request is received)に JSON を POST する Python を書いて。既定は DRY_RUN で送らずに内容だけを表示し、環境変数 FLOW_BEARER_TOKEN があれば Authorization ヘッダーに付けること。URL はログに出さないこと。

注意

Anyone の設定は URL だけで起動できるので避ける。OAuth 認証の設定は、地域によってまだ使えないことがあると文書にある。トークンの取り方はこの項では扱わない(security ページ)。受信の要求にも時間の上限があるので、フロー側では早めに応答を返す。

利用条件
Power Automate のクラウドフロー。トリガーの認証の設定は順次提供中と記載(2026-09-12 に確認)。
必要なもの
requests 2.34.2
試験
手元で実行して確認(2026-09-12、Python 3.12.10 (venv) / Windows 11、requests 2.34.2)
出典
Microsoft Learn「Add OAuth authentication for HTTP request triggers」
Microsoft Learn「Regenerate the SAS key used in HTTP trigger flows」
確認日
2026-09-12(第 1 版)
出典の該当箇所
Anyone can trigger this workflow if they have access to the URL and the associated JSON schema.
Ensures that any user in the same tenant as the maker can trigger this workflow. This setting is the default for any new flows.
Audience values must be an exact match, including trailing slashes.
Once the key is regenerated, this value changes and serves as a confirmation that the execution of the following steps was successful.

05Office Scripts と Python の分担: ブックの中は Office Scripts、外との通信は関数確認済

Office Scripts は Power Automate の[Run script]から呼べ、ブックの表を読み書きして値をフローに返せる。ただしフローから動かすと外部 API の呼び出しは失敗する。外との通信や重い集計は Python の関数に回し、フローでつなぐ。

考え方と手順
  1. ブックの中の操作(表の読み書き、列の集計)は Office Scripts の main(workbook, ...) に書き、戻り値でフローに返す
  2. フローからは Excel Online (Business) コネクタの[Run script]か[Run script from SharePoint library]で呼ぶ
  3. 外部サービスとの送受信はスクリプトに書かず、フローの HTTP アクションで Python の関数を呼ぶ
  4. [Run script]は利用者ごとに1日1,600回、同期の処理は120秒、引数は30,000,000 バイトまでという上限がある
  5. Office Scripts が触れるのはブックだけで、ブックを開いている PC のファイルには触れない。PC のファイルを扱う処理は Python 側に置く
Text
// Office Script (TypeScript), called from Power Automate "Run script".
// Counts rows whose status is not "完了" and returns the number to the flow.
function main(workbook: ExcelScript.Workbook, statusColumn: string): number {
  const table = workbook.getTable("RequestLedger");
  const values = table.getColumnByName(statusColumn).getRangeBetweenHeaderAndTotal().getValues();
  let open = 0;
  values.forEach((row) => {
    if (row[0] !== "完了") {
      open += 1;
    }
  });
  return open;
}
Copilot に書かせる指示の例

Excel の表 RequestLedger の[状態]列を数え、完了でない行の件数を返す Office Scripts の main 関数を TypeScript で書いて。Power Automate の[Run script]から呼び、列名は引数で受け取ること。外部への fetch は使わないこと。

注意

Office Scripts を Power Automate で使うには Microsoft 365 の業務用ライセンスが要る。Office 365 Enterprise E1 と Office 365 F3 はフローからは使えるが、Excel の中の Power Automate 連携は無い。ISO strict 形式のブックは[Run script]で使えない。管理者は Excel Online コネクタや Office Scripts を止められる。

利用条件
Excel on the web、Excel for Windows(Version 2210 以降)、Excel for Mac と OneDrive for Business。対象の Microsoft 365 のライセンス。
試験
実行の対象外(設定・HTTP・数式)(2026-09-12)
出典
Microsoft Learn「Platform limits and requirements with Office Scripts」
Microsoft Learn「Run Office Scripts with Power Automate」
Microsoft Learn「Differences between Office Scripts and VBA macros」
確認日
2026-09-12(第 1 版)
出典の該当箇所
External API calls fail when a script is run through Power Automate.
Each user is limited to 1,600 calls to the Run script action per day.
Run script from SharePoint library. This is the action to use when scripts are stored in your team's SharePoint site.
Office Scripts only have access to the workbook, not the machine hosting the workbook.

06関数を OpenAPI 2.0 で記述し、カスタムコネクタとして取り込む確認済

関数の入出力を OpenAPI 2.0(旧 Swagger)の JSON に書き、Power Automate の[Import an OpenAPI file]で取り込むと、フローのアクションとして使える。定義は 1 MB 未満にし、OpenAPI 3.0 形式は取り込めない。

考え方と手順
  1. swagger を 2.0、host を関数アプリのホスト名、basePath を /api にする
  2. securityDefinitions で type を apiKey、in を header、name を x-functions-key にする。キーの値は定義に書かない
  3. paths に POST /summarize を書き、operationId に付けた名前がアクションとして表示される
  4. Power Automate で[Import an OpenAPI file]を選び、[General]ページのホストとベース URL を確かめる
  5. Power Automate で作ったコネクタは Power Apps と Copilot Studio でも使える
JSON
{
  "swagger": "2.0",
  "info": {
    "version": "1.0.0",
    "title": "LedgerSummary",
    "description": "Summarize request-ledger rows with an Azure Function"
  },
  "host": "example-func.azurewebsites.net",
  "basePath": "/api",
  "schemes": [
    "https"
  ],
  "consumes": [
    "application/json"
  ],
  "produces": [
    "application/json"
  ],
  "securityDefinitions": {
    "function_key": {
      "type": "apiKey",
      "in": "header",
      "name": "x-functions-key"
    }
  },
  "security": [
    {
      "function_key": []
    }
  ],
  "paths": {
    "/summarize": {
      "post": {
        "summary": "Count ledger rows by status",
        "operationId": "SummarizeLedger",
        "parameters": [
          {
            "in": "body",
            "name": "body",
            "schema": {
              "type": "object",
              "properties": {
                "rows": {
                  "type": "array",
                  "items": {
                    "type": "object"
                  },
                  "x-ms-summary": "rows"
                }
              }
            }
          }
        ],
        "responses": {
          "200": {
            "description": "200",
            "schema": {
              "type": "object",
              "properties": {
                "total": {
                  "type": "integer",
                  "x-ms-summary": "total"
                },
                "status": {
                  "type": "object",
                  "x-ms-summary": "status"
                },
                "open_by_owner": {
                  "type": "object",
                  "x-ms-summary": "open by owner"
                }
              }
            }
          }
        }
      }
    }
  }
}
Copilot に書かせる指示の例

Azure Functions の POST /api/summarize(本文 {"rows": [...]}、応答 total・status・open_by_owner)を、Power Automate のカスタムコネクタに取り込める OpenAPI 2.0 の JSON で書いて。認証は x-functions-key ヘッダーの apiKey にし、キーの値は書かないこと。

注意

OpenAPI 3.0 で書いた定義は取り込めないので、生成ツールの出力形式を確かめる。カスタムコネクタは無料ライセンス(標準コネクタだけ)では使えず、Power Automate Premium などのライセンスが要る。関数のホスト名とキーは環境ごとに違うので、取り込んだ後に接続の設定を確かめる。

利用条件
Power Automate、Power Apps、Copilot Studio、Logic Apps のカスタムコネクタ。Power Automate Premium のライセンスは標準・プレミアム・カスタムのコネクタを含むと文書にある。
試験
実行の対象外(設定・HTTP・数式)(2026-09-12)
出典
Microsoft Learn「Create a custom connector from an OpenAPI definition」
Microsoft Learn「Custom connectors overview」
Microsoft Learn「Types of Power Automate licenses」
確認日
2026-09-12(第 1 版)
出典の該当箇所
OpenAPI definitions that are in OpenAPI 3.0 format are not supported.
When creating a custom connector, the OpenAPI definition must be less than 1 MB.
In this case, the DetectSentiment action from the OpenAPI definition is displayed.
Connectors created in Power Automate are available in Power Apps and Copilot Studio
Connector usage is limited to standard connectors only.