Now inviting automation leaders: publish your playbook as a skill, under your own name. Publish yours →
Automation Skills
All skills/Spa sharepoint power automate/04-sharepoint
Reference · Spa sharepoint power automate

04-sharepoint

Part of Spa sharepoint power automate. Install the skill and your agent reads this page when it needs the depth.

<!-- spa-sharepoint-power-automate · references/04-sharepoint.md · secciones §10, §18 --> <!-- Contenido movido tal cual desde el SKILL.md monolítico (2026-09-24). Índice: ../SKILL.md -->

10 · SharePoint setup

List creation via REST — depende del tenant, PROBALO primero

POST /_api/web/lists devuelve HTTP 400 en algunos tenants por política, sin importar los permisos del usuario. Pero no es universal: en tenant-b.sharepoint.com (agosto 2026) funcionó a la primera y creó las dos listas sin chistar.

Corrección de una versión anterior de esta skill, que decía "don't try to script list creation" como regla general. Eso hizo que se le pidiera al usuario un paso manual que su tenant no necesitaba. Intentá el POST una vez —cuesta diez segundos y no rompe nada— y recién si devuelve 400 mandá a la UI.

$body = @{
    '__metadata'  = @{ type = 'SP.List' }
    Title         = $nombre
    Description   = $desc
    BaseTemplate  = 100          # 100 = lista generica (Custom List)
} | ConvertTo-Json -Depth 8
Invoke-SP -Method POST -Uri "$ApiSP/web/lists" `
    -BodyBytes ([Text.Encoding]::UTF8.GetBytes($body)) `
    -Extra @{ 'Content-Type' = 'application/json;odata=verbose;charset=utf-8' }

El script tiene que degradar con elegancia: si el POST falla, imprimir la URL que abre el diálogo con el nombre puesto y salir con código 1, en vez de morir con un stack trace.

Fallback para cuando sí está bloqueado:

En cualquiera de los dos casos, una vez que la lista existe, _api/.../fields para agregar columnas funciona siempre.

El bloqueo es por tenant, no por producto. Si trabajás con más de un tenant (ej. tenant-a y tenant-b), lo que aprendiste en uno no aplica al otro. Verificá en cada uno antes de dar por sentado que hace falta el paso manual.

List Title vs URL-name discrepancy

When you create Foo Bar via UI, SharePoint may store:

Always discover the actual Title via REST before doing anything else:

$lists = Invoke-RestMethod -Uri "$ApiSP/web/lists?`$select=Title&`$filter=Hidden eq false" -Headers $authHeaders
$lists.d.results | Where-Object { $_.Title -match "Foo" } | ForEach-Object { Write-Host $_.Title }

Real-world example: user creates a list at URL /Lists/CheckListSemiRemolque/..., but the actual Title is Check-List-Semi-Remolque (with hyphens). All getbytitle('CheckListSemiRemolque') calls return 404 until you use the real Title.

Idempotent column setup script

For repeatability, create columns from a versioned PowerShell script using device code auth (no app registration needed for tenant admin scenarios):

$ClientId = "9bc3ab49-b65d-410a-85ad-de819febfddc"  # SharePoint Online native client
$Resource = "https://$Hostname"

