Import-CSV: Reading CSV files with PowerShell

Run Import-Csv -Path .\file.csv to read a CSV file in PowerShell: each row becomes an object and each column header becomes a property you can filter, sort and loop through.

This guide covers the Import-Csv syntax, the differences between Windows PowerShell 5.1 and PowerShell 7, delimiters, custom headers and encoding, and real admin jobs driven by a CSV file: bulk Active Directory users, account lockouts, firewall rules and old user profiles.

How to read a CSV file in PowerShell with Import-Csv

Import-Csv treats the first line of the file as the column names unless you supply your own with -Header. Every value it returns is a string.

  1. Open Windows PowerShell or PowerShell 7 from the Start menu.
  2. Change to the folder that holds the file, for example Set-Location C:\Data.
  3. Read the file and store the rows in a variable: $rows = Import-Csv -Path .\users.csv.
  4. Show the rows as a table with $rows | Format-Table.
  5. Count the rows with $rows.Count.
  6. Read one column from every row with $rows.Name, replacing Name with a header from your file.

The built-in alias ipcsv works on every platform, so ipcsv .\users.csv does the same job in fewer keystrokes.

Import-Csv reads any CSV file, including files written by Export-Csv. You can run PowerShell as administrator when the file sits in a protected folder or the next command changes system settings.

Import-CSV: Reading CSV files with PowerShell
Pipe the imported rows to Format-Table to show every column as a table; each value Import-Csv returns is a string. (Image: Microsoft)

Import-Csv syntax and parameters

The default syntax is Import-Csv [[-Delimiter] <Char>] [-Path] <String[]> [-Header <String[]>] [-Encoding <Encoding>]. -Delimiter and -UseCulture cannot be used together, and neither can -Path and -LiteralPath.

Parameter What it does Notes
-Path File or files to read. You can also pipe a path string to Import-Csv Mandatory unless you use -LiteralPath
-LiteralPath Same as -Path, but no character is read as a wildcard Aliases PSPath and LP
-Delimiter Character that separates the values The default is a comma
-UseCulture Uses the list separator of the current culture Check it with (Get-Culture).TextInfo.ListSeparator
-Header Your own column names, which become the property names Delete the original header row first
-Encoding Text encoding of the file Default utf8NoBOM in PowerShell 7

Import-Csv returns PSCustomObject items. Because they are CSV copies of the original objects, PowerShell does not apply the formatting it uses for the real object type.

Import-Csv in Windows PowerShell 5.1 vs PowerShell 7

Windows 11 and Windows 10 include Windows PowerShell 5.1. You can install PowerShell 7 next to it, and the same Import-Csv command then behaves slightly differently.

