Get-Content for FileSystem
Aplica-se a: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0, Windows PowerShell 5.0
Obtém o conteúdo de um arquivo.
Get-Content [-Delimiter <string>] [-Encoding {<Unknown> | <String> | <Unicode> | <Byte> | <BigEndianUnicode> | <UTF8> | <UTF7> | <UTF32> | <Ascii> | <Default> | <Oem>}] [-Force] [-Raw <switch>] [-Stream <string>] [-Wait] [-UseTransaction] [<CommonParameters>]
Em unidades de sistema de arquivos, você pode usar o cmdlet Get-Content para obter o conteúdo que você exibir na linha de comando, salvar em uma variável para processamento ou gravar em outro arquivo. Não é válido em pastas.
Observação: Este arquivo de Ajuda do cmdlet personalizado explica como o cmdlet Get-Content funciona em uma unidade de sistema de arquivos. Para obter informações sobre o cmdlet Get-Content em todas as unidades, digite "Get-HelpGet-Content -Path $null" ou veja Get-Content em https://go.microsoft.com/fwlink/?LinkID=113310.
Especifica a codificação do arquivo. O padrão é ASCII.
Os valores válidos são:
-- ASCII: Usa a codificação para o conjunto de caracteres (7 bits) ASCII.
-- BigEndianUnicode: Codifica em formato UTF-16 usando a ordem de byte big-endian.
-- Byte: Codifica um conjunto de caracteres em uma sequência de bytes.
– String: Usa o tipo de codificação para uma cadeia de caracteres.
-- Unicode: Codifica em formato UTF-16 usando a ordem de byte little-endian.
-- UTF7: Codifica em formato UTF-7.
-- UTF8: Codifica em formato UTF-8.
-- Unknown: O tipo de codificação é desconhecido ou inválido. Os dados podem ser tratados como binários.
A codificação é um parâmetro dinâmico que adiciona o provedor FileSystem ao cmdlet Get-Content. Esse parâmetro funciona somente em unidades de sistema de arquivos.
Ao ler e gravar em arquivos binários, use um valor de Byte para o parâmetro dinâmico Encoding e um valor 0 para o parâmetro ReadCount. Um valor ReadCount 0 lê o arquivo inteiro em uma única operação de leitura e converte-o em um único objeto (PSObject). O valor default ReadCount (1) lê um byte em cada operação de leitura e converte cada byte em um objeto separado, o que causa erros quando você usa o cmdlet Set-Content para gravar os bytes em um arquivo. Para obter mais informações, consulte os exemplos.
Necessário? |
false |
Posição? |
chamada |
Valor padrão |
ASCII |
Aceitar entrada do pipeline? |
false |
Aceitar caracteres curinga? |
false |
Especifica o delimitador que o Get-Content usa para dividir o arquivo em objetos enquanto ele lê.
O padrão é "\n", o caractere de final de linha.
Portanto, por padrão, ao ler um arquivo de texto, o Get-Content retorna uma coleção de objetos de cadeia de caracteres, cada uma delas termina com um caractere de final de linha.
Quando você insere um delimitador que não existe no arquivo, o Get-Content retorna todo o arquivo como um único objeto não delimitado.
Você pode usar esse parâmetro para dividir um arquivo grande em arquivos menores, especificando um separador de arquivo, como "Final de exemplo," como o delimitador. O delimitador é preservado (não descartado) e se torna o último item em cada seção do arquivo.
O delimitador é um parâmetro dinâmico que adiciona o provedor FileSystem ao cmdlet Get-Content. Esse parâmetro funciona somente em unidades de sistema de arquivos.
Observação de solução de problemas: Atualmente, quando o valor do parâmetro delimitador é uma cadeia de caracteres vazia, o Get-Content não retorna nada. Esse é um problema conhecido. Para forçar o Get-Content a retornar o arquivo inteiro como uma única cadeia de caracteres não delimitada, insira um valor que não existe no arquivo.
Necessário? |
false |
Posição? |
chamada |
Valor padrão |
Caractere de fim de linha |
Aceitar entrada do pipeline? |
false |
Aceitar caracteres curinga? |
false |
Obtém o conteúdo de todos os arquivos, inclusive arquivos ocultos. Por padrão, o Get-Content não obtém o conteúdo dos arquivos ocultos, a menos que você especifique o arquivo oculto por nome.
Necessário? |
false |
Posição? |
chamada |
Valor padrão |
False |
Aceitar entrada do pipeline? |
false |
Aceitar caracteres curinga? |
false |
Ignora caracteres de nova linha e retorna todo o conteúdo de um arquivo em uma cadeia de caracteres. Por default, o conteúdo de um arquivo é retornado como uma matriz de cadeias de caracteres delimitadas por um caractere de nova linha.
O Raw é um parâmetro dinâmico que adiciona o provedor FileSystem ao cmdlet Get-Content. Esse parâmetro funciona somente em unidades de sistema de arquivos.
Este parâmetro é introduzido no Windows PowerShell 3.0.
Necessário? |
false |
Posição? |
chamada |
Valor padrão |
|
Aceitar entrada do pipeline? |
false |
Aceitar caracteres curinga? |
false |
Aguarda o cmdlet obter o conteúdo antes de retornar o prompt de comando. Enquanto aguarda, o Get-Content verifica o arquivo uma vez por segundo até você interrompê-lo, por exemplo, pressionando CTRL + C.
O Wait é um parâmetro dinâmico que adiciona o provedor FileSystem ao cmdlet Get-Content. Esse parâmetro funciona somente em unidades de sistema de arquivos.
Necessário? |
false |
Posição? |
chamada |
Valor padrão |
False |
Aceitar entrada do pipeline? |
false |
Aceitar caracteres curinga? |
false |
Obtém o fluxo de arquivos NTFS alternativo especificado do conteúdo do arquivo. Insira o nome do fluxo. Caracteres curinga não são suportados.
Fluxo é um parâmetro dinâmico que adiciona o provedor FileSystem ao cmdlet Get-Content. Esse parâmetro funciona somente em unidades de sistema de arquivos.
Este parâmetro é introduzido no Windows PowerShell 3.0.
Necessário? |
false |
Posição? |
chamada |
Valor padrão |
|
Aceitar entrada do pipeline? |
false |
Aceitar caracteres curinga? |
false |
Inclui o comando na transação ativa. Este parâmetro é válido somente quando uma transação está em andamento. Para obter mais informações, consulte about_Transactions.
Necessário? |
false |
Posição? |
chamada |
Valor padrão |
|
Aceitar entrada do pipeline? |
false |
Aceitar caracteres curinga? |
false |
Esse cmdlet dá suporte a parâmetros comuns: -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, -OutVariable, -Verbose, -WarningAction e -WarningVariable. Para obter mais informações, consulte about_CommonParameters.
O tipo de entrada é o tipo dos objetos que você pode canalizar para o cmdlet. O tipo de retorno é o tipo de objeto retornado pelo cmdlet.
Entradas |
System.Int64, System.String[], System.Management.Automation.PSCredential É possível canalizar a contagem de leitura, contagem total, caminhos ou credenciais para o Get-Content. |
Saídas |
System.Object, System.String O Get-Content retorna objetos que representam o conteúdo que ele recebe. O tipo de objeto depende do tipo de conteúdo. Se você usar o parâmetro Stream, o cmdlet retornará os conteúdos de fluxo de dados como uma cadeia de caracteres. |
C:\PS>Get-Content -Path C:\Chapters\chapter1.txt
Description
-----------
This command gets the content of the Chapter1.txt file and displays it in the console. It uses the Path parameter to specify the name of the item.
Get-Content actually passes the content down the pipeline, but because there are no other cmdlets in the pipeline, Windows PowerShell formats the contents and displays it in the console.
C:\PS>Get-Content C:\Logs\Log060912.txt -TotalCount 50 | Set-Content Sample.txt
Description
-----------
This command gets the first 50 lines of the Log060912.txt file and stores them in the sample.txt file.
The command uses the Get-Content cmdlet to get the text in the file. (The name of Path parameter, which is optional, is omitted.) The TotalCount parameter limits the retrieval to the first 50 lines. The pipeline operator (|) sends the result to Set-Content, which places it in the sample.txt file.
C:\PS>(Get-Content Cmdlets.txt -TotalCount 5)[-1]
Description
-----------
This command gets the fifth line of the Cmdlets.txt text file. It uses the TotalCount parameter to get the first five lines and then uses array notation to get the last line (indicated by "-1") of the resulting set.
C:\PS>Get-Content .\DataSets\*.csv -Delimiter "*---*" -Force -Encoding UTF8
Description
-----------
This command gets the contents of all CSV files in the DataSets subdirectory. It uses the Force parameter to get all files, including hidden files, and the Encoding parameter to specify the file encoding.
The command also uses the Delimiter parameter to divide the returned content into sets, each of which ends at the CSV file row that contains the "*----*" marker.
C:\PS>Get-Content .\Copy-Scripts.ps1 -Stream Zone.Identifier
[ZoneTransfer]
ZoneId=3
Description
-----------
This command uses the Stream parameter to get the content of the Zone.Identifier alternate data stream. The output includes Zone ID value of 3, which represents the Internet.
The Stream parameter is introduced in Windows PowerShell 3.0.
C:\PS>$Manifest = (Get-Module -List PSScheduledJob).Path
C:\PS>$Hash = Invoke-Expression (Get-Content $Manifest -Raw)
C:\PS>$Hash
Name Value
---- -----
Copyright © Microsoft Corporation. All rights reserved.
ModuleToProcess Microsoft.PowerShell.ScheduledJob.dll
FormatsToProcess PSScheduledJob.Format.ps1xml
PowerShellVersion 3.0
CompanyName Microsoft Corporation
GUID 50cdb55f-5ab7-489f-9e94-4ec21ff51e59
Author Microsoft Corporation
CLRVersion 4.0
CmdletsToExport {New-JobTrigger, Add-JobTrigger, Remove-JobTrigger, Get-JobTrigger...}
TypesToProcess PSScheduledJob.types.ps1xml
HelpInfoURI https://go.microsoft.com/fwlink/?LinkID=223911
ModuleVersion 1.0.0.0
C:\PS>$Hash.ModuleToProcess
Microsoft.PowerShell.ScheduledJob.dll
Description
-----------
The commands in this example get the contents of a module manifest file (.psd1) as a hash table. The manifest file contains a hash table, but if you get the contents without the Raw dynamic parameter, it is returned as an array of newline-delimited strings.
The Raw dynamic parameter is introduced in Windows PowerShell 3.0.
The first command uses the Path property of modules to get the path to the file that contains the module manifest for the PSScheduledJob module. It saves the path in the $Manifest variable.
The second command uses the Invoke-Expression cmdlet to run a Get-Content command and the Raw dynamic parameter of the Get-Content cmdlet to get the contents of the module manifest file in a single string. The command saves the hash table in the $Hash variable.
The third command gets the hash table in the Hash variable. The contents is returned as a collection of name-value pairs.
The fourth command uses the ModuleToProcess property of the hash table to get the value of the ModuleToProcess key in the module manifest.
C:\PS>$a = Get-Content -Path .\Download.zip -Encoding Byte -ReadCount 0
Set-Content -Path \\Server\Share\Download.zip -Encoding Byte -Value $a
$b = Get-Content -Path .\Download.zip -Encoding Byte
Set-Content -Path \\Server\Share\Download.zip -Encoding Byte -Value $b
Set-Content : Cannot proceed with byte encoding. When using byte encoding the content must be of type byte.
At line:1 char:1
+ Set-Content \\Server\Share\Download.zip -Encoding Byte -Value $b
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Content], PSArgumentException
+ FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.SetContentCommand
Description
-----------
This example shows how to use the ReadCount parameter of the Get-Content cmdlet with a value of 0 to avoid byte-related errors when using the Set-Content cmdlet to write the bytes to a file.
When getting the content of a file in bytes, Get-Content creates an object (PSObject) for the bytes in each read operation. If you read the bytes one at a time, which is the default, Get-Content creates an object for each byte. The objects cause errors when you use the Set-Content cmdlet to write the bytes to a file.
The first command uses the Get-Content cmdlet to get the contents of the Download.zip file and save it in the $a variable. The command uses the Encoding dynamic parameter with a value of Byte. It also uses the ReadCount parameter with a value of 0, which directs Get-Content to get the file contents in a single read operation. The default value of the ReadCount parameter, 1, gets one byte at a time.
The second command uses the Set-Content cmdlet to write the bytes in the $a variable to the Download.zip file on a file share. The command succeeds.
The third and fourth commands show the same sequence without the ReadCount parameter.
The third command uses the Encoding dynamic parameter of the Get-Content cmdlet to get the contents of the Download.zip file and save it in the $b variable. Because the command omits the ReadCount parameter, it uses the default value of 1.
The fourth command uses the Set-Content cmdlet to write the bytes in the $b variable to the Download.zip file on a file share. Because the content is a collection of objects, rather than a single object that contains a byte array, the command fails.
Clear-Content
Get-Content
Get-ChildItem
Get-Content
Get-Item
Remove-Item
Set-Content
Test-Path