You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PnP PowerShell模块和访问令牌连接SharePoint失败求助

问题描述

尝试使用PnP PowerShell模块结合访问令牌连接SharePoint站点,执行脚本后出现以下错误:

Connect-PnPOnline: Could not load file or assembly 'Microsoft.Identity.Client, Version=4.50.0.0, Culture=neutral, PublicKeyToken=0a613f4dd989e8ae'. Could not find or load a specific file. (0x80131621)

使用的脚本如下:

# Import the MSAL Module to generate the access token
Import-Module MSAL.PS

# Generating the token (this brings other fields too, like 'ExpireOn' or 'TokenType')
$token1 = Get-MsalToken -ClientId xxx -ClientSecret $(convertto-securestring("xxx") -AsPlainText -Force) -TenantId xxx

# Saving only the 'Access Token' field value into the variable
$token1 = $token1.AccessToken

# Trying to connect using the token
connect-pnpOnline -Url "https://boehringerdev.sharepoint.com/sites/z365SupportSite" -AccessToken $token1

尝试将令牌转换为安全字符串后,错误依然存在。

原因分析

该错误是由于MSAL.PS模块与PnP PowerShell模块依赖的Microsoft.Identity.Client程序集版本冲突导致的:PnP PowerShell自身依赖特定版本的Microsoft.Identity.Client,而外部导入的MSAL.PS模块引入了不同版本的该程序集,导致加载时无法找到匹配的版本。

解决方案

方案一:使用PnP PowerShell内置命令获取令牌(推荐)

PnP PowerShell自带令牌获取能力,无需额外依赖MSAL.PS模块,直接用客户端凭据连接即可:

# 直接使用客户端凭据连接SharePoint站点
Connect-PnPOnline -Url "https://boehringerdev.sharepoint.com/sites/z365SupportSite" `
                  -ClientId "xxx" `
                  -ClientSecret (ConvertTo-SecureString "xxx" -AsPlainText -Force) `
                  -Tenant "boehringerdev.onmicrosoft.com"

如果需要单独获取令牌,可在连接后执行:

$accessToken = Get-PnPAccessToken

方案二:解决版本冲突

  1. 卸载所有版本的MSAL.PS模块,避免版本干扰:
Uninstall-Module MSAL.PS -Force -AllVersions
  1. 查看PnP PowerShell依赖的Microsoft.Identity.Client版本:
Get-Module PnP.PowerShell -ListAvailable | 
  Select-Object -ExpandProperty RequiredModules | 
  Where-Object Name -eq "Microsoft.Identity.Client"
  1. 安装与PnP依赖版本匹配的MSAL.PS模块(若必须使用MSAL.PS):
Install-Module MSAL.PS -RequiredVersion <匹配的版本号> -Force

方案三:隔离模块会话

打开全新的PowerShell窗口,不导入MSAL.PS模块,直接运行PnP连接命令,避免模块间的版本冲突。

额外提示

Connect-PnPOnline的-AccessToken参数接受普通字符串格式的令牌,无需转换为安全字符串,之前的转换操作是多余的。

内容的提问来源于stack exchange,提问作者Maximiliano Ferradás

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 09:02:28