Powershell script to use input from .txt or .csv to find a value in a 2nd .csv file - powershell

Group,
First time posting a question so please be patient. Attempting to use Powershell to read 1 .csv file and search a second .csv for specific data associated with what I passed from the first .csv file. Lets say that both files contain a column with a heading of 'name' with a list of PC names in that column. The 2nd CSV file in addition has a column with a heading named 'id' and that contains a unique ID associated with that PC name (and to complicate matters there may be duplicate PC Names but each one has a unique ID). I want to work through all the PC names in the first .csv file searching for the corresponding unique id of that PC name in the second .csv file and then set that as a variable so that I can perform some action against it. The code below is what I have so far, I'm manually providing the PC name as I cannot seem to get-content of the first file and pass it to the 2nd file. It will get the unique ID but I cannot seem to get it into a variable. Any help would be appreciated.
$computer = "T4763110"
$csv = Import-Csv "C:\Devices.csv"
$csv | Where-Object { $_.name -eq $computer } | % id
1st CSV file
First CSV file
2nd CSV file
Second CSV file

You forgot to specify a >Delimiter< in your import-csv. You can look your delimiter up, when you open your .csv file with the basic Microsoft-Editor.
Mine looks like this:
ID;Name
1;Alienware
2;Lexware
3;One
4;Chip
5;Stack
6;Linux
I made a new table named dev.csv for myself with following content:
When executing this code:
> $csv = Import-Csv "C:/Users/Desktop/dev.csv" -Delimiter ';'
> $csv
Output:
ID Name
-- ----
1 Alienware
2 Lexware
3 One
4 Chip
5 Stack
6 Linux
Then execute this:
> $csv | where-object {$_.name -eq "Alienware"} | % id
1
To save it to a variable, simply put brackets around it.
> $idvar = ($csv | where-object {$_.name -eq "Alienware"} | % id)
> $idvar
1

Related

Powershell remove a column from csv only if a word is present

I have a csv with columns A, B, C. I would like to import that to powershell and only on column C, remove any rows that have the word "Unknown" listed. If Column A or B has "Unknown", they stay, however, if Column C has it, the entire row gets deleted. Per the picture below, Row 4 would be deleted.
Can someone please provide a sample script to do this?
Thanks!
So, you have 3 problems you need to solve:
Import the data from the CSV file
Filter it based on the value of column C
Export the filtered data to a file again
To import, use the aptly named Import-Csv cmdlet:
$data = Import-Csv .\path\to\file.csv
Import-Csv will parse the CSV file and for each row it reads, it will output 1 object with properties corresponding to the column names in the header row.
To filter these objects based on the value of their C property, use the Where-Object cmdlet:
$filteredData = $data |Where-Object C -ne 'Unknown'
Where-Object will test whether the C property on each object does not have the value 'Unknown' (-ne = not equals), and discard any object for which that's not the case.
To re-export the filtered data, use the Export-Csv cmdlet:
$filteredData |Export-Csv .\path\to\output.csv -NoTypeInformation
You can also combine all three statements into a single pipeline expression:
Import-Csv .\path\to\file.csv |Where-Object C -ne 'Unknown' |Export-Csv .\path\to\output.csv -NoTypeInformation
This "one-liner" approach might be preferable if you're working on large CSV files (> hundreds of thousands of records), as it doesn't require reading the entire CSV file into memory at once.
$Data = Get-Content "C:\file.csv" | ConvertFrom-Csv
$Data | Where-Object {$_.C-ne 'Unknown'} | Export-Csv "C:\file_New.csv"

Copy Specific column from csv file to another file with specific word location using powershell

