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+ }
0 commit comments