Skip to content

Commit 671e142

Browse files
authored
Merge pull request #2 from cksapp/module
Refresh Script
2 parents f8e920a + 4cf10d7 commit 671e142

4 files changed

Lines changed: 256 additions & 86 deletions

File tree

src/Refresh.ps1

Lines changed: 126 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,109 +1,150 @@
1-
<#
2-
Feel free to change these varaibles as needed for your environment if needed.
3-
#>
41

5-
# Set the path to the environment variable file
6-
$envFilePath = "$PSScriptRoot\override.env"
2+
<#PSScriptInfo
73
8-
# Set the URL of the API you want to access
9-
$apiUrl = "https://dbpool.datto.net/api/v2/containers"
4+
.VERSION 2023.11.0
105
11-
# Define the path for the log file
12-
$logFilePath = "$PSScriptRoot\logs\LogFile.log"
6+
.GUID 74cd4100-d57e-4660-b681-39148119afd3
137
14-
<#
15-
Please do not make any changes below this line unless you know what you are doing.
16-
If you would like to suggest a change, Pull Requests are always welcome.
17-
#>
8+
.AUTHOR Kent Sapp
189
19-
# Sets the Security Protocol for a .NET application to use TLS 1.2
20-
Set-Security
10+
.COMPANYNAME
2111
22-
# Check if the override.env file exists and import variables to session
23-
if (Test-Path -Path $envFilePath -PathType Leaf) {
24-
$envLines = Get-Content -Path $envFilePath
12+
.COPYRIGHT © 2023 Kent sapp. All rights reserved.
2513
26-
foreach ($line in $envLines) {
27-
# Skip commented lines that start with `#`
28-
if ($line -match '^\s*#') {
29-
continue
30-
}
14+
.TAGS
3115
32-
$line = $line.Trim()
33-
if (-not [string]::IsNullOrWhiteSpace($line) -and $line -match '^(.*?)=(.*)$') {
34-
$envName = $matches[1]
35-
$envValue = $matches[2]
36-
Write-Host "Setting environment variable: $envName=$envValue"
37-
[Environment]::SetEnvironmentVariable($envName, $envValue, "Process")
38-
}
39-
}
40-
} else {
41-
Write-Host "Override file does not exist at $envFilePath"
42-
}
16+
.LICENSEURI https://github.com/cksapp/DBPool_Refresh/blob/main/LICENSE
4317
44-
# Check if the variable $p_apiKey exists from override.env file, otherwise ask the user for their API key
45-
if (-not (Test-Path variable:p_apiKey)) {
46-
# If it doesn't exist, ask the user for input
47-
$apiKeySecure = Read-Host "Please enter your DBPool Personal API Key" -AsSecureString
48-
# Convert the secure string to a plain text string
49-
$p_apiKey = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($apiKeySecure))
50-
51-
# Set environment variable using [Environment]::SetEnvironmentVariable
52-
[Environment]::SetEnvironmentVariable("apiKey", $p_apiKey, "Process")
53-
54-
# Clear plaintext variable
55-
$p_apiKey = $null
56-
# Dispose of the SecureString to minimize its exposure in memory
57-
$apiKeySecure.Dispose()
58-
}
18+
.PROJECTURI https://github.com/cksapp/DBPool_Refresh
5919
60-
# Get the API key from environment variables
61-
$apiKey = $env:apiKey
62-
#Write-Host "apiKey value: $apiKey"
20+
.ICONURI
6321
64-
# Prepare headers with the API key
65-
$headers = @{
66-
"X-App-Apikey" = $apiKey
67-
}
22+
.EXTERNALMODULEDEPENDENCIES DattoDBPool PowerShellGet
6823
69-
# Make an API request with the API key in the headers
70-
$getContainers = Invoke-WebRequest -Uri $apiUrl -Headers $headers -Method Get
24+
.REQUIREDSCRIPTS
7125
72-
# Display the response content
73-
#Write-Host $getContainers.Content
26+
.EXTERNALSCRIPTDEPENDENCIES
7427
28+
.RELEASENOTES
7529
76-
# Convert JSON response to PowerShell object
77-
$json = ConvertFrom-Json $getContainers
7830
79-
# Check if the directory of the log file exists, and create it if not
80-
$logDirectory = [System.IO.Path]::GetDirectoryName($logFilePath)
81-
if (-not (Test-Path $logDirectory)) {
82-
New-Item -Path $logDirectory -ItemType Directory
83-
}
84-
# Start recording the transcript
85-
Start-Transcript -Path $logFilePath -Append
86-
Write-Output "Logging Started."
31+
.PRIVATEDATA
32+
33+
#>
34+
8735

