Hello,
I wrote a script that essentially pulls up all the AWS Security Groups which contains port 22 or 3389 open to the world. The script runs good, however the output is split as a different file for each violation it finds. Here is my Code block:
foreach ($sg in $sgs) {
try {
#Description of Public Endpoints
$permission = ($sg.IpPermission | Where-Object { $_.FromPort -eq 3389 -or 22 }).Ipv4Ranges
if ($permission.CidrIp -eq "0.0.0.0/0" ) {
Write-Host "There is a rule for 3389 or 22 open to the world in: "$sg.GroupName" in $vpc"
$AccountName = Get-IAMAccountAlias
$DateTimeStamp = (Get-Date).ToString("yyyyMMdd_HHmmss")
$outfilepath = "C:\temp\OutFile_$AccountName_$DateTimeStamp.csv"
New-Object -TypeName PSCustomObject -Property @{
SecurityGroupName = $sg.GroupName
VpcName = (Get-EC2Vpc -VpcId $vpc | Where-Object {$_.Tags.Key -eq "Name"}).Tags.Value
AccountName = $AccountName
} | Export-Csv $outfilepath -NoTypeInformation -Append
}
Pretty sure it is due to foreach block which goes through every security group and creates csv output. How do I ensure all the values are put in a single outfile file rather than multiples?
Sample Output: