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

时间:2016-07-19 21:59:24

标签: powershell

无法从目录中获取所有PowerShell脚本的源代码 尝试:

. .\*.ps1

返回:

>  : 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

3 个答案:

答案 0 :(得分:6)

使用Get-ChildItem抓取所有*.ps1个文件,然后使用ForEach-Object循环播放这些文件并单独点源

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

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

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

编辑: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
}

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

答案 1 :(得分:3)

这应该有效:

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

答案 2 :(得分:0)

要实现此目的,您可以遍历所有PowerShell文件并获取它们:

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