我目前正在开发脚本,以使用Power BI的REST API自动刷新我的Power BI数据集。该脚本是一个.ps1文件,从我的Python代码中调用,如下所示。我从this教程开始逐步学习,而我的 refresh.ps1 文件是从this official MS source.开发而来的,只是做了一些小改动以使其运行,所以如果有人要测试它,我建议使用我在此问题结尾处发布的代码。
但是,除了两个代码都可以正常工作之外,它们还允许我刷新数据集,每次运行时,我都必须通过提示的GUI手动登录Azure帐户。这使得该脚本无助于自动执行任务,例如我的情况。请参见下面的GUI图片:
我做了一些资源,但找不到任何类似的情况,其中也使用了Python。关于Powershell,我读过有关使用ADAL的信息,但并不能真正了解ADAL是什么。
到目前为止,我的Python脚本是:
import subprocess, sys
def powershell(file):
p = subprocess.Popen(["powershell.exe", file], stdout=sys.stdout)
p.communicate()
MS.powershell(r"'C:\blablabla\refresh.ps1'")
我的refresh.ps1
文件具有如下所示的内容:
$groupID = "MY_GROUP_ID"
$datasetID = "MY_DATASET_ID"
$clientId = "MY_CLIENT_ID"
function GetAuthToken
{
if(-not (Get-Module AzureRm.Profile)) {
Import-Module AzureRm.Profile
}
$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
$resourceAppIdURI = "https://analysis.windows.net/powerbi/api"
$authority = "https://login.microsoftonline.com/common/oauth2/authorize";
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, "Auto")
return $authResult
}
$token = GetAuthToken
$authHeader = @{
'Content-Type'='application/json'
'Authorization'=$token.CreateAuthorizationHeader()
}
$groupsPath = ""
if ($groupID -eq "me") {
$groupsPath = "myorg"
} else {
$groupsPath = "myorg/groups/$groupID"
}
$uri = "https://api.powerbi.com/v1.0/$groupsPath/datasets/$datasetID/refreshes"
Invoke-RestMethod -Uri $uri -Headers $authHeader -Method POST -Verbose
答案 0 :(得分:1)
如果您要进行静默身份验证,则可以使用UserCredentials类,并将用户名和密码传递给AcquireToken方法。您的GetAuthToken函数应该变成这样:
function GetAuthToken
{
# Change these
$username = "chuck@norris.com"
$password = ConvertTo-SecureString "myP@ssw0rd" –asplaintext –force
if(-not (Get-Module AzureRm.Profile)) {
Import-Module AzureRm.Profile
}
$resourceAppIdURI = "https://analysis.windows.net/powerbi/api"
$authority = "https://login.microsoftonline.com/common/oauth2/authorize";
$credentials = New-Object System.Management.Automation.PSCredential $Username,$password
$AADcredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credentials.UserName,$credentials.Password
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$authResult = $authContext.AcquireToken($resourceAppIdURI,$clientId,$AADcredential)
return $authResult
}