PS Csv Line count is null after import a one line csv file - powershell

I try to import a csv file containing one header and one line of data.
The content of csv file:
hcode,scode,sname,Cui,Data,Denumire,Adresa
74489,!00001,tstvnd,19706741,2023-02-10,"test fiscal hist","Str. TEst "
$csvChkPrs= Import-Csv -Path $o_fsFileInput.FullName -Delimiter "," -Encoding UTF8
when calling the \
$csvChkPrs.Count
It Returns null.
I managed this as follows
$iRows= If ( ($null -ne $csvChkPrs) -and ($null -eq $csvChkPrs.Count)) {1} elseif ($null -ne $csvChkPrs) {$csvChkPrss.Count}
However trying to pass this variable to a function that expects as input an Collection.arraylist I get a conversion error reading that A PSCustomObject can not be converted to a Collection.ArrayList
I just used a repetitive structure to copy each item of the csv to he arraylist\
ForEach ($Line in $csvChkPrs) {$o_colChkPrs.Add($Line) |Out-null}
Any ideas how to overcome the error when getting just one line of data from Csv?

Related

Remove #{} from output and place in command

I am trying to figure out how to remove the #{} from the output of the $list coming from the CSV file.
I am trying to run the Command "Complete-DomainJoin -Identity $line -DagNumber 023" for each line inside the CSV file
#Complete-DomainJoin (MultipleObjects)
$csv = Import-Csv C:\Temp\DEPTComputers023DEPTComputers023.csv
foreach ($line in $csv) {
Complete-DomainJoin -Identity $line -DagNumber 023
}
When I run this powershell script it errors out because its placing the line item from the CSV into the command as #{xxxx}, from reading around it seems the common way to fix the issue is by adding -ExpandProperty variable but I have not found where to place it or I am not understanding how to implement it correctly.
If everything is in the first column with no header row, then you can try this:
# Name the first column
$csv = Import-Csv C:\Temp\DEPTComputers023DEPTComputers023.csv -Header 'ComputerName'
foreach ($row in $csv) {
# use the ComputerName property
Complete-DomainJoin -Identity $row.ComputerName -DagNumber 023
}
If there aren't any commas in the file at all, then just replace Import-Csv with Get-Content
the #{property=value} syntax means that your object has sub-properties, instead of being a single string

Save property with comma to CSV

