共用方式為


Import-Csv

從字元分隔值 (CSV) 檔案中的專案建立類似數據表的自定義物件。

語法

Import-Csv
      [[-Delimiter] <Char>]
      [-Path] <String[]>
      [-Header <String[]>]
      [-Encoding <Encoding>]
      [<CommonParameters>]
Import-Csv
      [[-Delimiter] <Char>]
      -LiteralPath <String[]>
      [-Header <String[]>]
      [-Encoding <Encoding>]
      [<CommonParameters>]
Import-Csv
      [-Path] <String[]>
      -UseCulture
      [-Header <String[]>]
      [-Encoding <Encoding>]
      [<CommonParameters>]
Import-Csv
      -LiteralPath <String[]>
      -UseCulture
      [-Header <String[]>]
      [-Encoding <Encoding>]
      [<CommonParameters>]

Description

Import-Csv cmdlet 指令會從 CSV 檔案中的項目建立類似數據表的自訂物件。 CSV 檔案中的每個資料行都會成為自訂物件的屬性,而列中的內容會變成屬性值。 Import-Csv 適用於任何 CSV 檔案,包括由 Export-Csv Cmdlet 產生的檔案。

您可以使用 Import-Csv Cmdlet 的參數來指定資料欄標題列和項目分隔符,或者指定 Import-Csv 使用當前文化特性的清單分隔符作為項目分隔符。

您也可以使用 ConvertTo-CsvConvertFrom-Csv Cmdlet,將對象轉換成 CSV 字串(和返回)。 這些 Cmdlet 與 Export-CSVImport-Csv Cmdlet 相同,不同之處在於它們會使用管線中的數據,而不是使用檔案。

如果 CSV 檔案中的標頭列項目包含空值或 Null 值,PowerShell 會插入預設的標頭列名稱,並顯示警告訊息。

從 PowerShell 6.0 開始,Import-Csv 現在支援 W3C 擴充記錄檔格式。

範例

範例 1:匯入進程物件

此範例示範如何匯出並匯入進程物件的 CSV 檔案。

Get-Process | Export-Csv -Path .\Processes.csv
$P = Import-Csv -Path .\Processes.csv
$P | Get-Member

TypeName: System.Management.Automation.PSCustomObject

Name                       MemberType   Definition
----                       ----------   ----------
Equals                     Method       bool Equals(System.Object obj)
GetHashCode                Method       int GetHashCode()
GetType                    Method       type GetType()
ToString                   Method       string ToString()
BasePriority               NoteProperty string BasePriority=8
Company                    NoteProperty string Company=Microsoft Corporation
...

$P | Format-Table

Name                   SI Handles VM            WS        PM        NPM    Path
----                   -- ------- --            --        --        ---    ----
ApplicationFrameHost   4  407     2199293489152 15884288  15151104  23792  C:\WINDOWS\system32\ApplicationFrameHost.exe
...
wininit                0  157     2199112204288 4591616   1630208   10376
winlogon               4  233     2199125549056 7659520   2826240   10992  C:\WINDOWS\System32\WinLogon.exe
WinStore.App           4  846     873435136     33652736  26607616  55432  C:\Program Files\WindowsApps\Microsoft.WindowsStore_11712.1001.13.0_x64__8weky...
WmiPrvSE               0  201     2199100219392 8830976   3297280   10632  C:\WINDOWS\system32\wbem\wmiprvse.exe
WmiPrvSE               0  407     2199157727232 18509824  12922880  16624  C:\WINDOWS\system32\wbem\wmiprvse.exe
WUDFHost               0  834     2199310204928 51945472  87441408  24984  C:\Windows\System32\WUDFHost.exe

Get-Process Cmdlet 會將程序物件向下傳送至 Export-CsvExport-Csv Cmdlet 會將進程物件轉換成 CSV 字串,並將字串儲存在 Processes.csv 檔案中。 Import-Csv Cmdlet 會從 Processes.csv 檔案匯入 CSV 字串。 字串會儲存在 $P 變數中。 $P 變數會向下傳送至 Get-Member Cmdlet,以顯示匯入 CSV 字串的屬性。 $P 變數會向下傳送至 Format-Table Cmdlet,並顯示物件。

範例 2:指定分隔符

此範例示範如何使用 Cmdlet 的 Import-Csv 參數。

