7

Can not dot source all PowerShell scripts from directory tried:

. .\*.ps1

Returns this:

>  : The term '.\*.ps1' is not recognized as the name of a cmdlet,
> function, script file, or operable program. Check the spelling of the
> name, or if a path was included, verify that the path is correct and
> try again. At line:1 char:3
> + . .\*.ps1
> +   ~~~~~~~
>     + CategoryInfo          : ObjectNotFound: (.\*.ps1:String) [], CommandNotFoundException
>     + FullyQualifiedErrorId : CommandNotFoundException
1
  • I wish . .\*.ps1 worked Commented Nov 7, 2017 at 17:22

3 Answers 3

13

Use Get-ChildItem to grab all *.ps1 files, then loop through them with ForEach-Object and dot-source them individually

$Path = "C:\Scripts\Directory"
Get-ChildItem -Path $Path -Filter *.ps1 |ForEach-Object {
    . $_.FullName
}

If you put the above in a script, and the script itself is located in $Path, make sure to exclude the file itself so as to avoid it recursively dot-sourcing itself over and over again:

$Path = "C:\Scripts\Directory"
Get-ChildItem -Path $Path -Filter *.ps1 |Where-Object { $_.FullName -ne $PSCommandPath } |ForEach-Object {
    . $_.FullName
}

Edit: jcolebrand - 2018-06-25

Used the above to define a folder called Functions under my executing script. Works just fine in PS5:

## Folder\myIncluder.ps1
## Folder\Functions\Some-Function.ps1          -included
## Folder\Functions\Some-Other-Function.ps1    -included
## Folder\Functions\Some-Other-Function.readme -not included
(Get-ChildItem -Path (Join-Path $PSScriptRoot Functions) -Filter *.ps1 -Recurse) | % {
    . $_.FullName
}

Figure this makes it easy for the next lazy person to just adopt the same structure :p

Sign up to request clarification or add additional context in comments.

2 Comments

If I add this command to a file, source it and execute, it hangs. By any chance, do you know how can I put this command in file such that it works?
That's because it recursively starts dot-sourcing itself, that can be fixed though, let me update the answer
3

This should work:

Get-ChildItem -Filter '*.ps1' | Foreach { . $_.FullName }

Comments

0

To achieve this, you can loop through all your PowerShell files, and source them:

foreach ($ps1 in (ls *.ps1)) {
    . $ps1.FullName
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.