从 powershell 脚本导出 CSV

CSV export from a powershell script

我在 powershell 中有一段代码用作“安装配方”。 我使用此脚本来检查 PC 的准备是否良好以及各种软件是否已正确安装。 Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force

If ((Test-Path "C:\Program Files-Zip") -eq $True) 
   {Write-Host " ~                 7-ZIP : Installation => OK!                  ~" -ForegroundColor Green}
else{Write-Host " ~                7-ZIP : Installation => NOK!                  ~" -ForegroundColor Red}
 
Sleep 3

If ((Test-Path "C:\Program Files (x86)\Adobe\Acrobat Reader DC") -eq $True) 
   {Write-Host " ~             Adobe Reader DC : Install => OK!                 ~" -ForegroundColor Green}
else{Write-Host " ~            Adobe Reader DC : Install => NOK!                 ~" -ForegroundColor Red}

exit

如果安装正常 (OK),那么它会生成一个值,我们存储该值然后导出到 .CSV 或 .XLSX 文件。如果安装不成功 (NOK),同上。

你是怎么做到的?

感谢您的帮助

一种方法是将每个 non-installed 软件的名称保存到一个数组中以供以后处理。

话虽这么说,但可以改进所讨论的测试路径。不要到处输入路径,而是将它们存储在一个集合中以便于处理。哈希 table 工作正常。像这样,

$ht = @{
"7-Zip" = "C:\Program Files-Zip"
"Adobe Reader DC" = "C:\Program Files (x86)\Adobe\Acrobat Reader DC"
"FooApp" = "C:\Program Files\FooApp"
}
$failedInstalls = @()
    
foreach($key in $ht.keys){ 
    if(test-path $ht[$key] ) {
        Write-Host " ~ $key : Installation => OK! ~" -ForegroundColor Green
    } else {
        Write-Host " ~ $key : Installation => NOK! ~" -ForegroundColor Red
        $failedInstalls += $key
    }
}
$failedInstalls

这里所做的是将软件名称和路径存储在散列中 table。因此,所有路径都位于一个中心位置。然后迭代集合并将每个缺失的软件添加到 $failedInstalls 数组。改变软件的数量是微不足道的,它只需要改变散列 table - 不需要每个软件的 if(test-path... 声明。

如何将数组导出为 XSLX 或 CSV 作为练习留给 reader。

VonPryz answer 中所示的哈希表来收集要测试的软件的名称和路径确实是处理此问题的最简单方法。

根据问题标题,您想要一个包含测试结果的 CSV 文件;不仅是彩色控制台输出。为此,您需要遍历软件列表并输出 objects 您收集在如下变量中:

# add as many items here as you would like to test
$software = @{
    "7-Zip"           = "C:\Program Files-Zip"
    "Adobe Reader DC" = "C:\Program Files (x86)\Adobe\Acrobat Reader DC"
}

# a template line for output to console
$message = ' ~ {0} : Install => {1}! ~'

# loop through the hashtable Keys
$result = $software.Keys | ForEach-Object {
    $installed = Test-Path -Path $software[$_]
    if ($installed) { $color = 'Green'; $success = 'OK' } 
    else { $color = 'Red'; $success = 'NOK' }
    # output to console
    Write-Host ($message -f $_, $success) -ForegroundColor $color
    # output an object to save as CSV
    [PsCustomObject]@{
        'Software'    = $_
        'Path'        = $software[$_]
        'IsInstalled' = $installed
    }
}

# output result to console as table
$result | Format-Table -AutoSize

# output result as CSV file
$result | Export-Csv -Path 'D:\Test\InstalledSoftware.csv' -NoTypeInformation

$result 在屏幕上的输出为 Table:

Software        Path                                           IsInstalled
--------        ----                                           -----------
7-Zip           C:\Program Files-Zip                               False
Adobe Reader DC C:\Program Files (x86)\Adobe\Acrobat Reader DC        True