通过 REST API 和令牌认证将 xlsx 作为附件上传到 confluence 页面

问题描述 投票:0回答:1

我正在编写一个 Powershell 脚本,它将使用令牌身份验证通过 REST API 将 Excel 文档上传到 Atlassian Confluence 页面。

Write-Host "Start of script"

$userToken = "TOKEN"
$pageId = "PAGE-ID"
$fileName = "All_Employee_List.xlsx"

$rootFolder = "C:\moonfall\Powershell\Server Side\General Server Scripts"
$subFolder = "All_Employee_list\All_Employee_List_SRV_2"
$filePath = Join-Path $rootFolder $subFolder


$wpURL = "https://DOMAIN/rest/api/content/"

$Headers = @{
    'Authorization' = "Bearer $userToken"
    'X-Atlassian-Token' = 'nocheck'
}

# Get the attachment ID if it exists
$uri = $wpURL + $pageId + "/child/attachment?filename=$fileName&expand=body.storage,version,space,ancestors"
$attachment = Invoke-RestMethod -Method GET -Headers $Headers -Uri $uri
$attachmentId = $attachment.results.id

# If the attachment doesn't exist, create it
if (!$attachmentId) {
    $uri = $wpURL + $pageId + "/child/attachment"
    
    #after this file path check it won't upload to confluence anymore, it just says access to the path is denied
    if (-not (Test-Path $filePath)) {
        Write-Error "File does not exist at $filePath"
        return
    }
    
    try {
        $fileBytes = [System.IO.File]::ReadAllBytes(${filePath})
    } catch {
        Write-Error "Failed to read file at ${filePath}: $_"
        return
    }

    $fileEncoded = [System.Convert]::ToBase64String($fileBytes)

    $delimiter = [System.Guid]::NewGuid().ToString()
    $LF = "`r`n"
    $bodyData = ( 
        "--$delimiter",
        "Content-Disposition: form-data; name=`"file`"; filename=`"$fileName`"",
        "Content-Type: application/octet-stream$LF",
        $fileEncoded,
        "--$delimiter--$LF" 
    ) -join $LF

    Invoke-RestMethod -Uri $uri -Method POST -ContentType "multipart/form-data; boundary=$delimiter" -Headers $Headers -Body $bodyData
    Write-Output "Attachment created successfully."
} else {
    Write-Output "Attachment already exists. Skipping creation."
}

# Set the attachment as the primary viewable attachment
$uri = $wpURL + $attachmentId + "/?minorEdit=true"
$bodyData = @{
    "id" = $attachmentId
    "version" = @{
        "number" = $attachment.version.number + 1
    }
    "type" = "attachment"
    "title" = $fileName
    "container" = @{
        "id" = $pageId
        "type" = "page"
    }
    "metadata" = @{
        "comment" = @{
            "value" = "Automatically uploaded from PowerShell script."
        }
        "labels" = @()
        "properties" = @{
            "download" = @{
                "value" = @{
                    "downloadAll" = "true"
                }
            }
        }
    }
    "extensions" = @{
        "mediaType" = @{
            "value" = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            "macroEnabled" = "true"
        }
    }
    "status" = "current"
} | ConvertTo-Json

# Make the request
$response = Invoke-RestMethod -Uri $uri -Method POST -Headers $Headers -ContentType "multipart/form-data; boundary=$delimiter" -Body $bodyData

# Print the response
$response

当我在具有管理员权限的 Powershell 终端中运行脚本时,出现错误:

无法读取“FILE-PATH”处的文件:使用“1”参数调用“ReadAllBytes”的异常:“拒绝访问路径‘FILE-PATH’。

但是当我删除 $filebytes 的文件路径检查时,它会写入一个稍微不同的错误:

Exception calling "ReadAllBytes" with "1" argument(s): "Access to the path 'C:\moonfall\Powershell\Server Side\General Server Scripts\All_Employee_list\All_Employee_List_SRV_2' is denied."
At line:29 char:5
+     $fileBytes = [System.IO.File]::ReadAllBytes($filePath)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : UnauthorizedAccessException
 
Exception calling "ToBase64String" with "1" argument(s): "Value cannot be null.
Parameter name: inArray"
At line:30 char:5
+     $fileEncoded = [System.Convert]::ToBase64String($fileBytes)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException


results                                                                                                                                               size _links
-------                                                                                                                                               ---- ------
{@{id=123455572; type=attachment; status=current; title=All_Employee_List.xlsx; version=; container=; metadata=; extensions=; _links=; _expandable=}}    1 @{base=https://DOMAIN; context=}
Attachment created successfully.
Invoke-RestMethod : The remote server returned an error: (415).
At line:84 char:13
+ $response = Invoke-RestMethod -Uri $uri -Method POST -Headers $Header ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

并将文件作为附件上传到页面,但文件只有 0.0 kb,打开时里面什么也没有。 所以在我看来,这个脚本有两个问题。 如果有人能提供帮助,请帮忙,这对我来说都是全新的,我已经尝试解决这个问题 3 周了,而且还在 ChatGPT 的帮助下。

excel powershell confluence confluence-rest-api http-token-authentication
1个回答
0
投票

您错过了将文件名添加到文件路径:

$fileName = "All_Employee_List.xlsx"

$rootFolder = "C:\moonfall\Powershell\Server Side\General Server Scripts"
$subFolder = "All_Employee_list\All_Employee_List_SRV_2"
$filePath = Join-Path $rootFolder $subFolder ## File name missing?

所以

ReadAllBytes(${filePath})
试图阅读文件夹和窒息。错误信息不是很准确

© www.soinside.com 2019 - 2024. All rights reserved.