In fact, if you call a .ps1 file, by default any functions and variables declared within it are scoped privately within the script (this is referred to as “script scope”). Since you’re seeing both functions defined globally, I infer that you’re dot-sourcing SvcTest.ps1, i.e. invoking it like this
PS> . <path>\SvcTest.ps1
rather than calling it like this
PS> <path>\SvcTest.ps1
You have two options.
1. If your private function is only used by one other function in the script, you can declare the private function within the body of the function that uses it, and invoke the script by dot-sourcing it:
function Test-Service ([string] $url)
{
function isURI ([string] $address)
{
($address -as [System.URI]).AbsoluteURI -ne $null
}
if (-Not (isURI($url)))
{
Write-Host "Invalid URL: $url"
return
}
# Blah blah blah, implementation not important
}
2. (ed. This option does not work powershell 7.3.4, it should either be removed or fixed, see comment) – If the private function is needed by more than one other function within the script (or even if not, this is an alternative to the above), explicitly declare global scope for any functions that you want defined globally, and then call the script rather than dot-sourcing it:
function isURI ([string] $address)
{
($address -as [System.URI]).AbsoluteURI -ne $null
}
function global:Test-Service ([string] $url)
{
if (-Not (isURI($url)))
{
Write-Host "Invalid URL: $url"
return
}
# Blah blah blah, implementation not important
}
In either case, Test-Service will be defined in the global scope, and isURI will be restricted to the script scope.
* One thing that might confuse the issue here is that PowerShell only looks for executables in the path, not the current working directory, unless `.` has been added to the path (which is not the case by default). So, it’s typical in PowerShell when invoking scripts in the working directory to precede the script name with `.\`. Don’t confuse the `.` representing the working directory with the dot-sourcing operator. This calls a script:
PS> .\SvcTest.ps1
This dot-sources it:
PS> . .\SvcTest.ps1