It's unclear why you want this and I'd probably solve it another way, but to answer your question, you can try the sample below.
Remember to use literal strings (single quotes) for values with a leading $
to avoid them being treated as a variable. If not, PowerShell will try to replace the variables with it's value (or nothing if it's not defined), which means that Check-Variables
won't get the variable names. The following solution accepts both 'a'
and '$a'
.
Var.ps1
$a = "aa"
$b = "bb"
Check.ps1
#Dot-sourcing var.ps1 which is located in the same folder as Check.ps1
#Loads variables into the current scope so every function in Check.ps1 can access them
. "$PSScriptRoot\var.ps1"
function Check-Variables {
foreach ($name in $args) {
#Remove leading $
$trimmedname = $name -replace '^\$'
if(-not (Get-Variable -Name $trimmedname -ErrorAction SilentlyContinue)) {
Write-Host "ERROR: Variable `$$trimmedname is not defined"
}
}
}
Check-Variables '$a' "b" '$c'
Demo:
PS> C:\Users\frode\Desktop\Check.ps1
ERROR: Variable $c is not defined