Include the same setting file only once

17/12/2012 11:18

We have many scripts (e. g. debug.ps1, debug2.ps1) with one shared settingsTest.ps1 file. We wanted to load settingsTest.ps1 file, but only when it's needed. Case was when file was not included yet, or was modified since last inclusion. We have four files here what use settingsTest.ps1 file. Files will work independently or together. If  we call single scripts in other ps1 file (, settingsTest.ps1 is loaded only once.

 

settingsTest.ps1


$siteUrl="http://server/site4"
write-host "==================================== Initial settings =============================="
write-host ""
write-host "siteUrl:                " $siteUrl


$settingsLoaded = $true

 

debug.ps1


if([string]::IsNullOrEmpty($location))
{
    $location = ($myinvocation.InvocationName | split-path -parent)
}
$modified=(get-childitem "$location\settingsTest.ps1").LastWriteTime
if(-not($settingsLoaded) -or ($modified -gt $env:settingsLoadedTime))
{
  
    #Include Settings file
    $env:settingsLoadedTime=Get-date
    . $location\settingsTest.ps1
   
}

#========================= Some code with site url ==================================
$listName="MyList"
write-host "List name is: "$listName " and is on site url: " $siteUrl

 

debug2.ps1

if([string]::IsNullOrEmpty($location))
{
    $location = ($myinvocation.InvocationName | split-path -parent)
}
$modified=(get-childitem "$location\settingsTest.ps1").LastWriteTime

if(-not($settingsLoaded) -or ($modified -gt $env:settingsLoadedTime))
{
    #Include Settings file
    $env:settingsLoadedTime=Get-date
    . $location\settingsTest.ps1
}

#========================= Other job ==================================

write-host "Some other job on site url: " $siteUrl

 

doAllTest.ps1

#do All test
if([string]::IsNullOrEmpty($location))
{
    $location = ($myinvocation.InvocationName | split-path -parent)
}
$modified=(get-childitem "$location\settingsTest.ps1").LastWriteTime
if(-not($settingsLoaded) -or ($modified -gt $env:settingsLoadedTime))
{
    #Include Settings file
    $env:settingsLoadedTime=Get-date
    . $location\settingsTest.ps1
}


write-host "Do all with site url: " $siteUrl

 . $location\debug.ps1
 . $location\debug2.ps1