How can I get autocomplete for objects created by dot-sourced PowerShell scripts?
Asked by
MellowCedar47
I'm writing CI/CD scripts in PowerShell and split larger scripts into separate .ps1 files to keep them organized. For example, a paths.ps1 script creates a $Paths PSCustomObject containing shared directories, and build.ps1 dot-sources that file before using $Paths.BuildRootDir, $Paths.SrcDir, and other properties. The code runs correctly, but the editor doesn't offer IntelliSense or property completion after typing $Paths. Is there a practical workaround for getting autocomplete on objects created this way?
Answers
PowerShell completion generally gets information either from the current session state or by statically analyzing the script. Static analysis usually canโt determine the properties of a variable assigned inside a dot-sourced script. One workaround is to dot-source paths.ps1 in the editorโs integrated PowerShell/debug console before working, which places $Paths into the session and allows completion there. Another option is to make paths.ps1 output the object instead of assigning it, then capture it in the consuming script, although runtime variables such as $PSScriptRoot can still prevent static analysis from resolving everything.
Reply to this answer
Make sure youโre testing completion in the PowerShell extensionโs integrated or debug terminal. Completion may be available there even when it doesnโt appear in a regular terminal session.
Reply to this answer
If the shared code is mostly functions rather than data objects, consider turning it into a PowerShell module. Put the functions in a .psm1 file and load the module from the standard module path. The editor can generally discover and complete exported functions like regular cmdlets.
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowCedar47: Dot-sourcing the file in the integrated console works well enough for my workflow. Thanks for explaining why the editor canโt infer the properties.