I am new to PowerShell its just been a day that I started using this, I need some help regarding building script for my model. These are the steps
I am taking file content and I have taken everything in different variable like:
$Test_Name, $Test_number, $Result and consequently imported the data from CSV into these variables:
Import-Csv .\result.csv | ForEach-Object {($Test_Result += $_."Test Result"),($Test_number +=$_."Test Number")
.... and so on
Now I have data into some powershell variables and now I want these variable content to be pasted to another file named output.txt/docs upon several specific parameters like %%PasteHereTestName%%, %%PasteHereTestNumber%%.
Can anyone guide me on this, I have tried several ways but it seems like I need some guidance.
**this will be used by Azure devops pipeline to copy the content from test file to output doc file..
Import the CSV into a variable and you can address each attribute directly, and write individual columns/attributes to a new CSV file by including the select-object statement
$Results = Import-csv c:\temp\testfile.csv
$results | select-object Column1, Column2, Column3 | export-csv C:\temp\proddata.csv

Reading Multiple Entry from CSV using PowerShell

I have a CSV file that contains multiple vendors (Cisco, Redhat, vmware..etc), I need a PowerShell script to read this column (vendor) and add separate column "Multiple1 or Multiple2" (Remark) if the CSV contains multiple entries of same vendors.
I have attached screen shot of the sample file.
I tried from end to get this done, but it didn't work.
Okay, after Spikeys last comment I had a go at guessing what he might want to achieve.
I created a CSV file:
Product,Template
Microsoft Windows,
RedHat Enterprise,
Apple Safari,
Microsoft Windows,
RedHat Enterprise,
RedHat Enterprise,
and then wrote the following script. It's commented and produces the following output:
Product Template
------- --------
Microsoft Windows Multiple2
RedHat Enterprise Multiple3
Apple Safari Multiple1
Microsoft Windows Multiple2
RedHat Enterprise Multiple3
RedHat Enterprise Multiple3
Code:
$Csv = Import-Csv -Path "C:\Book1.csv"
#Hastables have key - value pairs. Example "Microsoft Windows" = 1. Here 'Microsoft Windows' is the key and '1' is the value
[hashtable]$ProductCount = #{}
#Go through each line in the CSV. This returns the product name e.g. Microsoft Windows
ForEach ($Product in $Csv.Product)
{
#If there us no key for the current product in hashtable $Productcount, then add it with value 1
If ($ProductCount.Keys -notcontains $Product)
{
$ProductCount.Add($Product, 1)
}
#If the above does not apply, then increase the value (effectively the count) by 1
Else
{
$ProductCount[$Product] = $ProductCount[$Product] + 1
}
}
#Go through each row in the CSV file. Each row is returned as it's own object with a 'Product' and 'Template' property
ForEach ($Row in $Csv)
{
#Extract the count for the current product from hastable $ProductCount
$Count = $ProductCount[$Row.Product]
#Set the 'Template' property for the current row object to multipile + the count we got earlier
$Row.Template = "Multiple$Count"
}
#Save the changes to the CSV file as a new CSV. You can also overwrite your old one if you like
$Csv | Export-Csv -Path "C:\Book2.csv"
I don't quite understand your question, but here are some techniques I find useful when working with CSV files.
Example CSV:
Name,City
Bob,BlackPool
Alice,Dover
Carl,Manchester
Presume you assign the CSV file to a variable like so
$CSV = Import-CSV -Path "C:\Stuff.csv"
1. You can access all rows in a column by typing the variable dot(.) column header, so
$CSV.Name
returns:
Bob
Alice
Carl
2. To access a row in a CSV file you need to use indexing, so
$CSV[1]
returns:
Name City
---- ----
Alice Dover
3. An easy way to replace a property of a specific row is to filter it using Where-Object. Say I want to change Carl's city to London.
$($CSV | Where-Object {$_.Name -like "Carl"}).City = "London"
Here is what happens:
What's in the parentheses is processed first, so we are selecting a row where the Name property is like "Carl" (You can use wilcard here, so "Ca*" would have worked too). Then, outside of the parentheses, we are setting the city property to "London".
Note: $_ represents the data currently in a pipeline, in this case that's the row containing Carl.
There is more stuff to know, but this might help you the most.
Don't forget to save your changes by using the Export-CSV cmdlet!
$CSV | Export-CSV -Path "C:\new.csv" -NoTypeInformation

powershell incremental lines in csv

I have a csv journal file like this:
and I would like to add incremental line numbering like the below:
Can anyone suggest the easiest way to do this through PowerShell so that every time a file is generated it will automatically insert a column called LINENUMBER and insert the incremental numbering?
All help greatly appreciated.
You could do this:
Import-CSV SomeFile.csv | Select *,LINENUMBER | ForEach-Object -Begin { $Line = 1 } {
$_.LineNumber = $Line++
$_
} | Export-CSV SomeFile.csv
Uses Import-CSV to load the CSV file as a PowerShell object and then Select-Object to return all of it's properties and add an additional property named 'LINENUMBER'
Iterates through each line of the CSV, incrementing the new LINENUMBER property with a counter variable named $Line (which is set to 1 before it iterates).
Exports the result as CSV overwriting the original (or you could here redirect it to a new file name).
Note that the new column will be last. You could make it the first column by changing the Select part to Select LINENUMBER,*. If you want it to sit somewhere in the middle that would be slightly more complicated (and likely involve knowing what headers the input file had in advance).

Using PowerShell to get a count from a csv file and export to csv

I have a csv file with name,id,age. I have imported it properly and am looking for a count of all names that are null(empty).
I have this so far:
#(Import-Csv C:\Mine\Desktop\f1.txt | Where-Object {$_.name -eq ""}).Count
This prints out the correct number of empty names into the prompt, but if I export it, nothing shows up in the txt file.
#(Import-Csv C:\Mine\Desktop\f1.txt | Where-Object {$_.name -eq ""}).Count | Export-Csv C:\Mine\Desktop\tests.txt -notype
So it shows the correct number in the command prompt, but when I try to export it, it creates the .txt but it is empty. Any help would be appreciated. Also, if I wanted to know how many null entries their are in the entire CSV (from name,id,age). Would the best way be to do this line
Where-Object {$_.name -eq ""} but change $_.name every time? Or is there a shorter version?
The problem is that you are taking an integer (the count of entries with blank names) and trying to export a CSV. Export-CSV expects you to have an object, or array of objects with properties that it can convert to a table in CSV format, with property names as the header row, and values below that for each object.
What you want is to just output that value to a file, so try replacing Export-CSV with Set-Content (and remove the -notype) to set the content of the file you specify to the number delivered by your command.