How to iterate through csv and look for column name in powershell?

I have a csv that has 3 columns:

  Name/desc       Start IPv4 address          End IPv4 Address

Ultimately I need to loop through this csv and execute the following in powershell:

  New-AzSqlServerFirewallRule -ResourceGroupName "ResourceGroup01" -ServerName "Server01" -FirewallRuleName "Rule01" -StartIpAddress "192.168.0.198" -EndIpAddress "192.168.0.199"

I’m familiar with python but have struggled with doing this in powershell. Here is what I have so far:

$csv = Import-Csv -Path "C:\Pathtofile"

foreach($line in $csv)
{ 
    $properties = $line | Get-Member -MemberType Properties
    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
        $columnvalue = $line | Select -ExpandProperty $column.Name
        if($column.name  -contains 'Start'){
        #write($column)
            write($column.name)
        }
        write($column.name.GetType())
    }
} 

My thought was to first check if the column name contains either ‘Start’, ‘End’ or ‘Name’, but my if statement doesn’t work. I suspect it’s because I’m trying to compare an object to a string. When I write the GetType() I see this for each line:

  IsPublic IsSerial Name                                     BaseType                                                                                                                                                             
  True     True     String                                   System.Object 

I don’t know if that means it’s a string or what? It appears like it’s a string but I don’t understand why my if statement isn’t working.

I think if I could get past this I could probably set the variables and use them in the AzSqlServerFirewallRule command.

>Solution :

Assuming the column names are exactly named Name/desc, Start IPv4 address and End IPv4 Address and you want to execute the New-AzSqlServerFirewallRule you can simplify your code to loop through each object in $csv and from there you can use dot notation to reference the values of each property:

$csv = Import-Csv -Path 'C:\Pathtofile'

foreach ($object in $csv) {
    $newAzSqlServerFirewallRuleSplat = @{
        ResourceGroupName = 'ResourceGroup01'
        ServerName        = 'Server01'       
        FirewallRuleName  = $object.'Name/desc'
        StartIpAddress    = $object.'Start IPv4 address'
        EndIpAddress      = $object.'End IPv4 Address'
    }

    New-AzSqlServerFirewallRule @newAzSqlServerFirewallRuleSplat
}

This code also uses splatting to bind the parameters to your command for better readability.

Leave a Reply