Rules/Test-ForUnimportedModuleFile.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function Test-ForUnimportedModuleFile
{
    param(
    [Parameter(ParameterSetName='TestModuleInfo',Mandatory=$true,ValueFromPipeline=$true)]
    [Management.Automation.PSModuleInfo]
    $ModuleInfo
    )
    
    process {
        $verbNounPairFiles = $ModuleInfo.Path | 
            Split-Path | 
            Get-ChildItem -Filter *-*.ps1 | 
            Select-Object -ExpandProperty Fullname
        
        $moduleScriptFiles = $moduleInfo.ExportedCommands.Values | 
            Where-Object { $_.ScriptBlock }  | 
            ForEach-Object {$_.ScriptBlock.File } 
                
        $missingFiles = 
            if ($moduleScriptFiles -and $verbNounPairFiles) {
                Compare-Object -ReferenceObject $verbNounPairFiles -DifferenceObject $moduleScriptFiles | 
                Where-Object { $_.SideIndicator -eq '<=' } |
                Select-Object -ExpandProperty InputObject
            } else { @() }

        if ($missingFiles) {            
            $missingFileNames = $missingFiles | 
                Split-Path -Leaf
            
            if ($moduleInfo.Path -like "*.psm1") {
                $lines = [IO.File]::ReadAllLines($moduleInfo.Path)                
            }    
            
            $missingFileNames = $missingFileNames | 
                Where-Object {
                    foreach ($l in $lines) {
                        if ($l -like "*$_*") {
                            return
                        }
                    }
                    $true
                }
            
            if ($MissingFileNames) {
                Write-Error -Message "$ModuleInfo does not import some .ps1s in the directory. The files are: $($missingFileNames -join ',') " -ErrorId "ScriptCop.UnimportedModuleFiles" -TargetObject $missingFileNames  -Category "NotInstalled"                                 
            }
        }
    }
}