如何从目录中获取所有PowerShell脚本

Ale*_*lex 5 powershell

无法从目录尝试点源所有PowerShell脚本:

. .\*.ps1
Run Code Online (Sandbox Code Playgroud)

返回此:

>  : 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
Run Code Online (Sandbox Code Playgroud)

Mat*_*sen 6

Get-ChildItem抢的所有*.ps1文件,然后通过他们循环使用ForEach-Object和点源他们的个人

$Path = "C:\Scripts\Directory"
Get-ChildItem -Path $Path -Filter *.ps1 |ForEach-Object {
    . $_.FullName
}
Run Code Online (Sandbox Code Playgroud)

如果您将上述内容放在脚本中,并且脚本本身位于其中$Path,请确保排除文件本身,以避免它一遍又一遍地递归点源:

$Path = "C:\Scripts\Directory"
Get-ChildItem -Path $Path -Filter *.ps1 |Where-Object { $_.FullName -ne $PSCommandPath } |ForEach-Object {
    . $_.FullName
}
Run Code Online (Sandbox Code Playgroud)

编辑:jcolebrand - 2018-06-25

使用上面的方法在我的执行脚本下定义一个名为Functions的文件夹.在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
}
Run Code Online (Sandbox Code Playgroud)

图这使得下一个懒人很容易采用相同的结构:p