Get-Process | Export-Csv -Path .\Processes.csv -Delimiter :
$P = Import-Csv -Path .\Processes.csv -Delimiter :
$P | Format-Table

Get-Process Cmdlet 會將處理程序物件沿著管線傳送至 Export-CsvExport-Csv Cmdlet 會將進程物件轉換成 CSV 字串,並將字串儲存在 Processes.csv 檔案中。 Delimiter 參數可用來指定冒號分隔符。 Import-Csv Cmdlet 會從 Processes.csv 檔案匯入 CSV 字串。 字串會儲存在 $P 變數中。 $P 變數被傳送到管線下游至 Format-Table cmdlet。

範例 3:指定分隔符的目前文化特性

此範例示範如何使用 Import-Csv Cmdlet 搭配 UseCulture 參數。

(Get-Culture).TextInfo.ListSeparator
Get-Process | Export-Csv -Path .\Processes.csv -UseCulture
Import-Csv -Path .\Processes.csv -UseCulture

Cmdlet 會使用 TextInfo 和 ListSeparator 的巢狀 屬性來取得目前文化特性的預設清單分隔符。 Get-Process Cmdlet 會將處理程序物件沿著管線傳送至 Export-CsvExport-Csv Cmdlet 會將進程物件轉換成 CSV 字串,並將字串儲存在 Processes.csv 檔案中。 UseCulture 參數會使用目前文化特性的預設清單分隔符。 Import-Csv Cmdlet 會從 Processes.csv 檔案匯入 CSV 字串。

範例 4:變更匯入物件中的屬性名稱

這個範例示範如何使用 Import-Csv 參數來變更所產生匯入物件中的屬性名稱。

Start-Job -ScriptBlock { Get-Process } | Export-Csv -Path .\Jobs.csv -NoTypeInformation
$Header = 'State', 'MoreData', 'StatusMessage', 'Location', 'Command', 'StateInfo', 'Finished',
          'InstanceId', 'Id', 'Name', 'ChildJobs', 'BeginTime', 'EndTime', 'JobType', 'Output',
          'Error', 'Progress', 'Verbose', 'Debug', 'Warning', 'Information'
# Delete the default header from file
$A = Get-Content -Path .\Jobs.csv
$A = $A[1..($A.Count - 1)]
$A | Out-File -FilePath .\Jobs.csv
$J = Import-Csv -Path .\Jobs.csv -Header $Header
$J

State         : Running
MoreData      : True
StatusMessage :
Location      : localhost
Command       : Get-Process
StateInfo     : Running
Finished      : System.Threading.ManualResetEvent
InstanceId    : a259eb63-6824-4b97-a033-305108ae1c2e
Id            : 1
Name          : Job1
ChildJobs     : System.Collections.Generic.List`1[System.Management.Automation.Job]
BeginTime     : 12/20/2018 18:59:57
EndTime       :
JobType       : BackgroundJob
Output        : System.Management.Automation.PSDataCollection`1[System.Management.Automation.PSObject]
Error         : System.Management.Automation.PSDataCollection`1[System.Management.Automation.ErrorRecord]
Progress      : System.Management.Automation.PSDataCollection`1[System.Management.Automation.ProgressRecord]
Verbose       : System.Management.Automation.PSDataCollection`1[System.Management.Automation.VerboseRecord]
Debug         : System.Management.Automation.PSDataCollection`1[System.Management.Automation.DebugRecord]
Warning       : System.Management.Automation.PSDataCollection`1[System.Management.Automation.WarningRecord]
Information   : System.Management.Automation.PSDataCollection`1[System.Management.Automation.InformationRecord]

Start-Job Cmdlet 會啟動執行 Get-Process的背景作業。 作業物件會將管線向下傳送至 Export-Csv Cmdlet,並轉換成 CSV 字串。 NoTypeInformation 參數會從 CSV 輸出中移除類型資訊標頭,而且在 PowerShell v6 和更新版本中是選擇性的。 $Header 變數包含取代下列預設值的自定義標頭:HasMoreDataJobStateInfoPSBeginTimePSEndTimePSJobTypeName$A 變數會使用 Get-Content Cmdlet 從 Jobs.csv 檔案取得 CSV 字串。 $A 變數可用來從檔案中移除預設標頭。 Out-File Cmdlet 會將新版本的 Jobs.csv 檔案儲存在 $A 變數中。 Import-Csv Cmdlet 會匯入 Jobs.csv 檔案,並使用 Header 參數來套用 $Header 變數。 $J 變數包含匯入 PSCustomObject,並在 PowerShell 控制台中顯示物件。

