Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Source all powershell scripts from a directory

Tags:

powershell

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
like image 337
Alex Avatar asked Jul 19 '16 21:07

Alex


2 Answers

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

like image 190
Mathias R. Jessen Avatar answered Sep 22 '22 14:09

Mathias R. Jessen


This should work:

Get-ChildItem -Filter '*.ps1' | Foreach { . $_.FullName }
like image 24
Martin Brandl Avatar answered Sep 22 '22 14:09

Martin Brandl