Share via


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 字串, (和返回) 。 這些 Cmdlet 與 和 Import-Csv Cmdlet 相同Export-CSV,不同之處在於它們不會處理檔案。

如果 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分隔符參數。

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 檔案中。 分隔符參數可用來指定冒號分隔符。 Cmdlet 會 Import-Csv 從 Processes.csv 檔案匯入 CSV 字串。 字串會儲存在變數中 $P 。 變數 $P 會向下傳送至 Format-Table Cmdlet 的管線。

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

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

(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-CsvHeader 參數來變更所產生匯入物件中的屬性名稱。

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 Core 中是選擇性的。 $Header變數包含取代下列預設值的自定義標頭:HasMoreDataJobStateInfoPSBeginTimePSEndTimePSJobTypeName。 變數 $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 檔案 Create 自定義物件

此範例示範如何使用 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 檔案中用來分隔屬性值的分隔符號。 預設值為逗號 (,)。

輸入字元,例如冒號 (:)。 若要指定分號 (;) 以單引弧括住它。

如果您指定檔案中實際字串分隔符以外的字元,則無法從 CSV 字串建立對象, Import-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 位) 字元集的編碼方式。
  • bigendianunicode:使用大位元組位元組順序以UTF-16格式編碼。
  • oem:使用 MS-DOS 和控制台程式的預設編碼方式。
  • unicode:使用小位元節順序以UTF-16格式編碼。
  • utf7:以 UTF-7 格式編碼。
  • utf8:以 UTF-8 格式編碼。
  • utf8BOM:使用位元節順序標記 (BOM) ,以 UTF-8 格式編碼
  • utf8NoBOM:以 UTF-8 格式編碼,不含位元組順序標記 (BOM)
  • utf32:以 UTF-32 格式編碼。

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

Type:Encoding
Accepted values:ASCII, BigEndianUnicode, 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

您可以使用管線傳送包含 路徑的 Import-Csv字串。

輸出

Object

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

備註

因為匯入的對像是物件類型的 CSV 版本,所以無法辨識這些對象,並且由格式化物件類型非 CSV 版本的 PowerShell 類型格式化專案格式化。

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

欄標題列會決定欄數和欄名稱。 欄名稱也是物件的屬性名稱。 除非您使用 Header 參數來指定數據行標頭,否則第一個數據列會解譯為數據行標頭。 如果有任何列包含的值比標題列還多,即會忽略額外的值。

如果數據行標頭數據列遺漏值或包含 Null 或空白值, Import-Csv 請使用 H ,後面接著遺漏數據行標頭和屬性名稱的數位。

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

Import-Csv 也支援 W3C 擴充記錄格式。 開頭的 # 行會被視為批注,除非批注 #Fields: 開頭為 ,且包含數據行名稱的分隔清單。 在此情況下,Cmdlet 會使用這些數據行名稱。 這是 Windows IIS 和其他網頁伺服器記錄的標準格式。 如需詳細資訊,請參閱 擴充記錄檔格式