I'm creating a CSV file in powershell.
Right now my code is:
Add-content -Path $filePath -Value "$($variable.Property)"
This works fine for the most part EXCEPT if the property contained a comma ie. "test, organization".
When I open up the CSV, the comma is taken with it (which is what i want) causing a extra separation. How do save "test, organization" to one column?
Referring to the documentation for Export-CSV, you will need to use a different delimiter, like a semi-colon.
When you read the CSV you should specify the delimiter as well: Import-CSV.
Try to quote your properties:
Add-content -Path $filePath -Value "'$($variable.Property)'"
Or use one of the built-in CSV commands, which automatically quote all values:
$foo.Bar | Export-Csv -Path $filePath
$foo.Bar| ConvertTo-Csv | Out-File -Path $filePath
If you just want to avoid issues with commas, you can change the delimiter between fields:
$foo | Export-Csv -Path $filePath -Delimiter '|'
Here is an article on how to use out-file or add-member with some cells of the row having commas in the variable values and some not.
https://imjustanengineer.blogspot.com/2022/01/so-youre-trying-to-use-powershell-out.html
Here is a code snippet, a more detailed explanation with a full working function is in the link. $outputArr is an array of all the lines of csv data you want to write to the csv. The loop checks each line to see if it contains commas inside of the individual cell entries and puts quotes around that entry if it does. If it does not, no adjustment is necessary and then a new array is appended to afterwards.
$index = 0;
foreach ($outputTemp in $outputArr)
{
if ($outputTemp.ToString().Contains(","))
{
$output += "`"$outputTemp`",";
}
else
{
$output += $outputTemp + ",";
}
$index++;
if ($index -eq $outputArr.Count)
{
if ($output.EndsWith(","))
{
$output = $output.Remove($output.Length - 1);
}
}
}
I found a diabolically simply answer after I opened a csv file in Excel and added text and commas to one column. When I saved, closed and reopened, the column still had all the words and commas properly formatted. So, then I opened the file in notepad++ and this is what I found:
column1text, column2text,"column3,text,with,commas"
In case it's not clear, and it took me a fair bit to recognize the little detail that makes all the difference, the opening double quote cannot have a space after the preceding comma.
column1text, column2text, "column3,text,with,commas"
splits all the words into separate columns because there is a space between
column2text, "column3,etc"
Take that space away
column2text,"column3,etc"
and everything within the double quotes stays in one column.
Example using active directory distinguishedName such as CN=somename,OU=Domain Controllers,DC=foo,DC=bar
$computers = get-adcomputer -filter *
foreach ($computer in $computers) {
$deviceName = $computer.Name
$dn = '"' + $computer.DistinguishedName + '"'
$guid = $computer.objectGUID
$lastLogon = $computer.LastLogonDate
$serialNumber = $computer.serialNumber
$whenCreated = $computer.whenCreated
"$guid, $lastLogon, $deviceName, $serialNumber, $whenCreated,$dn" | add-content "c:\temp\filename.csv"
}
It does not work if a space is added between $whenCreated, and $dn like so:
"$guid, $lastLogon, $deviceName, $serialNumber, $whenCreated, $dn" | add-content "c:\temp\filename.csv"
This took up an afternoon, so I hope this saves somebody some time and frustration.

How to extract specific fields from CSV file with data using PowerShell

I am trying to extract the specific fields with data from the CSV file, but when I do run the following script, I do get only the fields without data on it.
Tried PowerShell script and got the file, but it's empty.
$folderPath = 'D:\Data\Orignal\'
$folderPathDest = 'D:\Data\New\'
$desiredColumns = 'ID','TC', 'POINTS_AT','POINTS_DESC','SURVEYSENT'
Get-ChildItem $folderPath -Name | ForEach-Object {
$filePath = $folderPath + $_
$filePathdest = $folderPathDest + $_
Import-Csv $filePath |
Select $desiredColumns |
Export-Csv -Path $filePathDest -NoTypeInformation
}
I do expect that data should be exported as well with fields!
Here is an example data from where I am trying to extract fields. It's sample file, I have big dump.
ID;TC;POINTS_AT;POINTS_DESC;SURVEYSENT;STATUSCHECK;MEM_REQ;EXPIRY_DAT
1;true;5;SUBS;true;08.08.2018;true;20.12.2020
2;true;3;SUBS;true;08.08.2018;true;20.12.2020
3;false;2;SUBS;true;08.08.2018;false;20.12.2020
4;true;5;UNSUBS;true;08.08.2018;false;20.12.2020
5;true;1;UNSUBS;true;08.08.2018;true;20.12.2020
6;false;1;UNSUBS;true;08.08.2018;true;20.12.2020
Define ; as delimiter when calling Import-Csv. The default delimiter is , , so the cmdlet won't be able to split the different columns. Based on that, Select-Object won't find the given properties, and will return objects with empty properties.
Import-Csv:
Delimiter
Specifies the delimiter that separates the property values in the CSV file. The default is a comma (,).
Enter a character, such as a colon (:). To specify a semicolon (;) enclose it in single quotation marks.

Append text to certain values in text file with PowerShell

I have a CSV text file separated with ; and it's in the format as:
USER_EMPLOYEE_ID;SYSTEM1;USERNAME1
The first column is an identity and the following pairs of columns are user's account on different active directories. I have placed garbage data but the idea is there.
ay7suve0001;ADDPWN;ay7suve0001
AAXMR3E0001;ADDPWN;AAXMR3E0001
ABABIL;ADDPWN;ABABIL
ABDF17;ADDPWN;ABDF17;
ABKMPPE0001;ADDPWN;ABKMPPE0001
ABL1FL;ADDPWN;ABL1FL
AB6JG8E0004;ADDPWN;AB6JG8E0004;
ACB4YB;ADDPWN;ACB4YB
ACK7J9;ADDPWN;ACK7J9
ACLZFS;ADDPWN;ACLZFS;
ACQXZ3;ADDPWN;ACQXZ3
Now there is a requirement that I have to append a fixed string like #ADDPWN.com to all the USERNAME1 values. Some records are having a ; and some don't.
Is there a quick way to append the #ADDPWN.com to each line taking care of:
any ;
any already #ADDPWN.com
From PowerShell?
Import-Csv is your friend. The following should get you on the right track.
Import-Csv "import.csv" -Delimiter ';' |
foreach {
if ($_.username1 -notlike '*#ADDPWN.com') { $_.username1 += '#ADDPWN.com' }
$_
} |
Export-Csv "export.csv" -Delimiter ';'
This assumes the first line of your csv file is your header line. If it's not, you can pass -Header 'USER_EMPLOYEE_ID','SYSTEM1','USERNAME1' as another parameter to Import-Csv.
Export-Csv adds some extra stuff like quotes around parameters, so you may need to play with the output format if you don't want that.
For another explanation how this works, check out Changes last name, first name to first name, last name in last column CSV powershell
This was a solution that worked for me.........
#opens list of file names
$file2 ="F:\OneDrive_Biz\PowerApps\SecurityCameraVideoApp\file_list_names.csv"
$x = Get-Content $file2
#appends URl to beginning of file name list
for($i=0; $i -lt $x.Count; $i++){
$x[$i] = "https://analytics-my.sharepoint.com/personal/gpowell_analytics_onmicrosoft_com/Documents/PowerApps/SecurityCameraVideoApp/Video_Files/" + $x[$i]
}
$x
#remove all files in target directory prior to saving new list
get-childitem -path C:\_TEMP\file_list_names.csv | remove-item
Add-Content -Path C:\_TEMP\file_list_names_url.csv -Value $x

Powershell - search through CSV and return only rows with specific error

I'm trying to write a powershell script that returns only the rows that have a specific entry in one of the columns but struggling a bit.
The CSV has 2 relevant columns, the ID and the Error.
At the moment I have this:
$ImportFile = Import-csv X:\errorlist.csv
$Error = $userobject.Error
$ID = $userobject.ID
$ErrorMessage1 = "Error1"
foreach($test in $ImportFile)
{
$field1 = $test.Error
$field2 = $test.ID
Echo "$field1, $field2"
} Where-Object {$_.Error -like $ErrorMessage1}
However the echo still returns everything in the csv even with the Where-Object.
I'm trying to run a ForEach because ultimately where I have the echo I'm going to insert a SQL script that uses the ID information in the csv to fix specific errors. Therefore I think I need to keep the foreach to process each sql script in turn, unless anyone has a better idea?
Try this way, this will check for $ErrorMessage1 in the ID or Error columns:
Import-csv X:\errorlist.csv |
Where-Object {$_.Error -like "*$ErrorMessage1*" -or $_.ID -like "*$ErrorMessage1*"}
Filter the rows from the CSV before you run the SQL:
Import-Csv X:\errorlist.csv |
Where-Object { $_.Error -like $ErrorMessage } |
ForEach-Object {
# Don't use aliases in scripts, use the real cmdlet names. Makes maintenance easier.
Write-Host ('{0}, {1}' -f $_.Error,$_.ID)
# Run your SQL cmd here.
}
The foreach loop operates independent of the Where-object, so you all you're doing is dumping the contents of the CSV file to the console.
You can shorten this up a lot by just pumping the data through the pipeline. This will filter your CSV records down to just the ones that meet your criteria.
$ErrorMessage1 = "Error1"
$allerrors = Import-csv X:\errorlist.csv|where-object {$_.error -eq $ErrorMessage1}
$allerrors;