I have 3 scripts in the following directories:
C:\PS
- Caller.ps1
C:\PS\Module
- Connect.ps1
- Statusbar.ps1
Caller.ps1
and Connect.ps1
contains the following code:
Set-Location $PSScriptRoot.Replace("\Module","")
#### not working ####
Get-ChildItem ".\Module" | Where {$_.Name -like "*.ps1"}|Where {$_.Name -notlike $MyInvocation.MyCommand} | ForEach {
Write-Host $_.Name
. .\Module\$_
}
The problem is that Connect.ps1
calls itself in a loop.
Normally I'd like Caller.ps1
to call Connect.ps1
with all other *.ps1
scripts except Connect.ps1
.
Does anyone have a solution for me?
Thanks.
Restructure your code as follows, by placing the following only in
Caller.ps1
:This first dot-sources all
.ps1
files in theModule
subdirectory exceptConnect.ps1
...... and then invokes the latter.
Note that the current location is not changed in the code above. Doing so is best avoided in PowerShell scripts, because it affects the entire session. If you do need to change it, save the previous location first and restore it in the
finally
clause of atry
statement afterwards. See this answer for details.