範例 5:使用 CSV 檔案建立自定義物件

此範例示範如何使用 CSV 檔案在 PowerShell 中建立自定義物件。

Get-Content -Path .\Links.csv

113207,about_Aliases
113208,about_Arithmetic_Operators
113209,about_Arrays
113210,about_Assignment_Operators
113212,about_Automatic_Variables
113213,about_Break
113214,about_Command_Precedence
113215,about_Command_Syntax
144309,about_Comment_Based_Help
113216,about_CommonParameters
113217,about_Comparison_Operators
113218,about_Continue
113219,about_Core_Commands
113220,about_Data_Section

$A = Import-Csv -Path .\Links.csv -Header 'LinkID', 'TopicTitle'
$A | Get-Member

TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
LinkID      NoteProperty string LinkID=113207
TopicTitle  NoteProperty string TopicTitle=about_Aliases

$A | Where-Object -Property TopicTitle -Like '*alias*'

LinkID TopicTitle
------ ----------
113207 about_Aliases

若要建立您的 Links.csv 檔案,請使用 Get-Content 輸出中顯示的值。

Get-Content Cmdlet 會顯示 Links.csv 檔案。 Import-Csv Cmdlet 會匯入 Links.csv 檔案。 Header 參數會指定屬性名稱 ,包括 LinkIdTopicTitle。 物件會儲存在 $A 變數中。 Get-Member Cmdlet 指令會顯示來自 標題 參數的屬性名稱。 Where-Object Cmdlet 會使用包含 別名TopicTitle 屬性來選取物件。

範例 6:匯入遺漏值的 CSV

此範例示範當 CSV 檔案中的標頭數據列包含 Null 或空白值時,PowerShell 中的 Import-Csv Cmdlet 如何回應。 Import-Csv 取代遺漏標頭數據列的預設名稱,成為 Import-Csv 傳回之對象的屬性名稱。

Get-Content -Path .\Projects.csv

ProjectID,ProjectName,,Completed
13,Inventory,Redmond,True
440,,FarEast,True
469,Marketing,Europe,False

Import-Csv -Path .\Projects.csv

WARNING: One or more headers weren't specified. Default names starting with "H" have been used in
place of any missing headers.

ProjectID ProjectName H1      Completed
--------- ----------- --      ---------
13        Inventory   Redmond True
440                   FarEast True
469       Marketing   Europe  False

Get-Content Cmdlet 會顯示 Projects.csv 檔案。 標題列缺少一個位於 ProjectNameCompleted之間的值。 Import-Csv Cmdlet 會匯入 Projects.csv 檔案,並顯示警告訊息,因為 H1 是預設標頭名稱。

參數

-Delimiter

指定分隔符,分隔 CSV 檔案中的屬性值。 預設值為逗號 (,)。

