我已经创建了一个脚本,从Azure导出防火墙规则,它的工作完美,但我需要创建.csv与标题,即使没有数据。目前它正在创建一个空白文件。
``function create($path) {
$exists = Test-Path -path $path
Write-Host "tried the following path: $path, it" $(If ($exists) {"Exists"} Else {"Does not Exist!"})
if (!($exists)) { New-Item $path -itemType Directory }
}
# reading file contents
$subs_file = "C:\script\Subscriptions.xlsx"
$azSubs = Import-Excel $subs_file
$azSubs
$output_folder = "C:\audit-automation"
# creating folder for outputing data
create("$output_folder")
# New-Item $output_folder -itemType Directory
# iterating over subscriptions
ForEach ( $sub in $azSubs ) {
# sub
$azsub = $sub.Subscription
# app
$app = $sub.Application
$azsub
$app
# creating folder to save data for apps
# New-Item $output_folder\$app -itemType Directory
# setting config for azure
Set-AzContext -SubscriptionName $azsub
# FIREWALL RULES
$azNsgs = Get-AzNetworkSecurityGroup
# iterating over retrieved NSGs
$Output = ForEach ( $azNsg in $azNsgs ) {
#Export custom rules
Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $azNsg | `
Select-Object @{label = 'NSG Name'; expression = { $azNsg.Name } }, `
@{label = 'NSG Location'; expression = { $azNsg.Location } }, `
@{label = 'Rule Name'; expression = { $_.Name } }, `
@{label = 'Source'; expression = { $_.SourceAddressPrefix } }, `
@{label = 'Source Application Security Group'; expression = { $_.SourceApplicationSecurityGroups.id.Split('/')[-1] } },
@{label = 'Source Port Range'; expression = { $_.SourcePortRange } }, Access, Priority, Direction, `
@{label = 'Destination'; expression = { $_.DestinationAddressPrefix } }, `
@{label = 'Destination Application Security Group'; expression = { $_.DestinationApplicationSecurityGroups.id.Split('/')[-1] } }, `
@{label = 'Destination Port Range'; expression = { $_.DestinationPortRange } }, `
@{label = 'Resource Group Name'; expression = { $azNsg.ResourceGroupName } },
@{label = 'Subscription Name'; expression = { $azSub } }
}
# creating folder to save
# New-Item $output_folder\$app\firewall_rules -itemType Directory
create("$output_folder\$app")
$Output | Export-Csv -Path $output_folder\$app\$app-firewall_rules_data$((Get-Date).ToString("yyyy-MM-dd")).csv -Append`
2条答案
按热度按时间piwo6bdm1#
测试
$Output
变量是否包含任何内容-如果没有,则创建一个与实际输出对象形状相同的“虚拟对象”,并将其与ConvertTo-Csv
结合使用以生成标题:h4cxqtbf2#
你遇到的问题是,如果
$output
中没有对象,那么Export-Csv
就不能决定使用什么头文件,在这种情况下,你需要自己生成头文件文本文件......这比@MathiasRJessen的答案稍微复杂一些,但它的优点是您只需要在代码中声明一次头文件,而不必在
Select-Object
参数和$dummyObject
路径中保持同步...首先,我们将属性定义从
Select-Object
移到一个变量中...那么
Select-Object
就变成了一旦我们让它工作了,我们就可以重用
$csvColumns
变量,用这个函数生成头文件:示例用法:
如果
$output
是$null
,则可以将其写入文件: