PowerShell Foreach Loop Not Executing after multiple successful attempts

Chris

I've created the following PowerShell function to loop through the files in a user specified directory, marry the CCI values provided by the DISA FSO to the test IDs for each of the STIGs in the directory, and output that data to a .csv file of the users choosing.

The code worked in PowerShell ISE, then I tried it in PowerShell Terminal and it no longer works in either.

When I execute the function, it asks for and stores the parameters however the primary loop does not execute (comment below at line 23). While debugging, I saw that the foreach loop is skipped altogether. What do I need to do to make the foreach loop execute?

Things I've tried:

  • moving the param outside the function
  • calling the function before or after the function declaration (i.e., at the top or bottom of the script
  • removing the check for if the user specified output file exists
  • adding a variable after the output file exists check to display the params (this displays -- anything after is skipped)

Current function state:

Function CreateTestPlan {
    param (
        [Parameter(Mandatory = $true, HelpMessage="Filename of DISA STIG Benchmark XCCDF.xml file. Downloaded from IASE website. Usage: -BenchMarksDir")]
        [string]$BenchMarksDir,
        [Parameter(Mandatory = $true, HelpMessage="Filename of DISA CCI .XML file. Downloaded from IASE website. Usages: -CCIFile")]
        [string]$CCIFile,
        [Parameter(Mandatory = $true, HelpMessage="Filename of your choosing, ending in .csv. Usages: -OutFile")]
        [string]$OutFile,
        [Parameter(Mandatory = $true, HelpMessage="Determines output of control numbers and selection. Usages: -CCIFilter + NIST SP 800-53, NIST SP 800-53 Revision 4, NIST SP 800-53A")]
        [ValidateSet("NIST SP 800-53","NIST SP 800-53 Revision 4","NIST SP 800-53A")]
        [string]$CCIFilter
    )

    if (![System.IO.File]::Exists($OutFile))
    {
        New-Item -ItemType file $OutFile -EA Stop
    }
    ElseIf([System.IO.File]::Exists($OutFile))
    {
        Clear-Content $OutFile -EA Stop
    }

    Foreach ($file in $files) #Loop does not execute
    {
        [xml]$Stigx = Get-Content -Path $file.FullName -EA Stop
        [xml]$CCIx = Get-Content -Path $CCIFile -EA Stop

        # start by parsing the xccdf benchmark
        if($Stigx){
            $StigCollection = @()
            # loop through the xccdf benchmark collecting data into an object collection
            $StigName = $Stigx.Benchmark.title
            #loop through each group in the stig
            foreach ($group in $StigX.Benchmark.Group){
                # create a new PSObject collecting and stripping out as required.
                $STIG = New-Object -TypeName PSObject -Property ([ordered]@{
                    GroupID = $group.id
                    RuleTitle = $group.Rule.title 
                    Severity = $group.Rule.severity
                    VulnerabilityDetails = $($($($group.Rule.description) -split '</VulnDiscussion>')[0] -replace '<VulnDiscussion>', '')
                    Check = $group.Rule.check.'check-content'
                    Fix = $group.Rule.fixtext.'#text'
                    ControlIdentifier = $group.Rule.ident.'#text' -join "`r`n"
                    Control = $null # control is null as it will be added from the CCI List
                    StigName = $StigName
                })
                $StigCollection += $STIG
           }# close foreach
        }# close if
        # loop through the Stig Collection updating the Control information pulled from the U_CCI_List.xml
        foreach($StigObj in $StigCollection){
            foreach($CciItem in $CCIX.cci_list.cci_items.cci_item){
                if($CciItem.Id -EQ $StigObj.ControlIdentifier){
                    # filter the control version by the title
                    if($CciItem.references.reference.title -EQ $CCIFilter){
                        $StigObj.Control = $CciItem.references.reference.index -join "`r`n"
                    }
                }
            }
        }
        $StigCollection | Select-Object -Property 'StigName', 'GroupID', 'Control', 'Check' | Export-Csv $OutFile -Append -NoTypeInformation
    }
}

Because adding the test files here caused my browser to crash, I'm providing links to where the necessary parameter files may be downloaded:

Benchmarks: General Operating System STIG CCI Matrix: DISA FSO CCI

Example Usage and No Errors are being recieved: No Errors and Example Usage

vrdse

The variable $files is never set, thus it must be $null (emtpy). The foreach-loop tries to go through every element in $files, which is nothing. The loop is not realy skipped, there is just nothing to iterate on.

If you want to iterate through all files in $BenchMarksDir, you would have to enumerate all files in there, first.

$files = Get-ChildItem -Path $BenchMarksDir -File

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

PowerShell/CLI: "Foreach" loop with multiple arrays

Add a delay after executing each iteration with forEach loop

Javascript else loop executing after if loop executes

Codeigniter multiple foreach loop

Iterate through the foreach loop array only after the ajax request is successful

Promise after forEach loop

Executing a callback function after .forEach finishes

Same thread created inside foreach loop is executing multiple times

javascript promise after foreach loop with multiple mongoose find

ForEach with Multiple Variables - Powershell

Foreach loop is not working in PowerShell

Nested foreach loop in powershell

Powershell foreach executing after pause

C# foreach loop not executing

How to break Foreach loop in Powershell?

Loading a pickeld file using pickle.load() fails after some successful attempts

Powershell - Variables and foreach loop

Powershell : ForEach Loop

TYPO3 login attempts not successful after migration

Executing statements after a successful asynchronous request in a try/catch block

Executing multiple Bash commands after OR

Can you have multiple IN conditions in a PowerShell ForEach loop?

powershell stdout/stderr during executing (.foreach{})

Powershell calls another PS1 in loop finishes after first foreach loop run completes

Multiple Foreach Loop Codeigniter

Multiple sheets for ForEach Loop

Why is my conditional statement not executing multiple times in a foreach loop? PHP

How to break while loop after 5 attempts?

else block not executing after successful execution of if/elif blocks