When you want to fetch data from an API, you often need many scripts to prepare the various data in the way you want to process it. To avoid having to include the connection information for the API and, in my case, the MySQL database in every single script, there is a simple trick.
You can write these connections in a single script and call this script repeatedly from all other scripts.
The call is always the first line in every script in PowerShell:
. "$PSScriptRoot\Connect.ps1"
$PSScriptRoot
is the folder where the running script resides. This works the same way on Linux as it does on Windows.
Here is an example of what the Connect.ps1
script might look like:
# Set WoW API region and language
Set-WoWRegion -Region Europe -Language German
# API client ID and secret replaced with placeholders
$clientId = 'YourClientID'
$clientSecret = 'YourClientSecret'
Set-WoWApiAccessToken -clientId $clientId -clientSecret $clientSecret
# MySQL username and password replaced with placeholders
$MySQLUser = 'YourUsername'
$MySQLPW = 'YourPassword'
$MySQLCreds = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList ($MySQLUser, (ConvertTo-SecureString -String $MySQLPW -AsPlainText -Force))
# Connection configuration
$ConnectionName = 'MySQL'
# Establish connection to MySQL database
Open-MySqlConnection -Credential $MySQLCreds -ConnectionName $ConnectionName -Server localhost -Database wow
By adopting this approach, you save time and reduce redundancy, allowing you to focus on the core logic of your scripts. Modularizing connections keeps your workflow clean and efficient, making your scripts easier to maintain and scale.