輸入字元,例如冒號(:)。 若要指定分號 (;),請以單引弧括住它。 若要指定轉義的特殊字元,例如製表符(`t),請以雙引號括住它。

如果您指定檔案中實際字串分隔符以外的字元,Import-Csv 無法從 CSV 字串建立物件,並傳回完整的 CSV 字串串。

類型:Char
Position:1
預設值:comma (,)
必要:False
接受管線輸入:False
接受萬用字元:False

-Encoding

指定匯入 CSV 檔案的編碼方式。 預設值為 utf8NoBOM

此參數可接受的值如下:

  • ascii:使用 ASCII (7 位) 字元集的編碼方式。
  • ansi:使用當前文化特性的 ANSI 代碼頁的編碼方式。 此選項已在PowerShell 7.4中新增。
  • bigendianunicode:使用高位元組序以 UTF-16 格式編碼。
  • bigendianutf32:使用 UTF-32 格式並以 big-endian 位元組順序編碼。
  • oem:使用 MS-DOS 和控制台程序的預設編碼方式。
  • unicode:使用小端位元組順序的UTF-16格式編碼。
  • utf7:以UTF-7格式編碼。
  • utf8:以UTF-8格式編碼。
  • utf8BOM:以 UTF-8 格式(含 BOM,位元組順序標記)編碼
  • utf8NoBOM:以 UTF-8 格式編碼,不含 BOM(位元組順序標記)
  • utf32:以UTF-32格式編碼。

從 PowerShell 6.2 開始,編碼 參數也允許已註冊代碼頁的數值識別元(例如 -Encoding 1251)或已註冊代碼頁的字串名稱(例如 -Encoding "windows-1251")。 如需詳細資訊,請參閱 Encoding.CodePage的 .NET 檔。

從 PowerShell 7.4 開始,您可以使用 Ansi 參數的 值,自動傳遞目前文化設定的 ANSI 代碼頁數字 ID,而不需手動指定。

注意

UTF-7* 不再建議使用。 自 PowerShell 7.1 起,如果您為 utf7 參數指定 ,則會撰寫警告。

類型:Encoding
接受的值:ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32
Position:Named
預設值:UTF8NoBOM
必要:False
接受管線輸入:False
接受萬用字元:False

-Header

指定匯入檔案的替代欄位標題列。 欄位標題會決定 Import-Csv所建立之物件的屬性名稱。

輸入欄位標題作為以字元分隔的列表。 請勿以引號括住標頭字串。 以單引號括住每個欄位標題。

如果您輸入的列標題數量少於數據列,則會捨棄其餘的數據列。 如果您輸入的數據行標頭數目超過數據行,則會使用空白數據行來建立其他數據行標頭。

使用 Header 參數時,請從 CSV 檔案中刪除原始標頭數據列。 否則,Import-Csv 會從標題行中的項目創建額外的物件。

類型:String[]
Position:Named
預設值:None
必要:False
接受管線輸入:False
接受萬用字元:False

-LiteralPath

指定要匯入的 CSV 檔案路徑。 與 Path不同,LiteralPath 參數的值會被按照輸入時的格式原樣使用。 不會將任何字元解譯為通配符。 如果路徑包含逸出字元,請以單引弧括住它。 單引號會告知PowerShell不要將任何字元解譯為逸出序列。

類型:String[]
別名:PSPath, LP
Position:Named
預設值:None
必要:True
接受管線輸入:True
接受萬用字元:False

-Path

指定要匯入的 CSV 檔案路徑。 您也可以使用管道將路徑傳送至 Import-Csv

類型:String[]
Position:0
預設值:None
必要:True
接受管線輸入:True
接受萬用字元:False

-UseCulture

使用針對目前文化環境的清單分隔符作為項目分隔符。 若要尋找文化特性的清單分隔符,請使用下列命令:(Get-Culture).TextInfo.ListSeparator

類型:SwitchParameter
Position:Named
預設值:None
必要:True
接受管線輸入:False
接受萬用字元:False

輸入

String

您可以使用管線傳送包含此 Cmdlet 路徑的字串。

輸出

Object

此 Cmdlet 會傳回 CSV 檔案中內容所描述的物件。

備註

PowerShell 包含以下 Import-Csv的別名:

  • 所有平臺:
    • ipcsv

因為匯入的對象是對象類型的 CSV 版本,所以未被辨識和格式化,因而無法由格式化非 CSV 版本對象類型的 PowerShell 類型格式化專案進行格式化。

Import-Csv 命令的結果是構成類似數據表的自定義物件的字串集合。 每個數據列都是個別的字串,因此您可以使用 物件的 Count 屬性來計算數據表數據列。 列是物件的屬性,而行中的項目是屬性值。

欄位標題列決定欄位數目和欄位名稱。 欄位名稱也是物件屬性的名稱。 除非您使用 Header 參數來指定列標頭,否則第一行會被解釋為列標頭。 如果有任何數據列的值超過標頭數據列,則會忽略其他值。

如果欄位標頭行遺漏值或包含 null 或空白值,Import-Csv 將使用 H,後面接一個數字,表示遺漏的欄位標頭和屬性名稱。

在 CSV 檔案中,每個物件都會以物件屬性值的字元分隔清單來表示。 屬性值會使用 物件的 ToString() 方法轉換成字串,因此會以屬性值的名稱表示。 Export-Csv 不會匯出 物件的方法。

Import-Csv 也支援 W3C 擴充記錄格式。 以哈希字元(#)開頭的行會被視為註解並被忽略,除非該註解以 #Fields: 開頭且包含欄位名稱的分隔列表。 在此情況下,Cmdlet 會使用這些數據行名稱。 這是 Windows IIS 和其他網頁伺服器記錄的標準格式。 如需詳細資訊,請參閱 擴充記錄檔格式