Behaviour Windows PowerShell 5.1 PowerShell 7
Default -Encoding Default (the system's active code page, usually ANSI); a byte order mark in the file is detected utf8NoBOM
Encoding values ASCII, BigEndianUnicode, Default, OEM, Unicode, UTF7, UTF8, UTF32 Adds utf8BOM, utf8NoBOM, bigendianutf32 and, from 7.4, ansi
Code page numbers such as -Encoding 1251 Not accepted Accepted from PowerShell 6.2
W3C Extended Log File Format (IIS logs) Not supported Supported from PowerShell 6.0; #Fields: sets the column names
#TYPE line written by Export-Csv Present unless the file was exported with -NoTypeInformation Not written by default

Loop through CSV rows in PowerShell with ForEach-Object

A loop is how Import-Csv drives real work: one command per row, with the row's columns available as $_.ColumnName.

  1. Check the column names first with Import-Csv -Path .\servers.csv | Get-Member -MemberType NoteProperty.
  2. Pipe the rows to ForEach-Object: Import-Csv -Path .\servers.csv | ForEach-Object { "Checking $($_.ComputerName)" }.
  3. Replace the text inside the braces with the command you need, using $_.ComputerName wherever the value goes.
  4. For longer scripts, store the rows first and use a foreach statement: $rows = Import-Csv .\servers.csv then foreach ($row in $rows) { $row.ComputerName }.
  5. Run the loop with a harmless command such as Write-Output first, then swap in the command that makes changes.

Filter and sort CSV data in PowerShell with Where-Object

  1. Keep only matching rows: Import-Csv .\users.csv | Where-Object Department -eq 'Sales'.
  2. Use a wildcard match: Import-Csv .\users.csv | Where-Object -Property Title -Like '*manager*'.
  3. Sort the result: Import-Csv .\users.csv | Sort-Object -Property LastName.
  4. Pick the columns you want to see: Import-Csv .\users.csv | Select-Object -Property FirstName, LastName, Department.
  5. Save the filtered rows to a new file: Import-Csv .\users.csv | Where-Object Department -eq 'Sales' | Export-Csv .\sales.csv -NoTypeInformation.

Comparisons such as -gt and -lt compare text, not numbers, because every imported value is a string. The numbers section below shows how to convert them.

Filter CSV data in PowerShell with Where-Object and a -Like wildcard
Where-Object keeps only the rows whose TopicTitle matches the wildcard; use any column name from your own file. (Image: Microsoft)

Import-Csv with a semicolon or tab delimiter

Files saved in regions that use a comma as the decimal mark often separate values with a semicolon. Import-Csv needs to be told, or it puts each whole line into a single property.

  1. Open the file with Get-Content .\data.csv -TotalCount 3 and look at the character between values.
  2. For a semicolon, wrap it in single quotes: Import-Csv .\data.csv -Delimiter ';'.
  3. For a tab, use an escaped tab in double quotes: Import-Csv .\data.tsv -Delimiter "t"`.
  4. For a colon or another plain character, pass it directly: Import-Csv .\data.csv -Delimiter :.
  5. To match the file to your PC's regional list separator, use Import-Csv .\data.csv -UseCulture instead of -Delimiter.

Import-Csv without a header row using -Header

Some exports have no header line, so the first data row would become the property names. -Header supplies the names instead.

  1. Confirm the file starts with data, not names: Get-Content .\links.csv -TotalCount 2.
  2. Import it with your own names, each in single quotes: $links = Import-Csv .\links.csv -Header 'LinkID', 'TopicTitle'.
  3. Check the new property names with $links | Get-Member.
  4. Use the names as normal: $links | Where-Object -Property TopicTitle -Like '*alias*'.

If the file does have a header row, delete it before using -Header, or Import-Csv returns the old header as an extra data row.

Give fewer names than there are columns and the extra columns are dropped. Give more names and the extra properties are created empty.

Import-Csv -Header names checked with Get-Member as NoteProperty columns
The names passed to -Header become the property names, and every column is listed as a NoteProperty string. (Image: Microsoft)

Import-Csv encoding for UTF-8 and accented characters

Garbled names such as é in place of é mean the file was read with the wrong encoding.

  1. In Windows PowerShell 5.1, read a UTF-8 file with Import-Csv .\names.csv -Encoding UTF8.
  2. In PowerShell 7, read an ANSI file saved by an older program with Import-Csv .\names.csv -Encoding ansi (PowerShell 7.4 and later).
  3. For a specific code page in PowerShell 7, pass its number or name, for example -Encoding 1251 or -Encoding 'windows-1251'.
  4. For a UTF-16 file, use -Encoding Unicode in either version.
  5. Run Import-Csv again and check the problem rows with Format-Table.

Avoid utf7. PowerShell 7.1 and later print a warning when you use it.

Convert Import-Csv string values to numbers in PowerShell

Import-Csv stores every value as text, so '9' -gt '10' is true and a sort puts 100 before 20.

  1. Cast the value inside the filter: Import-Csv .\disks.csv | Where-Object { [int]$_.FreeGB -lt 20 }.
  2. Sort as numbers with a script block: Import-Csv .\disks.csv | Sort-Object { [int]$_.FreeGB }.
  3. Add a converted column for later use: Import-Csv .\disks.csv | Select-Object Name, @{Name='FreeGB'; Expression={[int]$_.FreeGB}}.
  4. Use [double] instead of [int] when the column holds decimals.

How to install RSAT (Remote Server Administration Tools) for Import-Csv AD scripts

The Active Directory cmdlets used in the next sections (New-ADUser, Search-ADAccount, Unlock-ADAccount) come with RSAT. RSAT installs only on Windows 11 or Windows 10 Pro and Enterprise, and you need administrator rights. Once it is in, Get-ADUser queries work from the same window.

  1. On Windows 11, select Start, type Optional Features and select Add an optional feature.
  2. Select View features, search for RSAT: Active Directory, select the AD DS and AD LDS tools, select Next, then Install.
  3. On Windows 10, open Optional Features, select Add a feature, search for the same tool and select Install.
  4. To use PowerShell instead, run PowerShell as administrator and list the tools: Get-WindowsCapability -Online | Where-Object Name -like 'RSAT*'.
  5. Install the AD tools: Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0.
  6. Wait for the result to show Online : True, then open a new PowerShell window.

Bulk create Active Directory users from a CSV with Import-Csv and New-ADUser

Build a CSV with the headers Name, SamAccountName, UserPrincipalName and Path (the OU distinguished name). SamAccountName is required to create a user, and keep it to 20 characters or fewer for older systems.

$pw = Read-Host -AsSecureString 'Initial password'
Import-Csv -Path .\newusers.csv | ForEach-Object {
    New-ADUser -Name $_.Name -SamAccountName $_.SamAccountName -UserPrincipalName $_.UserPrincipalName -Path $_.Path -AccountPassword $pw -ChangePasswordAtLogon $true -Enabled $true
}

Read-Host stores one starting password as a secure string. Import-Csv reads each row, and New-ADUser creates the account in the OU named in the Path column, forces a password change at first sign-in and enables it.

You should see: The command prints nothing when every account is created. Check the result with Get-ADUser -Filter * -SearchBase '<OU distinguished name>'.

Accounts are never enabled without a valid password. If the password fails the domain policy, the user is still created but stays disabled until you set one with Set-ADAccountPassword.

How to find the source of account lockouts for users in a CSV file

Windows logs event 4740 in the Security log every time an account locks. On a domain controller, its Caller Computer Name field names the machine whose sign-in attempts caused the lockout. The CSV here holds one SamAccountName column of users to check.

$users = (Import-Csv -Path .\watchlist.csv).SamAccountName
Search-ADAccount -LockedOut -UsersOnly | Where-Object { $users -contains $_.SamAccountName }
Get-WinEvent -FilterHashtable @{ LogName='Security'; Id=4740 } | Where-Object { $m = $_.Message; $users | Where-Object { $m -match $_ } } | Select-Object TimeCreated, Message

The first line reads the user names into a list. Search-ADAccount returns the locked accounts that are on the list. Get-WinEvent, run on a domain controller, returns the 4740 lockout events whose text mentions one of those users.

You should see: Each event's message shows Account That Was Locked Out and Caller Computer Name. That computer is where to look for a saved old password, a mapped drive or a service using stale credentials.

After fixing the source, unlock the accounts from the same list: Import-Csv .\watchlist.csv | ForEach-Object { Unlock-ADAccount -Identity $_.SamAccountName }.

Event 4740 is recorded only when the Audit User Account Management subcategory is enabled.

Account lockout source in event 4740 showing the Caller Computer Name field
Event 4740 on a domain controller names the locked account and the computer whose sign-in attempts caused the lockout. (Image: Microsoft)

Managing Windows Firewall rules with PowerShell from a CSV file

A CSV lets you create the same set of rules on many PCs. Use the headers DisplayName, Direction, Protocol, LocalPort and Action, with values such as Inbound, TCP, 8080 and Allow. For one-off rules, the advanced firewall rules console does the same job by hand.

Import-Csv -Path .\rules.csv | ForEach-Object {
    New-NetFirewallRule -DisplayName $_.DisplayName -Direction $_.Direction -Protocol $_.Protocol -LocalPort $_.LocalPort -Action $_.Action
}

Each row becomes one rule. New-NetFirewallRule takes the direction (Inbound or Outbound), protocol, local port and action (Allow or Block) from the matching columns. Run it in PowerShell as administrator.

You should see: PowerShell prints the properties of each new rule. List them later with Get-NetFirewallRule -DisplayName 'Rule name', or all inbound rules with Get-NetFirewallRule -Direction Inbound -Enabled True.

To check that rules from the file exist on a PC, loop through the same CSV: Import-Csv .\rules.csv | ForEach-Object { Get-NetFirewallRule -DisplayName $_.DisplayName }.

How to delete old user profiles in Windows from a CSV list

Use Import-Csv to find which profiles on a PC match a list of departed users, then delete them from User Profiles. You need to be a member of the local Administrators group. The CSV holds one UserName column.

  1. Read the list: $gone = (Import-Csv -Path .\leavers.csv).UserName.
  2. Find matching profiles that are not in use and not owned by a system service: Get-CimInstance -ClassName Win32_UserProfile | Where-Object { -not $_.Loaded -and -not $_.Special -and $gone -contains (Split-Path $_.LocalPath -Leaf) } | Select-Object LocalPath, LastUseTime.
  3. Review the list and save it if needed by adding | Export-Csv .\profiles-to-delete.csv -NoTypeInformation.
  4. Select Start, search for Control Panel and open it.
  5. Set View by to Large icons and select System, then select Advanced system settings.
  6. Under User Profiles, select Settings.
  7. Select each profile from your list and select Delete.

Loaded is true while the user is signed in, and Special is true for profiles owned by system services. Filtering both out keeps the list to profiles that are safe to review.

How to see the columns Import-Csv created with Get-Member

Import-Csv -Path .\users.csv | Get-Member -MemberType NoteProperty

Get-Member lists every property Import-Csv built from the header row, with the value from the first row.

You should see: The output shows TypeName: System.Management.Automation.PSCustomObject and one NoteProperty string line per column. A single property whose name contains your whole header line means the delimiter is wrong.

Property names called H1, H2 and so on mean those header cells were empty in the file.

Import-Csv vs ConvertFrom-Csv vs Get-Content

Your situation Use this Why
The data is in a .csv file on disk Import-Csv Reads the file and returns one object per row
The CSV text is already in a variable or comes from a web request ConvertFrom-Csv Same parsing as Import-Csv, but works on pipeline strings instead of a file
You need to see or fix the raw lines, such as a broken header Get-Content Returns plain text lines with no parsing
You are reading IIS or other W3C extended logs in PowerShell 7 Import-Csv Uses the #Fields: line as headers and skips other # comment lines

Import-Csv not working in PowerShell

Every row shows as one long column

The -Delimiter value does not match the character in the file, so Import-Csv returns one property named after the whole header line.

  1. Run Get-Content .\file.csv -TotalCount 2 and note the separator.
  2. Import again with -Delimiter ';', -Delimiter "t" or -UseCulture`.

WARNING: One or more headers weren't specified

A cell in the header row is empty, so Import-Csv names that column H plus a number.

  1. Open the file and give the empty header cell a name, or
  2. Remove the header row and import with -Header listing every column name.

The first row of data contains the column names

-Header was used on a file that still has its own header row.

  1. Delete the first line of the file, or
  2. Drop -Header and let Import-Csv use the existing header row.

Accented or non-English characters look garbled

The file's encoding differs from the one Import-Csv assumed.

  1. Add -Encoding UTF8 in Windows PowerShell 5.1.
  2. Add -Encoding ansi or a code page number in PowerShell 7.

Cannot find path because it does not exist

A relative path such as .\users.csv is resolved from the current folder, not the script's folder.

  1. Run Get-Location to see the current folder.
  2. Use the full path, or Join-Path $PSScriptRoot 'users.csv' inside a script.

A path with square brackets is not found

-Path reads [ and ] as wildcard characters.

  1. Use -LiteralPath 'C:\Data\report[1].csv' with single quotes.

If a script that reads the CSV will not run at all, the cause is usually the execution policy, which you can change to allow running scripts.

Import-Csv not working: missing header warning with default H1 column name
An empty header cell makes Import-Csv print this warning and name the column H plus a number; fill in the cell to fix it. (Image: Microsoft)

Import-Csv PowerShell FAQ

What does Import-Csv return in PowerShell?

Import-Csv returns one PSCustomObject per data row. Each column header becomes a property name, and the cells in that row become the property values, stored as strings. You can filter, sort and loop through the objects like any other PowerShell output.

How do I count the rows in a CSV file with PowerShell?

Store the import in a variable and read its Count property: $rows = Import-Csv .\file.csv then $rows.Count. The header row is not counted, so the number matches the data rows only.

How do I read one column from a CSV in PowerShell?

Use member access on the imported rows: (Import-Csv .\file.csv).Email returns every value in the Email column. You can also run Import-Csv .\file.csv | Select-Object -ExpandProperty Email for the same list.

What is the default delimiter for Import-Csv?

The default delimiter is a comma. Use -Delimiter with another character, such as ';' for a semicolon or "t" for a tab, or use -UseCulture` to read with your region's list separator.

Can Import-Csv read a file with no header row?

Yes. Add -Header with a name for each column, such as -Header 'Id', 'Name'. Import-Csv then treats every line as data. If the file has a header row, delete it first or it becomes an extra data row.

What is the difference between Import-Csv and ConvertFrom-Csv?

Import-Csv reads CSV data from a file. ConvertFrom-Csv parses CSV text that is already in the pipeline, such as a variable or the output of a web request. Both return the same kind of objects.

Why are Import-Csv numbers sorted in the wrong order?

Import-Csv stores every value as text, so values sort alphabetically and 100 comes before 20. Cast the column to a number in the sort or filter, for example Sort-Object { [int]$_.Size }.

What is the default encoding of Import-Csv?

In PowerShell 7 the default is utf8NoBOM. In Windows PowerShell 5.1 the default is Default, the system's active code page, and a byte order mark in the file is detected. Use -Encoding when characters look wrong.

Can I import several CSV files at once?

Yes. -Path accepts more than one file, and you can pipe paths to Import-Csv: Get-ChildItem .\*.csv | Import-Csv. Files with the same headers combine into one set of rows.

Is there a short alias for Import-Csv?

Yes. PowerShell includes the alias ipcsv for Import-Csv on all platforms, so ipcsv .\file.csv works the same way. Use the full cmdlet name in scripts you share so others can read them.

Philip Celasco

Philip is a Texas-based technology writer and IT administrator at Techdows.com with more than 10 years of experience creating practical content for everyday users and professionals. He specializes in web browsers, particularly Chromium-based platforms such as Google Chrome, Microsoft Edge, Brave, and Opera. Through his work as an IT administrator, Philip has hands-on experience managing devices, configuring browser policies, troubleshooting software and network issues, and helping people resolve problems that affect productivity and security. His articles are based on practical testing and real-world technical experience. He covers browser settings, extensions, performance problems, privacy controls, security features, and Windows troubleshooting. Outside work, Philip enjoys the quieter side of life in Texas and stepping away from the screen when he can. He has two kids, two cats and loves to play golf with his mother during the weekends.

Leave a Reply

Your email address will not be published. Required fields are marked *