如何解决从Powershell脚本导出CSV
我在powershell中有一段代码,可以用作“安装配方”。 我使用此脚本来检查PC的准备工作是否正确,以及各种软件的安装是否正确。 Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force
If ((Test-Path "C:\Program Files\7-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),则同上。
您如何做到的?
感谢您的帮助
解决方法
一种方法是将每个未安装的软件的名称保存到一个数组中,以供以后处理。
话虽如此,测试路径可以改进。与其在各处输入路径,不如将它们存储在一个集合中以便于处理。哈希表工作正常。像这样
$ht = @{
"7-Zip" = "C:\Program Files\7-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
这里所做的是将软件名称和路径存储在哈希表中。因此,所有路径都位于一个中央位置。然后,对该集合进行迭代,并将每个缺少的软件添加到$failedInstalls
数组中。更改软件数量是微不足道的,只需要更改哈希表即可-无需为每个软件都使用if(test-path...
语句。
作为练习,留给读者的是如何将数组导出为XSLX或CSV格式。
,VonPryz answer中所示的哈希表用于收集要测试的软件的名称和路径,确实是处理此问题的最简单方法。
在问题标题中,您需要一个包含测试结果的CSV文件;不仅彩色控制台输出。为此,您需要遍历软件列表,并输出收集在变量中的对象,如下所示:
# add as many items here as you would like to test
$software = @{
"7-Zip" = "C:\Program Files\7-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
的输出如表所示:
Software Path IsInstalled -------- ---- ----------- 7-Zip C:\Program Files\7-Zip False Adobe Reader DC C:\Program Files (x86)\Adobe\Acrobat Reader DC True
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。