Import-Csv

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

Syntax

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

Cmdlet Import-Csv 會從 CSV 檔案中的專案建立類似數據表的自定義物件。 CSV 檔案中的每個資料行都會成為自定義物件的屬性,而數據列中的專案會變成屬性值。 Import-Csv 適用於任何 CSV 檔案,包括 Cmdlet 所產生的 Export-Csv 檔案。

您可以使用 Cmdlet 的參數 Import-Csv 來指定資料行行首列和專案分隔符,或直接 Import-Csv 使用目前文化特性的清單分隔符做為專案分隔符。

您也可以使用 ConvertTo-CsvConvertFrom-Csv Cmdlet 將物件轉換成 CSV 字串串 (和 back)。 這些 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

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

範例 2:指定分隔符

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

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

Cmdlet 會將 Get-Process 行程物件向下傳送至 Export-Csv。 Cmdlet 會將 Export-Csv 進程對象轉換成 CSV 字串,並將字串儲存在Processes.csv檔案中。 Delimiter 參數是用來指定冒號分隔符。 Cmdlet Import-Csv 會從 Processes.csv 檔案匯入 CSV 字串。 字串會儲存在變數中 $P 。 To $P 變數會向下傳送至 Cmdlet 的 Format-Table 管線。

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

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

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

Cmdlet Get-Culture 會使用巢狀屬性 TextInfoListSeparator 來取得目前文化特性的預設清單分隔符。 Cmdlet 會將 Get-Process 行程物件向下傳送至 Export-Csv。 Cmdlet 會將 Export-Csv 進程對象轉換成 CSV 字串,並將字串儲存在Processes.csv檔案中。 UseCulture 參數會使用目前文化特性的預設清單分隔符。 Cmdlet Import-Csv 會從 Processes.csv 檔案匯入 CSV 字串。

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

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

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]

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

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

範例 6:匯入遺漏值的 CSV

此範例示範當 CSV 檔案中的標頭數據列包含 Null 或空白值時,PowerShell 中的 Cmdlet 如何 Import-Csv 回應。 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 were not 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

(Import-Csv -Path .\Projects.csv).H1

WARNING: One or more headers were not specified. Default names starting with "H" have been used in
place of any missing headers.
Redmond
FarEast
Europe

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

Cmdlet Get-Content 會顯示Projects.csv檔案。 標頭數據列遺漏 ProjectNameCompleted 之間的值。 Cmdlet Import-Csv 會匯入Projects.csv檔案,並顯示警告訊息,因為 H1 是預設標頭名稱。 此命令 (Import-Csv -Path .\Projects.csv).H1 會取得 H1 屬性值,並顯示警告。

參數

-Delimiter

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

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

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

Type:Char
Position:1
Default value:comma (,)
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-Encoding

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

此參數可接受的值如下:

  • ascii:使用 ASCII (7 位) 字元集的編碼方式。
  • ansi:針對目前文化特性的 ANSI 代碼頁,使用 的編碼方式。 此選項已在PowerShell 7.4中新增。
  • bigendianunicode:使用 big-endian 位元組順序以 UTF-16 格式編碼。
  • bigendianutf32:使用 big-endian 位元組順序以 UTF-32 格式編碼。
  • 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 參數也允許已註冊代碼頁的數值識別元(例如 -Encoding 1251)或已註冊代碼頁的字串名稱(例如 )。-Encoding "windows-1251" 如需詳細資訊,請參閱 Encoding.CodePage.NET 檔。

從 PowerShell 7.4 開始,您可以使用 Ansi Encoding 參數的值,傳遞目前文化特性 ANSI 代碼頁的數值標識碼,而不需要手動指定它。

注意

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

Type:Encoding
Accepted values:ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32
Position:Named
Default value:UTF8NoBOM
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-Header

指定匯入檔案的替代數據行行首數據列。 數據行標頭會決定 所 Import-Csv建立之 對象的屬性名稱。

輸入數據行標頭做為字元分隔清單。 請勿以引號括住標頭字串。 以單引弧括住每個數據行標頭。

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

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

Type:String[]
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-LiteralPath

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

Type:String[]
Aliases:PSPath, LP
Position:Named
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:False

-Path

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

Type:String[]
Position:0
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:False

-UseCulture

使用目前文化特性的清單分隔符做為專案分隔符。 若要尋找文化特性的清單分隔符,請使用下列命令: (Get-Culture).TextInfo.ListSeparator

Type:SwitchParameter
Position:Named
Default value:None
Required:True
Accept pipeline input:False
Accept wildcard characters: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 和其他網頁伺服器記錄的標準格式。 如需詳細資訊,請參閱 擴充記錄檔格式