Search code examples
powershellpowershell-4.0

how to run a list of functions in a foreach loop in powershell?


I have a text file that lists several functions for doing recuring checks on SQL server. I have tested each function and verified they work. I am writing a control script as a psm1 and to call all the functions, but they do not run. all I receive is a list of the functions on the host but none of the outputs that are writen within the functions. I am not sure what I am doing wrong. The section of code that I am having problems with is as follows:

$funcList = Get-Content $Home\Documents\WindowsPowerShell\CheckList.txt
foreach ($fl in $funcList) {
        Import-Module $Home\Documents\WindowsPowerShell\$fl\$fl.psm1
        $check = "$fl -ComputerName $ComputerName -UserName $UserName -Output_Path $Output_Path -SystemName $SystemName"
        $check
        }

I also tried to put all the parameters as a variable as

$params = "-ComputerName $ComputerName -UserName $UserName -Output_Path $Output_Path -SystemName $SystemName"
$check = $fl + $params

I was able to get it to work listing each check like this:

if (!(Test-Path -Path "$Home\Documents\WindowsPowerShell\check1" )) {
        Import-Module $Home\Documents\WindowsPowerShell\check1\check1.psm1
        check1 -ComputerName $ComputerName -UserName $UserName -Output_Path $Output_Path -SystemName $SystemName
        Write-Host "check1 complete"} 

I have another script that places all the functions and checklist into the users powershell modules folders. the only other part is the params that are needed.

the checklist file can be txt or csv.


Solution

  • Functions has to be invoked using Function name and the parser should treat that string as function name. Whatever starts with single/double quotes are treated as strings in PowerShell.

    Use call operator & to call the function when the name is in a variable.

    $funcList = Get-Content $Home\Documents\WindowsPowerShell\CheckList.txt
    foreach ($fl in $funcList) {
            Import-Module $Home\Documents\WindowsPowerShell\$fl #no need to point to .psm1.
            & $fl -ComputerName $ComputerName -UserName $UserName -Output_Path $Output_Path -SystemName $SystemName"
    
            }