# Device code flow
$dcBody = "client_id=$ClientId&resource=$Resource"
$dcResp = Invoke-RestMethod -Method POST `
  -Uri "https://login.microsoftonline.com/common/oauth2/devicecode" -Body $dcBody
Write-Host "URL:    $($dcResp.verification_url)"
Write-Host "CODIGO: $($dcResp.user_code)"

# Poll for token (60s × 5s)
do {
  Start-Sleep -Seconds 5
  try {
    $tok = Invoke-RestMethod -Method POST `
      -Uri "https://login.microsoftonline.com/common/oauth2/token" `
      -Body "grant_type=urn:ietf:params:oauth:grant-type:device_code&client_id=$ClientId&code=$($dcResp.device_code)"
    break
  } catch { if ($_.ErrorDetails.Message -notmatch "authorization_pending") { throw } }
} while ($true)
$accessToken = $tok.access_token

# Idempotent column add
$h = @{ Authorization = "Bearer $accessToken"; Accept = "application/json;odata=verbose" }
foreach ($col in $columns) {
  $url = "$Resource/sites/X/_api/web/lists/getbytitle('Y')/fields/getbyinternalnameortitle('$($col.Name)')"
  try {
    Invoke-RestMethod -Uri $url -Headers $h | Out-Null
    Write-Host "✓ $($col.Name) ya existe"
  } catch {
    # Crear
    $body = @{ '__metadata' = @{ type = "SP.Field" }; Title = $col.Name; FieldTypeKind = $col.Type } | ConvertTo-Json
    Invoke-RestMethod -Method POST -Uri "$baseListUrl/fields" -Headers $h -Body $body
  }
}

Run idempotently any time. The script never fails on existing columns.

REST + PowerShell — UTF-8 trap

The single most painful integration bug. Invoke-RestMethod with a string -Body sends the body using ISO-8859-1, not UTF-8. Any accented character (ó, á, é, í, ú, ñ) anywhere in Title, Description, or Choices will cause SharePoint to reject the request with HTTP 400 and:

"Unable to translate bytes [F3] at index N from specified code page to Unicode"

(F3 = ó in Latin-1.) Plain-ASCII columns work, accented ones silently fail and the script "succeeds" with half the columns missing.

The fix is mandatory for any column whose Title or Choices may have accents:

$json = $body | ConvertTo-Json -Depth 8
$bodyBytes = [System.Text.Encoding]::UTF8.GetBytes($json)
$h2 = @{}; foreach ($k in $h.Keys) { $h2[$k] = $h[$k] }
$h2["Content-Type"] = "application/json;odata=verbose;charset=utf-8"
Invoke-RestMethod -Method POST -Uri $url -Headers $h2 -Body $bodyBytes

Always send body as UTF-8 byte array, never as string. Apply this to every POST/PATCH against _api/web/lists/.... The fix is local to each call — there's no global flag to set.

PowerShell 5.1 .ps1 file encoding

Even the script source itself: PowerShell 5.1 reads .ps1 files as ANSI/Windows-1252 unless they have a UTF-8 BOM. Without BOM, parser errors like "Falta la cadena en el terminador" appear at lines containing accented characters. Save with BOM:

$content = [System.IO.File]::ReadAllText($path, [System.Text.Encoding]::UTF8)
[System.IO.File]::WriteAllText($path, $content, (New-Object System.Text.UTF8Encoding($true)))

Validate with [System.Management.Automation.Language.Parser]::ParseFile($path, [ref]$tokens, [ref]$errs) before running.

Hidden default columns conflict

Some internal names collide with SharePoint's built-in hidden columns even though they don't appear in the UI. Symptoms: Add-Column returns HTTP 400 "Solicitud incorrecta" for a name that doesn't appear via getbyinternalnameortitle. Common conflicts:

Workaround: use a distinct InternalName, separate from the display Title:

Add-Column -ListTitle $list -Name "CategoriaItem" -Title "Categoría" ...
#                            ^^ unique internal     ^^ what user sees

The display name (Title) can have accents and conflicts; only the InternalName needs to be unique and ASCII.

Lookup column creation via REST

SP.FieldLookup creation through _api/web/lists/.../fields with __metadata.type = "SP.FieldLookup" returns HTTP 400 in most tenants, even with correct LookupListId and LookupFieldName. Known REST API limitation.

Three options, in order of effort:

  1. Manual via UI (recommended for one-offs): list → + Add column → Lookup → pick parent list + column

  2. Use createfieldasxml endpoint with raw SP XML schema:

    POST /_api/web/lists/getbytitle('Items')/fields/createfieldasxml
    Body: { "parameters": { "__metadata": { "type": "SP.XmlSchemaFieldCreationInformation" },
                             "SchemaXml": "<Field Type='Lookup' DisplayName='Inspeccion' Name='Inspeccion' List='{guid}' ShowField='Title' />",
                             "Options": 28 } }
    

    ⚠️ El endpoint REST es createfieldasxml. addfieldasxml es el nombre del método en CSOM/PnP y por REST devuelve ResourceNotFoundException — "No se encuentra el recurso para la solicitud addfieldasxml". Es un 404 disfrazado, fácil de confundir con un problema de permisos.

    Options es un bitmask: 4 AddToDefaultContentType + 8 AddFieldInternalNameHint + 16 AddFieldToDefaultView. 28 = las tres (lo habitual: crea la columna y además la muestra en la vista por defecto).

    Este endpoint sí funciona para columnas normales (Text, DateTime, URL, Choice) — es la forma más confiable de crearlas, porque permite fijar InternalName y DisplayName por separado y setear Indexed='TRUE' en el mismo XML.

  3. PnP PowerShell (Add-PnPField) — but requires module install + auth

In practice, manual UI is fastest. Always include a fallback in the script that prints clear instructions when REST creation fails.

Lookup column belongs on the CHILD list (very common mistake)

The lookup belongs on the child list (the one referencing the parent), not the parent. Symptom in Power Automate:

Fix: delete the column from the parent list, recreate it in the child list. After saving, refresh make.powerautomate.com — the field appears in the right place.

Verify SP Choice columns include all SPA values

When the SPA adds a new option to a dropdown that maps to a SharePoint Choice column (with FillInChoice='FALSE'), the new value is silently dropped by SP if it's not in the column's choices list. The flow's Create item succeeds (no error), but the column ends up empty for that row.

Whenever you add an option in types.ts (e.g. PROYECTOS_SERVICIOS), also:

  1. Update the choices list in Setup-AllColumns-*.ps1
  2. Either re-run the script (Ensure-ChoiceField updates choices via PATCH/MERGE) OR add manually in the SP UI

The script update needs the SP MERGE pattern (X-HTTP-Method: MERGE + IF-MATCH: *), with the same UTF-8 byte-body fix as above.


18 · Bulk data sync: Excel → SharePoint list via REST (NO Power Automate)

When the task is "load/update an existing SP list from an Excel" (not a public form pipeline), skip the flow entirely. Drive SharePoint REST directly with a resource token from a script.

18.1 Auth without per-app admin consent and without re-prompts

Scope and responsible use — read first.

  • This is a delegated, user-context technique: the token can only do what the signed-in person can already do in SharePoint. It grants no extra permission.
  • It is meant for people building automation with their own access who get stuck on per-app admin consent. It is a pragmatic workaround, not a substitute for the proper route (an app registration with admin-approved permissions, ideally Sites.Selected), and not a way to reach anything you couldn't already open in the browser.
  • Check your organization's policy first. It is fully visible in Entra sign-in logs (client SharePoint Online Management Shell, device-code flow) and can be blocked by Conditional Access or by disabling the device-code flow. Microsoft may change that client's pre-authorization at any time, so don't build production on it.
  • Treat the refresh token like a password: encrypted at rest, never shared, never committed.

18.2 Reading existing items — the /items returns 0 quirk

On some lists the OData feed _api/web/GetList('...')/items returns value: [] even though ItemCount says 314 — even when the caller is Site Admin, ReadSecurity=1, WriteSecurity=1, moderation off, full EffectiveBasePermissions. It is not a permission/moderation issue. Fix: read via RenderListDataAsStream (what the UI uses):

$gid  = (Invoke-RestMethod ".../_api/web/GetList('$encUrl')?`$select=Id" -Headers $H).Id
$view = "<View><ViewFields><FieldRef Name='ID'/><FieldRef Name='$keyField'/></ViewFields><RowLimit>5000</RowLimit></View>"
$body = @{ parameters = @{ RenderOptions = 2; ViewXml = $view } } | ConvertTo-Json -Compress
$rd   = Invoke-RestMethod -Method POST ".../_api/web/lists(guid'$gid')/RenderListDataAsStream" -Headers $H -Body ([Text.Encoding]::UTF8.GetBytes($body))
$rd.Row   # array of { ID, field_1, ... } as DISPLAY strings

