想要使用 $env:computername 手动添加 PCName。我试图在导出的文件中添加 PCName 标头,而不对原始文件进行任何更改

想要使用 $env:computername 手动添加 PCName。我试图在导出的文件中添加 PCName 标头,而不对原始文件进行任何更改

想要在导出的 excel 中使用 $env:computername 手动添加 PCName。但出现以下错误。

$destinationPath= "C:\temp\Excelfile.csv"
$info = Import-Csv -Path "C:\kumar.csv" | 
    ?{ !([string]::IsNullOrEmpty($_.Parameter))}
    Select-Object -Property PCName, Parameter, Status |
        Sort-Object -Property Status |ConvertFrom-Csv

        $NewCSV = @"
$($info.PCName="$env.computername" -join ',')
$($info.Parameter -join ',')
$($info.Status -join ',')
"@ | ConvertFrom-Csv


$NewCSV |Export-Csv -Path $destinationPath

答案1

要将内容添加到您当前的内容中,只需这样做:

Clear-Host
@'
"Parameter","Version","Status"
"Windows 11","20H2","Compliant"
"Patching","NA","Compliant"
'@ | 
ConvertFrom-Csv | 
Export-Csv -Path 'D:\Temp\PCDetails.csv' -NoTypeInformation



Import-Csv -Path 'D:\Temp\PCDetails.csv' | 
Select-Object -Property @{
    Name       = 'PCName'
    Expression = {$env:COMPUTERNAME}
},
@{
    Name       = 'OSName'
    Expression = {$PSItem.Parameter}
},
@{
    Name       = 'OSVersion'
    Expression = {$PSItem.Version}
}, Status
# Results
<#
PCName OSName     OSVersion Status   
------ ------     --------- ------   
PC70   Windows 11 20H2      Compliant
PC70   Patching   NA        Compliant
#>

请注意,只需按照我的评论使用计算属性即可。

再次,只有一个记录,你可以非常快速和粗略地做到这一点非优雅方式:

Clear-Host
$PCHealthDetails = (
Get-Content -Path 'D:\Temp\PCDetails.csv' | 
Select-Object -Skip 1
) -join ',' | 
ConvertFrom-Csv -Header H0, H1, H2, H3, H4, H5 | 
Select-Object -Property @{
    Name       = 'ComputerName'
    Expression = {$env:COMPUTERNAME}
}, '*' 


[PSCustomObject]@{
    ComputerName        = $PCHealthDetails.ComputerName
    $PCHealthDetails.H0 = $PCHealthDetails.H2
    $PCHealthDetails.H3 = $PCHealthDetails.H5
}

# Results
<#
ComputerName Windows 11 Patching 
------------ ---------- -------- 
PC70         Compliant  Compliant
#>

请注意,由于您说/显示您想要的数据操作/布局,您不能将原始 CSV 与 Import-CSV 一起使用。

再次,您在这里给我们留下了很多猜测,因为不止一条记录,使用不同的 Windows 操作系统版本,那么这种方法就不起作用;因为标题横幅不会改变

Clear-Host
@'
"Parameter","Version","Status"
"Windows 11","20H2","Compliant"
"Patching","NA","Compliant"
"Windows 10","RollUp","Compliant"
"Patching","NA","Compliant"
'@ | 
ConvertFrom-Csv | 
Export-Csv -Path 'D:\Temp\PCDetails.csv' -NoTypeInformation

您最终必须做这样的事情来显示所有检查的记录和操作系统版本:

Clear-Host
(Get-Content -Path 'D:\Temp\PCDetails.csv' -ReadCount 3) -replace '"Parameter","Version","Status"' | 
ForEach{

    $PCHealthDetails = ($PSItem -Join ',') -replace '" "', '","' | 
    ConvertFrom-Csv -Header H0, H1, H2, H3, H4, H5

    [PSCustomObject]@{
        ComputerName = $env:COMPUTERNAME
        Version      = $PCHealthDetails.H0
        Status       = $PCHealthDetails.H2
        $PCHealthDetails.H3 = $PCHealthDetails.H5
    }
}
# Results
<#
ComputerName Version    Status    Patching 
------------ -------    ------    -------- 
PC70         Windows 11 Compliant Compliant
PC70         Windows 10 Compliant Compliant
#>

相关内容