-
Notifications
You must be signed in to change notification settings - Fork 6
/
Add-AzureStorageBlob.ps1
92 lines (84 loc) · 2.87 KB
/
Add-AzureStorageBlob.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
function Add-AzureStorageBlob {
<#
.SYNOPSIS
Uploads files to Azure Storage Blob
.DESCRIPTION
Uploads files to Azure Storage Blob from a local folder
.PARAMETER Path
Path to file or local folder
.PARAMETER StorageContainer
StorageContainer name
.PARAMETER StorageAccount
StorageAccount name
.PARAMETER ResourceGroup
ResourceGroup name
.PARAMETER Recurse
Recurse through subfolders
.EXAMPLE
Add-AzureStorageBlob -Path "C:\Temp\MyFolder" -StorageContainer "mycontainer" -StorageAccount "mystorageaccount" -ResourceGroup "myresourcegroup" -Recurse $true
.NOTES
Author: Bas Wijdenes
Site: https://baswijdenes.com
#>
[CmdletBinding()]
param (
[parameter(mandatory = $true)]
[string]$Path,
[parameter(mandatory = $true)]
$StorageContainer,
[parameter(mandatory = $true)]
$StorageAccount,
[parameter(mandatory = $true)]
$ResourceGroup,
[parameter(mandatory = $false)]
[bool]$Recurse
)
try {
Write-Verbose "Getting StorageAccount: $($StorageAccount) in ResourceGroup: $($ResourceGroup)"
$storageAccount = Get-AzStorageAccount -ResourceGroupName "$($ResourceGroup)" -AccountName "$StorageAccount"
}
catch {
throw $_.Exception.Message
}
if ($null -eq $StorageAccount) {
throw "StorageAccount: $StorageAccount not found under ResourceGroup: $ResourceGroup"
}
$CTX = $storageAccount.Context
try {
if ($Recurse -eq $true) {
Get-ChildItem -Path $Path -File -Recurse | Set-AzStorageBlobContent -Container ($StorageContainer) -Context $CTX -Force
$Items = Get-ChildItem -Path $Path -Recurse
}
else {
$Items = Get-ChildItem -Path $Path
}
}
catch {
throw $_.Exception.Message
}
if ($null -eq $Items) {
throw "No files found under $Path"
}
else {
if ($Recurse -eq $false) {
$UploadedItems = [System.Collections.Generic.List[Object]]::new()
foreach ($Item in $Items) {
$Object = [PSCustomObject]@{
Item = $Item.Name
Successful = $null
}
Write-Verbose "Uploading $($Item.BaseName) to $($StorageContainer)"
try {
$null = $Item | Set-AzStorageBlobContent -Container $($StorageContainer) -Context $CTX -Force -ErrorAction Stop
$Object.Successful = $true
}
catch {
Write-Warning "Something went wrong uploading $($Item.BaseName) to $($StorageContainer): $($_.Exception.Message)"
$Object.Successful = $false
}
$UploadedItems.Add($Object)
}
}
return $UploadedItems
}
}