36+
<#
37+
38+
.DESCRIPTION
39+
PowerShell script to `Refresh` all child containers in Datto (Kaseya) DBPool, this can be combined with Scheduled Tasks in Windows or a Cron job to automate the refresh script on a set interval.
40+
41+
#>
42+
[CmdletBinding(SupportsShouldProcess)]
43+
Param(
44+
[Parameter(
45+
Position = 0,
46+
Mandatory = $False,
47+
ValueFromPipeline = $True,
48+
ValueFromPipelineByPropertyName = $True
49+
)]
50+
$apiUrl = "https://dbpool.datto.net",
51+
52+
[Parameter(
53+
Position = 1,
54+
Mandatory = $False,
55+
ValueFromPipeline = $True,
56+
ValueFromPipelineByPropertyName = $True
57+
)]
58+
$apiKey,
59+
60+
[Parameter(
61+
Mandatory = $False,
62+
ValueFromPipeline = $True,
63+
ValueFromPipelineByPropertyName = $True
64+
)]
65+
$varScope = "Script"
66+
)
67+
68+
Begin {
69+
# Functions Directory Path
70+
$functionsPath = Join-Path -path $PSScriptRoot -ChildPath "functions" -AdditionalChildPath "*.ps1"
71+
72+
# Import functions
73+
$Functions = @( Get-ChildItem -Path $functionsPath -ErrorAction SilentlyContinue )
74+
foreach ($Import in @($Functions)) {
75+
try {
76+
. $Import.fullname
77+
} catch {
78+
throw "Could not import function $($Import.fullname): $_"
79+
}
80+
}
8881

89-
# Extract and print the 'id' values under 'containers'
90-
$json.containers | ForEach-Object {
91-
$ids = $_.id
92-
$names = $_.name
82+
#Import environment override variables
83+
. Import-Env
9384

94-
# Perform API call for each 'id'
95-
$refreshUrl = "$apiUrl/${ids}/actions/refresh"
96-
$refreshResponse = Invoke-WebRequest -Uri $refreshUrl -Headers $headers -Method Post
85+
# Specify the module name
86+
$moduleName = "DattoDBPool"
9787

98-
# Display the API response
99-
Write-Host "API Response for Refresh of container:${names}"
100-
$refreshResponse | ConvertTo-Json -Depth 4
88+
# Check if the module is installed
89+
$installedModule = Get-InstalledModule $moduleName -ErrorAction SilentlyContinue
90+
$onlineModule = Find-Module -Name $moduleName
91+
92+
if (!$installedModule) {
93+
try {
94+
Write-Output "Module $moduleName was not installed, attempting to install."
95+
Install-Module $moduleName -Force -ErrorAction Stop
96+
Write-Output "Module $moduleName installed successfully."
97+
} catch {
98+
Write-Error "Error installing module $moduleName`: $_"
99+
throw
100+
}
101+
} else {
102+
Write-Verbose -Message "Module $moduleName is already installed."
103+
104+
#Update the module if the version is higher
105+
if ($installedModule.version -lt $onlineModule.version) {
106+
Write-Verbose -Message "Updating $moduleName from version $installedModuleVersion to $onlineModuleVersion."
107+
Update-Module -Name $moduleName -Force
108+
} elseif ($installedModule.version -eq $onlineModule.version) {
109+
Write-Verbose -Message "$moduleName version installed is $installedModuleVersion which matches $onlineModuleVersion."
110+
}
111+
}
101112
}
102113

114+
Process {
115+
Import-Module -Name $moduleName -Force
116+
Set-SecurityProtocol
117+
118+
# Set API parameters
119+
If ($apiUrl -and $apiKey) {
120+
Set-DdbpApiParameters -apiUrl $apiUrl -apiKey $apiKey -varScope "$varScope"
121+
}
122+
123+
# Get Containers only if API is available
124+
while (Test-ApiAvailability -apiUrl $apiUrl -apiKey $apiKey -Verbose) {
125+
$Containers = Get-Containers -apiUrl $apiUrl -apiKey $apiKey -Verbose -varScope "$varScope"
126+
127+
$Containers | ForEach-Object -Parallel {
128+
Import-Module -Name $using:moduleName -Force
129+
130+
Write-Output "Refreshing Container $($_.name) with ID: $($_.id)."
131+
Sync-Containers -apiUrl $using:apiUrl -apiKey $using:apiKey -id $_.id -Verbose
132+
} -ThrottleLimit 10
133+
}
134+
135+
<#
136+
if (Test-ApiAvailability -apiUrl $apiUrl -apiKey $apiKey -Verbose) {
137+
$Containers = Get-Containers -apiUrl $apiUrl -apiKey $apiKey -Verbose -varScope "$varScope"
138+
139+
$Containers | ForEach-Object -Parallel {
140+
Import-Module -Name $using:moduleName -Force
141+
142+
Write-Output "Refreshing Container $($_.name) with ID: $($_.id)."
143+
Sync-Containers -apiUrl $using:apiUrl -apiKey $using:apiKey -id $_.id -Verbose
144+
} -ThrottleLimit 10
145+
}#>
146+
}
103147

104-
# Stop recording the transcript
105-
Write-Output "Logging Stopped."
106-
Stop-Transcript
148+
End {
107149

108-
# Close Session
109-
Exit-PSSession
150+
}

src/example-env_override.ps1

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# This is an example override.env file, accepts lines commented out with `#`
2+
$apiUrl = "https://dbpool.datto.net"
3+
# $apiKey="your_api_key_here"
4+
$ids="xxxxx"

src/example_override.env

Lines changed: 0 additions & 1 deletion
This file was deleted.

src/functions/Import-Env.ps1

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
<#
2+
.SYNOPSIS
3+
Checks if the override.ps1 file exists and imports the variables to current session
4+
.DESCRIPTION
5+
This allows for a user specified file location for
6+
.NOTES
7+
Information or caveats about the function e.g. 'This function is not supported in Linux'
8+
.LINK
9+
Specify a URI to a help page, this will show when Get-Help -Online is used.
10+
.EXAMPLE
11+
Test-MyTestFunction -Verbose
12+
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
13+
#>
14+
15+
function Import-Env {
16+
[CmdletBinding()]
17+
param (
18+
[Parameter(
19+
Mandatory = $False,
20+
Position = 0,
21+
ValueFromPipeline = $True,
22+
ValueFromPipelineByPropertyName = $True,
23+
HelpMessage = "The path for environment override file."
24+
)]
25+
[String]
26+
$envFilePath,
27+
28+
[Parameter(
29+
Mandatory = $False,
30+
Position = 1,
31+
ValueFromPipeline = $True,
32+
ValueFromPipelineByPropertyName = $True,
33+
HelpMessage = "The environment override file name."
34+
)]
35+
[String]
36+
$envFileName = "env_override",
37+
38+
[Parameter(
39+
Mandatory = $False,
40+
Position = 2,
41+
ValueFromPipeline = $True,
42+
ValueFromPipelineByPropertyName = $True,
43+
HelpMessage = "Environment override file extenstion."
44+
)]
45+
[String]
46+
$envFileExt = "ps1",
47+
48+
[Parameter(
49+
Mandatory = $False,
50+
Position = 3,
51+
ValueFromPipeline = $True,
52+
ValueFromPipelineByPropertyName = $True,
53+
HelpMessage = "The environment override file filter. Defaults to remove lines begining with `#` comments"
54+
)]
55+
[regex]
56+
$envFilter,
57+
58+
[Parameter(
59+
Mandatory = $False,
60+
ValueFromPipeline = $True,
61+
ValueFromPipelineByPropertyName = $True
62+
)]
63+
$varScope = "Script"
64+
)
65+
66+
begin
67+
{
68+
$envFile = "$($envFileName).$($envFileExt)"
69+
$currentLocation = Get-Location
70+
$envFilePath = Join-Path -Path $currentLocation -ChildPath $envFile
71+
72+
if (Test-Path -Path $envFilePath -PathType Leaf) {
73+
# Convert path only if the file exists
74+
$envFilePath = Convert-Path $envFilePath
75+
76+
# Dot source env override if file exists
77+
. $envFilePath
78+
}
79+
else {
80+
Write-Verbose -Message "Override file does not exist at $envFilePath"
81+
}
82+
#Continue
83+
}
84+
85+
86+
process {
87+
<#
88+
$envFilter = '^\s*#'
89+
$envContent = Get-Content -Path $envFilePath | Where-Object { $_ -notmatch $envFilter }
90+
foreach ($line in $envContent) {
91+
# Skip commented lines that start with `#`
92+
if ($line -match $envFilter) {
93+
continue
94+
}
95+
96+
$line = $line.Trim()
97+
if (-not [string]::IsNullOrWhiteSpace($line) -and $line -match '^(.*?)=(.*)$') {
98+
$varName = $matches[1]
99+
$varValue = $matches[2]
100+
Write-Host "Setting override variable: $varName=$varValue"
101+
Set-Variable -Name "$varName" -Value "$varValue" #-Force -Scope $varScope
102+
}
103+
}
104+
#>
105+
106+
<#
107+
# Check if the variable $p_apiKey exists from override.ps1 file, otherwise ask the user for their API key
108+
if (-not (Test-Path variable:apiKey)) {
109+
# If it doesn't exist, ask the user for input
110+
$apiKeySecure = Read-Host "Please enter your DBPool Personal API Key" -AsSecureString
111+
# Convert the secure string to a plain text string
112+
$p_apiKey = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($apiKeySecure))
113+
114+
# Set environment variable using [Environment]::SetEnvironmentVariable
115+
[Environment]::SetEnvironmentVariable("apiKey", $p_apiKey, "Process")
116+
117+
# Clear plaintext variable
118+
$p_apiKey = $null
119+
# Dispose of the SecureString to minimize its exposure in memory
120+
$apiKeySecure.Dispose()
121+
}#>
122+
}
123+
<#end {
124+
return $envContent
125+
}#>
126+
}

0 commit comments

Comments
 (0)