모듈파일 안에는 보통 다음과 같이 파일을 로드해서 그 중 일부를 export하는 것이 일반적입니다.
Basic Loop
1
2
3
4
| $functionFileList = Get-ChildItem -Path "$PSScriptRoot\functions" -Name "*.ps1" -Recurse
foreach ($functionFile in $functionFileList) {
. ("$PSScriptRoot\functions\$functionFile")
}
|
exclude 설정
그 다음에는 Load 하고 싶지 않은 파일들이 보이기 시작합니다.
1
2
3
4
5
| $exclude = @("*.Tests.ps1")
$functionFileList = Get-ChildItem -Path "$PSScriptRoot\functions" -Name "*.ps1" -Recurse -Exclude $exclude
foreach ($functionFile in $functionFileList) {
. ("$PSScriptRoot\functions\$functionFile")
}
|
try-catch 설정
dot-sourcing하다가 실패하는 파일들이 생겨나기 시작합니다.
1
2
3
4
5
6
7
8
9
10
| $exclude = @("*.Tests.ps1")
# Write-Debug "PSScriptRoot: $PSScriptRoot "
$functionFileList = Get-ChildItem -Path "$PSScriptRoot\functions" -Name "*.ps1" -Recurse -Exclude $exclude
foreach ($functionFile in $functionFileList) {
try {
. ("$PSScriptRoot\functions\$functionFile")
} catch {
Write-Error -Message "Failed to import function $PSScriptRoot\functions\$functionFile : $_"
}
}
|
여기까지는 일반적인 흐름입니다. 그런데,
- utf8로 인코딩한 파일들이 sourcing되지 않기 시작합니다.
지금과 같은 시대에 utf8로 인코딩된 파일들이 로딩되지 않는다니요. - 거기다. 파일들이 많으면, 뭔가 로딩에 시간이 걸리기 시작합니다. Import-Module하는데 30초가 걸리는 경우가 있다고 합니다.
psm1 파일 내부의 최종적인 형태는 다음과 같습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| $exclude = @("*.Tests.ps1")
# Write-Debug "PSScriptRoot: $PSScriptRoot "
$functionFileList = Get-ChildItem -Path "$PSScriptRoot\functions" -Name "*.ps1" -Recurse -Exclude $exclude
foreach ($functionFile in $functionFileList) {
# Write-Debug "$PSScriptRoot\functions\$functionFile"
try {
. (
[scriptblock]::Create(
[io.file]::ReadAllText(
"$PSScriptRoot\functions\$functionFile",
[Text.Encoding]::UTF8
)
)
)
} catch {
Write-Error -Message "Failed to import function $PSScriptRoot\functions\$functionFile : $_"
}
}
|
레퍼런스