3

From a PowerShell program, I can "dot source" another PowerShell program. i.e I can execute it as if it were written inside the first one.
Example:

Write-Host 'before'
. MyOtherProgram.ps1
Write-Host 'after'

MyOtherProgram in 'included' inside the main program, exactly as if its content had been copy/pasted.

The problem is: I can only dot source a filename finishing with .ps1
I can't with MyOtherProgram.lib or MyOtherProgram.whatever

Anyone have a method to dot source a PowerShell script not ending with .ps1 ?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Gregory MOUSSAT
  • 832
  • 4
  • 13
  • 22

2 Answers2

5

Another way would be using Invoke-Expression:

$code = Get-Content ./MyOtherProgram.lib | Out-String
Invoke-Expression $code
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
  • Invoke-Expression does not do the same thing as dot sourcing. You can not Invoke-Expression on a library of functions and be able to call those functions. – Joe B Jun 11 '20 at 17:07
1

I'm not aware if this is compiled into PowerShell or if it's configurable but one way to do it is just have your script temporarily rename it, import it and then rename it back.

Rename-Item C:\Path\MyScript.whatever C:\Path\MyScript.ps1
. C:\Path\MyScript.ps1
Rename-Item C:\Path\MyScript.ps1 C:\Path\MyScript.whatever
Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124