简体   繁体   中英

Export-CSV - (Powershell)

So i have the bottom scriptblock:

Import-csv C:\file_location.csv | foreach-object {
Get-WmiObject -computername $_.computername -class Win32_ComputerSystem | select username} | `
Select-Object computername, username | Export-CSV C:\file_location.csv -notypeinformation

the exported csv shows the Computer Name header but no actual computer and the username header is just fine. What and where am I missing something from?

Thank You!

select (which is an alias for Select-Object ) returns an object with only the properties you specify. So when you did your first select username you got an object with just the username; all other properties were discarded, so when the second Select-Object call runs, there is no computername for it to return.

The first select seems completely unnecessary there; just take it out and I think everything will work as expected.

EDIT: I see now that computername is not a property of the returned WMI object; it came from the CSV. Your ForEach-Object is only returning the WMI object, so the CSV row object is being discarded.

What you need to do is add the computername from the CSV to the WMI object, which you can do with Select-Object (with a computed column) or Add-Member :

Import-csv C:\file_location.csv | 
    ForEach-Object {
        Get-WmiObject -computername $_.computername -class Win32_ComputerSystem |
        Select-Object @{Name='ComputerName';Expression={$_.computername}},username
    } | 
    Export-CSV C:\file_location.csv -notypeinformation

Or:

Import-csv C:\file_location.csv | 
    ForEach-Object {
        Get-WmiObject -computername $_.computername -class Win32_ComputerSystem |
        Add-Member -NotePropertyName computername -NotePropertyValue $_.computername -Force -PassThru
    } | 
    Select-Object computername, username
    Export-CSV C:\file_location.csv -notypeinformation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM