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

qacovj5a  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(290)

我正在编写一个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的帮助。

ioekq8ef

ioekq8ef1#

未将文件名添加到文件路径:

$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})尝试读取文件夹并阻塞。错误消息并不真正准确

相关问题