How can I get autocomplete for objects created by dot-sourced PowerShell scripts?

0
8
Asked By MellowCedar47 On

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?

3 Answers

Answered By CopperLynx22 On

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.

Answered By QuietMaple63 On

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.

Answered By BrightHarbor8 On

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.

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.