-1

i'm new to powershell i have a script running on multiple devices to fetch details and i want a single csv to be generated with those details in a box folder . i wanted to know how to upload a csv to box folder using powershell without hard coding any credentials in script.

Any help will be thankfull.

2

2 Answers 2

0

Your question seems more authentication-related than PowerShell syntax-related.

I would first check out the documentation below from Box to get started:

Automate Box Integration Tasks from PowerShell

This link describes how to install the module and use it with these examples:

PowerShell

Install the module

Install-Module BoxCmdlets
Connect
$box = Connect-Box  -OAuthClientId "$OAuthClientId" -OAuthClientSecret "$OAuthClientSecret" -CallbackURL "$CallbackURL"
Search for and retrieve data
$id = "123"
$files = Select-Box -Connection $box -Table "Files" -Where "Id = `'$Id`'"
$files

There's a whole getting started guide here Use Box CLI with OAuth 2.0 | developer.box.com and chapter 5 focuses on using Powershell scripts with the CLI

Sign up to request clarification or add additional context in comments.

Comments

0

try this code

param(
    [string]$AccessToken,
    [string]$LocalFilePath,
    [string]$NewFileName,
    [string]$ParentFolderId
)

# ==============================
# Step 1: Create upload session
# ==============================
$FileInfo = Get-Item $LocalFilePath
$FileSize = $FileInfo.Length

$CreateSessionUrl = "https://upload.box.com/api/2.0/files/upload_sessions"
$SessionBody = @{
    folder_id = $ParentFolderId
    file_name = $NewFileName
    file_size = $FileSize
} | ConvertTo-Json

try {
    Write-Host "Creating upload session..."
    $SessionResponse = Invoke-RestMethod -Uri $CreateSessionUrl -Method Post `
        -Headers @{ "Authorization" = "Bearer $AccessToken"; "Content-Type" = "application/json" } `
        -Body $SessionBody

    $SessionId = $SessionResponse.id
    $PartSize = [int64]$SessionResponse.part_size

    Write-Host "✅ Upload session created successfully. Session ID: $SessionId"
}
catch {
    Write-Error "❌ Failed to create upload session: $($_.Exception.Message)"
    exit 1
}

# ==============================
# Helper: Abort session function
# ==============================
function Abort-UploadSession {
    param($SessionId, $AccessToken)
    Write-Warning "⚠️ Aborting upload session $SessionId..."
    try {
        Invoke-RestMethod -Uri "https://upload.box.com/api/2.0/files/upload_sessions/$SessionId" `
            -Method Delete `
            -Headers @{ "Authorization" = "Bearer $AccessToken" }
        Write-Host "🚫 Upload session aborted successfully."
    } catch {
        Write-Warning "⚠️ Failed to abort session: $($_.Exception.Message)"
    }
}

# ==============================
# Step 2: Upload chunks with retry
# ==============================
$FileStream = [System.IO.File]::OpenRead($LocalFilePath)
$Parts = @()
$ChunkNumber = 0
$BytesReadTotal = 0
$MaxRetries = 3

try {
    while ($BytesReadTotal -lt $FileSize) {
        $BufferSize = [Math]::Min($PartSize, $FileSize - $BytesReadTotal)
        $Buffer = New-Object byte[] $BufferSize
        $BytesRead = $FileStream.Read($Buffer, 0, $BufferSize)

        $StartByte = $BytesReadTotal
        $EndByte = $BytesReadTotal + $BytesRead - 1
        $ContentRange = "bytes $StartByte-$EndByte/$FileSize"
        $Digest = "sha=$([System.Convert]::ToBase64String([System.Security.Cryptography.SHA1]::Create().ComputeHash($Buffer)))"

        Write-Host "Uploading chunk $($ChunkNumber + 1)... [$StartByte-$EndByte]"

        $UploadChunkUrl = "https://upload.box.com/api/2.0/files/upload_sessions/$SessionId"
        $Success = $false

        for ($attempt = 1; $attempt -le $MaxRetries; $attempt++) {
            try {
                $ChunkResponse = Invoke-RestMethod -Uri $UploadChunkUrl -Method Put `
                    -Headers @{
                        "Authorization" = "Bearer $AccessToken"
                        "Content-Type" = "application/octet-stream"
                        "Content-Range" = $ContentRange
                        "Digest" = $Digest
                    } `
                    -Body $Buffer

                $Parts += $ChunkResponse.part
                $BytesReadTotal += $BytesRead
                $ChunkNumber++
                $Success = $true
                Write-Host "✅ Chunk $ChunkNumber uploaded successfully."
                break
            }
            catch {
                Write-Warning "⚠️ Chunk upload failed (Attempt $attempt/$MaxRetries): $($_.Exception.Message)"
                if ($attempt -lt $MaxRetries) {
                    $WaitTime = [Math]::Pow(2, $attempt) # 2s, 4s, 8s
                    Write-Host "⏳ Retrying in $WaitTime seconds..."
                    Start-Sleep -Seconds $WaitTime
                }
            }
        }

        if (-not $Success) {
            Write-Error "❌ Failed to upload chunk $($ChunkNumber + 1) after $MaxRetries attempts."
            Abort-UploadSession -SessionId $SessionId -AccessToken $AccessToken
            exit 1
        }
    }

    Write-Host "✅ All chunks uploaded successfully."
}
catch {
    Write-Error "❌ Unexpected error during upload: $($_.Exception.Message)"
    Abort-UploadSession -SessionId $SessionId -AccessToken $AccessToken
    exit 1
}
finally {
    $FileStream.Close()
}

# ==============================
# Step 3: Compute file digest (for commit)
# ==============================
try {
    Write-Host "Calculating full file digest..."
    $FileBytes = [System.IO.File]::ReadAllBytes($LocalFilePath)
    $FullDigestBytes = [System.Security.Cryptography.SHA1]::Create().ComputeHash($FileBytes)
    $FullDigest = "sha=$([System.Convert]::ToBase64String($FullDigestBytes))"
    Write-Host "✅ Digest calculated for commit."
}
catch {
    Write-Error "❌ Failed to calculate file digest: $($_.Exception.Message)"
    Abort-UploadSession -SessionId $SessionId -AccessToken $AccessToken
    exit 1
}

# ==============================
# Step 4: Commit upload session
# ==============================
$CommitUrl = "https://upload.box.com/api/2.0/files/upload_sessions/$SessionId/commit"
$CommitBody = @{ parts = $Parts } | ConvertTo-Json -Depth 5

try {
    Write-Host "Committing upload..."
    $CommitResponse = Invoke-RestMethod -Uri $CommitUrl -Method Post `
        -Headers @{
            "Authorization" = "Bearer $AccessToken"
            "Content-Type" = "application/json"
            "Digest" = $FullDigest
        } `
        -Body $CommitBody

    Write-Host "🎉 File uploaded and committed successfully!"
    Write-Host "📄 File ID: $($CommitResponse.entries[0].id)"
}
catch {
    Write-Error "❌ Failed to commit upload: $($_.Exception.Message)"
    Abort-UploadSession -SessionId $SessionId -AccessToken $AccessToken
    exit 1
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.