I want to import .csv file in Powershell. It is only one line in the CSV, which is structured as follows: Text;Text;Text...
This is what i have tried before:
$folder_csv = 'C:\Users\Win_User\Desktop\Folder\CSV_Files'
$files = Get-ChildItem $folder_csv -File -Filter *.csv
foreach ($file in $files) {
$Split_content = $file.split(";")
$timestamp = $($Split_content[0])
$User = $($Split_content[1])
$PC = $($Split_content[2])
$Software = $($Split_content[3]).Substring(1)
}
Write-Host $timestamp + " " + $User + " " + $PC + " " + $Software
I get the following Error Message: "Method invocation failed because [System.IO.FileInfo] does not contain a method named 'split'" .
Is there a better way to imort a csv file and safe each value in a seperate varibale?
Thanks for your help.
Your example file is not containing a header so I guess that's your problem. Then you need to specify it manually when Importing the CSV file. This code works only for when you have one row, if you have multiple rows it will just overwrite the variables and keep the last one. But feel free to change that.
$Header = 'timestamp','User','PC','Software'
$data = Import-Csv -Path .\testcsv.csv -Delimiter ';' -Header $Header
foreach ($row in $data) {
$timestamp = $row.timestamp
$User = $row.User
$PC = $row.PC
$Software = $row.Software
}
$timestamp
$User
$PC
$Software
$Header = 'Name','Age','Profession'
$data = Import-Csv -Path F:\Temp\NoHeader.csv -Delimiter ',' -Header $Header
$data | select Name, Age, Profession
Related
I have been asked to create a script to put comma (,) after every word in csv cell using powershell. However the actual csv has not been shared with me due to some security reason.
I have created a test csv and tried to put comma (,) after every word (Screen shot 1). I am able to create the script and it is working 100% fine (Screen shot 2). However the actual file size is approx 250 MB. I am assuming if that file has 100s of columns, do I have to mention each column name in the script as I mentioned in the foreach loop. Is there any easy way to accomplish this task without mentioning each column name. Any help would be appreciated. Below is my script that is working fine:
$csv = Import-Csv -Path C:\temp\test.csv
$outcsv = Read-Host "Enter the name of the output csv"
$outfile = "$env:USERPROFILE\Downloads" + "" + $outcsv + ".csv"
$data = #()
foreach ($item in $csv) {
$col1 = $item.Name + ","
$col2 = $item.Location + ","
$col3 = $item.Company + ","
$col4 = $item.Profile + ","
$col5 = $item.Shift + ","
$Properties = [ordered]#{
'Name' = $col1
'Location' = $col2
'Company' = $col3
'Profile' = $col4
'Shift' = $col5
}
$data += New-Object -TypeName PSObject -Property $Properties
}
$data | Export-Csv -Path $outfile -NoTypeInformation
Screen shot 1:
Screen shot 2 with comma (,):
This is an easier way to go about it that could handle the logic dynamically by accessing the object's PSObject.Properties.
$outcsv = Read-Host "Enter the name of the output csv"
if(-not [System.IO.Path]::GetExtension($outcsv)) {
$outcsv = $outcsv + '.csv'
}
$outfile = Join-Path "$env:USERPROFILE\Downloads" -ChildPath $outcsv
Import-Csv -Path C:\temp\test.csv | ForEach-Object { $firstObject = $true } {
if($firstObject) {
# get the property names of the first object
$properties = $_.PSObject.Properties.Name
$firstObject = $false
}
# enumerate each property of the object
foreach($property in $properties) {
# update the value
$_.$property = $_.$property + ','
}
# output the updated object
$_
} | Export-Csv $outfile
I have a PowerShell script that creates a csv file and neatly separates all user input. I need the remaining output to be split across the two headers and I'm struggling to find out how. Tried lots of different code but had no luck.
$Devices = read-host -Prompt "Enter Full Device Name" | out-file 'C:\Users\Public\Desktop\Devices.csv' -Force
$Find = ", "
$Replace = "`n"
$Arrange = (Get-Content 'C:\Users\Public\Desktop\Devices.csv') -replace "$Find","$Replace" | Set-Content 'C:\Users\Public\Desktop\Devices.csv' -Force
$CSV = import-csv 'C:\Users\Public\Desktop\Devices.csv' -Header "Firstname","Lastname"
$CSV | Export-Csv -NoTypeInformation 'C:\Users\Public\Desktop\Devices.csv'
$import = Import-Csv 'C:\Users\Public\Desktop\Devices.csv'
This is the output I currently have in the CSV:
This is the output I am after:
Could almost do with a foreach loop as the first and last names are likely to change as these are inputted using a variable
any help is appreciated.
Export-Csv exports 1 column per distinct property of the input - so to get 2 columns, you need to pipe an object with 2 properties to Export-Csv.
# read device names, split into individual strings
$devices = Read-Host -Prompt "Enter Full Device Name(s)"
$devices = $devices -split ',\s*' |ForEach-Object Trim
# now create one object per device name
$records = $devices |ForEach-Object {
# start by splitting the string into 2 on the first `-`
$FirstName,$LastName = $_ -split '-',2
# now create the object
[pscustomobject]#{
FirstName = $FirstName
LastName = $LastName
}
}
# ... and finally, export to CSV
$records |Export-Csv 'C:\Users\Public\Desktop\Devices.csv' -NoTypeInformation
If you want to retain the - as part of the FirstName value, change this line:
$FirstName,$LastName = $_ -split '-',2
to:
$FirstName,$LastName = $_ -split '(?<=-)',2
Try this out. Since I don't know what your input file looks like there might be some redundant steps in there. Feel free to modify the code to remove any redundant lines if you feel like.
$Devices = read-host -Prompt "Enter Full Device Name" | out-file 'C:\Users\Public\Desktop\Devices.csv' -Force
$Find = ", "
$Replace = "`n"
$Arrange = (Get-Content 'C:\Users\Public\Desktop\Devices.csv') -replace "$Find","$Replace" | Set-Content 'C:\Users\Public\Desktop\Devices.csv' -Force
$CSV = import-csv 'C:\Users\Public\Desktop\Devices.csv' -Header "Firstname","Lastname"
$X = $CSV | select -Skip 1
$y = $x -replace '-','-,' # this adds a comma so that the values are in different columns
$y | Export-Csv -NoTypeInformation 'C:\Users\Public\Desktop\Devices.csv'
$import = Import-Csv 'C:\Users\Public\Desktop\Devices.csv' -Header "Firstname","Lastname"
I need to add text to the end of the header in a text/csv file and then add other text (date) at the end of each line below the header. Adding the text part is working fine but it's the exporting to a csv that's not working as expected.
The expected output is (bold text is the added text);
"Folder Name","Files","Folders","Size","Comment","ReportDate"
"\\server\share\folder","2,029,756","819,527","1,785,490,958,735"," ","1/10/2020"
Instead I'm getting;
"Length"
"61"
"74"
"88"
"118"
$Path = "C:\temp\"
$files = Get-ChildItem $Path -filter '*.csv'
ForEach ($file in $files)
{
$datetmp = $file.PSChildName.Substring(0,10)
$datetmp = $datetmp.split("_")
$date = $datetmp[1] + "/" + $datetmp[2] + "/" + $datetmp[0]
$Fullpath = $Path + $file
[System.Collections.ArrayList]$content = Get-Content $Fullpath #| %{"$_," + $date}
$rptinsert = #()
for ($i=0; $i -lt ($content.Count); $i++)
{
if ($i -eq 0)
{
$rptinsert += $content[$i] + ",""ReportDate"""
}
else
{
$rptinsert += $content[$i] + ",`"$date`""
}
}
$Report = $Path + $file.PSChildName.Substring(0, 10) + "-FileSizes2.csv"
$rptinsert | Export-Csv -path $Report -Encoding ascii -NoTypeInformation
}
I'm sure there are shorter methods to perform the some of my lines as well, just not looking for that right now. ;-)
To use Export-Csv the way you are expecting, you need to be inputting objects with property/value pairs. You are piping in strings. The only property a string has is Length. I would use Import-Csv to read the files, modify the returned values, and then Export-Csv to output the changed objects. Below is a blueprint that will work:
$Path = "C:\temp\"
$files = Get-ChildItem $Path -filter '*.csv'
Foreach ($file in $files) {
$datetmp = $file.Name.Substring(0,10).Split('_')
$date = $datetmp[1],$datetmp[2],$datetmp[0] -join '/'
$content = Import-Csv $file | Add-Member -MemberType NoteProperty -Name 'ReportDate' -Value $date -PassThru
$content | Export-Csv -Path ($Path + $file.Name.Substring(0, 10) + "-FileSizes2.csv") -NoType
}
The output of Import-Csv is a collection of custom objects with property names that match the header line of the CSV file. Since it appears you want the same value added to every line of a CSV file, you can just run one Add-Member command. If each line needs a different value, then you will need to loop through each line and run an Add-Member command.
Add-Member allows for adding different member types to an object. In your case, you want to add a NoteProperty type with a value.
Once the updates are complete to one CSV's contents, you can pipe those results into Export-Csv. -NoType prevents an additional header line with type information from the output.
I need a script that generates usernames based on the first, last name and adds a couple of random numbers. How do I tell PowerShell to separate the columns and not write them all in one?
This is my current code. I was thinking maybe I can separate the names on the semicolon. And then select a part of them with substring and generate my number, put them together and voila.
$users = Import-Csv -Path C:\Users\username\Desktop\Namen.csv -Header "Vorname","Nachname","Username"
foreach ($user in $users) {
$user -replace ';', ' '
}
It seems that the only thing missing is the -delimiter ";" in your Import-Csv.
You can access/manipulate your data like so:
$csv_file = ".\Namen.csv"
$users = Import-Csv $csv_file -Delimiter ";" -Encoding "default"
foreach ($user in $users) {
$generated_username = $user.Vorname + $user.Nachname + "1234"
Write-Host "Vorname: " $user.Vorname
Write-Host "Nachname: " $user.Nachname
Write-Host "Username: " $user.Username
Write-Host "Generated username: $generated_username"
Write-Host ""
}
I've got a huge comma seperated CSV-list with IP-addresses of my network that I want to run queries against. Example of my CSV input:
172.168.0.1,172.168.0.2,172.168.0.3,172.168.0.4
Etc....
When I run the following code to test for the output:
$filepath = "c:\scripts\servers.csv"
$servers = Import-CSV $filepath -delimiter ","
Foreach ($server in $servers) {
write-host $server
}
I get no output, I think it's because there are no headers specified. I can obviously do a workaround and open the CSV-file and type in all the headers. Are there any other ways to solve this?
You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):
Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
Write-Host $_.IP1
Write-Host $_.IP2
...
}
$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
$IP
}
Get-content Filename returns an array of strings for each line.
On the first string only, I split it based on ",". Dumping it into $IP_Array.
$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
if ($IP -eq "2.2.2.2") {
Write-Host "Found $IP"
}
}
Solution is to change Delimiter.
Content of the csv file -> Note .. Also space and , in value
Values are 6 Dutch word aap,noot,mies,Piet, Gijs, Jan
Col1;Col2;Col3
a,ap;noo,t;mi es
P,iet;G ,ijs;Ja ,n
$csv = Import-Csv C:\TejaCopy.csv -Delimiter ';'
Answer:
Write-Host $csv
#{Col1=a,ap; Col2=noo,t; Col3=mi es} #{Col1=P,iet; Col2=G ,ijs; Col3=Ja ,n}
It is possible to read a CSV file and use other Delimiter to separate each column.
It worked for my script :-)
$filepath = ".\ADcomputerslist.csv"
$servers = Import-CSV $filepath -delimiter ","
Foreach ($entry in $servers) { write-host $entry.name }
also can replace stupid file with object.
$servers = Get-ADComputer -Filter * -Property * | Select-Object Name,OperatingSystem,OperatingSystemVersion,ipv4Address
Foreach ($entry in $servers) { write-host $entry.name }