Page with $rd.NextHref when present; with RowLimit ≥ count it's one page. Each Row value is the display-formatted string (numbers carry thousand separators, dates are localized) — normalize before comparing.

18.3 Resolve the list by server-relative URL, not Title

getbytitle('<slug>') 404s constantly: the URL slug strips accents and can differ from the display Title in spelling (real case: slug .../Lists/Histrico vs Actual Experto ART, actual Title Histórico vs Actual Experta ART). Use GetList('/sites/<site>/Lists/<slug>') (URL-encode spaces to %20) — it resolves by the URL you already have from the browser.

18.4 Transient 401 right after a token

The 2nd–3rd REST call right after obtaining/refreshing a token intermittently returns 401. Wrap every call in a retry that re-tokenizes on 401 (2–3 attempts, ~800ms sleep); also back off on 429/503 via Retry-After. Build the Authorization header fresh from a $script:Token each attempt so the refreshed token propagates.

18.5 Writes — nometadata, UTF-8, no digest

With an OAuth Bearer token you do not need X-RequestDigest. Create/update with odata=nometadata so you can omit __metadata:

18.6 Upsert keying for generic-column lists

Generic lists store custom columns as internal names field_1..field_N; map Excel headers → columns by normalized displayName (accent-strip + uppercase + alnum-only), same Normalize-HeaderKey as the flow scripts. Columns present in Excel but absent in the list (e.g. POLIZA) are simply skipped — log them, don't fail. Canonicalize the numeric upsert key by stripping non-digits on both the SP display value and the Excel value before matching.

Publish your skill

Copy this prompt into Claude Code, Codex or any agent. It walks you through your first skill in about 20 minutes, with you as the author.

Click to copy.