Home > database >  Look for a specific value in a csv file powershell
Look for a specific value in a csv file powershell

Time:11-22

so i'm kinda new to PS, I've spent the whole morning trying to figure this out and looking for similar questions/answers here and on Google.

Basically this is my script:

$value = $env:COMPUTERNAME
$csv =  Import-Csv -Path '\\UNC\PATH\file.csv'
$props =  'CsSystemFamily','CsDNSHostName', 'CsManufacturer' 


Get-ComputerInfo | Select-Object -Property $props | Export-Csv -Path $csv -NoTypeInformation -       Delimiter ';' -Append

i'm deploying this as GPO since i need to collect this specific data from some OU's. The thing is i want to check first if the computername exists or not in the CsDNSHostName column so that my script wont add the same computer twice.

Thanks in advance,

I've tried multiple things, but the last thing i found was this:

$value = $env:COMPUTERNAME
if ($file-contains $value) {

write-host 'Computer name already exists'
} else {
Get-ComputerInfo | Select-Object -Property $props | Export-Csv -Path $csv -NoTypeInformation -     Delimiter ';' -Append

}

this didn't semm to work since it would just skip if and go straight to else

CodePudding user response:

-contains is the right operator to use, but you must apply it to the array of CsDNSHostName property (column) values, which is easy to do, thanks to member-access enumeration:

$props =  'CsSystemFamily','CsDNSHostName', 'CsManufacturer' 
$csvFile = '\\UNC\PATH\file.csv'
$csv = Import-Csv $csvFile -Delimiter ';'

# $csv.CsDNSHostName returns an array of 
# all CsDNSHostName column (property) values.
if ($csv.CsDNSHostName -contains $env:COMPUTERNAME) {
  Write-Host 'Computer name already exists'
} else {
  Get-ComputerInfo | 
    Select-Object -Property $props |
    Export-Csv $csvFile -NoTypeInformation -Delimiter ';' -Append
}
  • Related