powershellpowershell-4.0dot-source

Include PS1-Data except script Itself


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.


Solution

  • Restructure your code as follows, by placing the following only in Caller.ps1:

    $connectionScriptName = 'Connect.ps1'
    Get-ChildItem $PSScriptRoot\Module\* -Include *.ps1 -Exclude $connectionScriptName | 
      ForEach-Object {
        Write-Host $_.Name
        . $_.FullName
      }
    
    . "$PSScriptRoot\Module\$connectionScriptName"
    
    • This first dot-sources all .ps1 files in the Module subdirectory except Connect.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 a try statement afterwards. See this answer for details.