Agregar datos al archivo usando PowerShell [4 formas]
Agregar texto a un archivo de texto
Tenemos varios enfoques para agregar contenido a un archivo de texto usando PowerShell. Por ejemplo, podemos agregar información en la misma línea, en una nueva línea con o sin caracteres especiales, en varias líneas y agregar datos formateados, como contenido tabular. Pero, antes de avanzar hacia posibles soluciones, es obligatorio conocer el archivo y el contenido del archivo que utilizaremos para cada enfoque a continuación en esta sección. El file.txt se encuentra en el directorio E:\Test.
Contenido del archivo file.txt:
This is the first line.Tenga en cuenta que nuestro cursor está en la misma línea, justo después del punto (.), lo que nos ayudará a agregarlo en la misma línea. Usemos este archivo para explorar las diversas soluciones a continuación.
Utilice el cmdlet Out-File
Utilice el cmdlet Out-File con el parámetro -Append para agregar contenido en la misma línea en el archivo file.txt.
Utilice el cmdlet Out-File:
$filePath = "E:\Test\file.txt"
$content = "This is the second line."
Out-File -FilePath $filePath -InputObject $content -Append
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.Utilice el cmdlet Out-File con el parámetro -Append para agregar contenido en la nueva línea del archivo file.txt.
Utilice el cmdlet Out-File:
$filePath = "E:\Test\file.txt"
$content = "This is the third line."
Out-File -FilePath $filePath -InputObject $content -Append
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.¿Encontró alguna similitud en los dos ejemplos anteriores? ¡Sí! ¿Por qué es así? Debido a que
-Appendse usó la primera vez en el primer ejemplo, agregó el contenido en la misma línea que nuestro cursor estaba en la misma línea, pero también agregó un carácter de nueva línea al final del archivo. . Ahora el cursor está en una nueva línea; es por eso que-Appenden el segundo ejemplo de código agregó el contenido en una nueva línea, pero también agregó un carácter de nueva línea al final del archivo. Tenga en cuenta que el parámetro-Appendagrega automáticamente un carácter de nueva línea al final del archivo; es por eso que el contenido se agrega en la nueva línea cada vez, excepto en el primer ejemplo.
Utilice el cmdlet Out-File con el parámetro -Append para agregar contenido con caracteres especiales (como tabulación) en el archivo file.txt archivo.
Utilice el cmdlet Out-File:
$filePath = "E:\Test\file.txt"
$content = "`tThis fourth line is with tab character."
Out-File -FilePath $filePath -InputObject $content -Append
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.Utilice el cmdlet Out-File con el parámetro -Append para agregar varias líneas en el archivo file.txt.
Utilice el cmdlet Out-File:
$filePath = "E:\Test\file.txt"
$content = @("This is the fifth line.",
"This is the sixth line.",
"This is the seventh line.")
Out-File -FilePath $filePath -InputObject $content -Append
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.
This is the fifth line.
This is the sixth line.
This is the seventh line.Utilice el cmdlet Out-File con el parámetro -Append para agregar contenido tabular (contenido formateado) en el archivo file.txt.
Utilice el cmdlet Out-File:
$filePath = "E:\Test\file.txt"
$content = @("First`tLast`tAge",
"John`tWilliamson`t50",
"Mary`tPurell`t30",
"Sam`tAnderson`t35")
Out-File -FilePath $filePath -InputObject $content -Append
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.
This is the fifth line.
This is the sixth line.
This is the seventh line.
First Last Age
John Williamson 50
Mary Purell 30
Sam Anderson 35Utilice el cmdlet Out-File para agregar una línea que tenga comillas simples y dobles en el archivo file.txt.
Utilice el cmdlet Out-File:
$filePath = "E:\Test\file.txt"
$content = "This is the eighth line having `'single quote`' and `"double quotes`"."
Out-File -FilePath $filePath -InputObject $content -Append
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.
This is the fifth line.
This is the sixth line.
This is the seventh line.
First Last Age
John Williamson 50
Mary Purell 30
Sam Anderson 35
This is the eighth line having 'single quote' and "double quotes".El cmdlet Out-File se utiliza para enviar resultados a un archivo específico. Este cmdlet utiliza implícitamente el sistema de formato de PowerShell para escribir en un archivo. Tenga en cuenta que este archivo obtendrá la representación de visualización exacta que teníamos en la terminal, lo que significa que la salida solo puede ser lo suficientemente buena para el procesamiento programático si cada objeto de entrada involucrado en la salida es una cadena. Usamos este cmdlet para enviar la salida ($content) al archivo file.txt.
En los ejemplos anteriores, creamos dos variables denominadas $filePath y $content. $filePath contenía la ruta del archivo file.txt, mientras que $content tenía el contenido real que queríamos agregar. El cmdlet Get-Content se usó para recuperar todos los datos (contenido) del archivo file.txt y mostrarlos en el terminal, lo cual fue útil para ver el contenido actualizado. sin abrir el archivo file.txt.
La única diferencia fue cómo usamos el cmdlet Out-File según los requisitos. Los parámetros -FilePath, -InputObject y -Append fueron los mismos en todos los ejemplos. Entonces, ¿qué significan estos parámetros y por qué los utilizamos?
-FilePath se usó para especificar $filePath, -InputObject se usó para mencionar el $content que queríamos para agregar y -Append se usó para agregar $content al final del archivo file.txt. También puede utilizar el parámetro -Encoding para especificar el tipo de codificación para un archivo de destino. Normalmente, se utiliza la codificación UTF8 mientras que utf8NoBOMes su valor predeterminado. También tenemos otras codificaciones que podemos utilizar según nuestros requisitos.
Ahora, el punto es cómo se formatea el contenido. Se realiza mientras se inicializa la variable $content de cada ejemplo. Configuramos la variable $content en el primer y segundo fragmento de código con un texto simple. En el tercer ejemplo, inicializamos $content con un texto precedido por una `t (carácter especial) para agregar el texto después de una tab.
De manera similar, en el cuarto ejemplo, usamos un operador de matriz representado por @() para crear una matriz de cadenas donde cada cadena era una línea de texto que agregamos al archivo a la vez. Finalmente, en el quinto ejemplo, usamos @() con caracteres especiales para agregar datos en forma tabular; Estos caracteres especiales incluyen un carácter de nueva línea y un carácter de tabulación. Puedes encontrar diferentes caracteres especiales con su descripción a continuación.
- Special Character
Descripción
- `0
Nulo
- `a
Alerta
- `b
Retroceso
- `n
Nueva línea
- `r
Retorno de carro
- `t
Pestaña horizontal
- `'
Cotización única
- `"
Cotización doble
En el séptimo y último ejemplo de esta sección, utilizamos comillas simples y dobles al inicializar el valor de $content. Tenga en cuenta que cada comilla (simple y doble) estaba precedida por una comilla invertida, como se demuestra en la tabla anterior.
Si el archivo, que en nuestro caso era
file.txt, no existe, el cmdletOut-Filelo creará y realizará el resto de las operaciones.
Utilice el cmdlet Agregar contenido
Utilice el cmdlet Add-Content para agregar contenido en la misma línea en el archivo file.txt.
Utilice el cmdlet Agregar contenido:
$filePath = "E:\Test\file.txt"
$content = "This is the second line."
Add-Content -Path $filePath -value $content
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.Utilice el cmdlet Add-Content para agregar contenido en la nueva línea del archivo file.txt.
Utilice el cmdlet Agregar contenido:
$filePath = "E:\Test\file.txt"
$content = "This is the third line."
Add-Content -Path $filePath -value $content
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.Utilice el cmdlet Add-Content para agregar contenido con caracteres especiales (como tabulación) en el archivo file.txt.
Utilice el cmdlet Agregar contenido:
$filePath = "E:\Test\file.txt"
$content = "`tThis fourth line is with tab character."
Add-Content -Path $filePath -value $content
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.Utilice el cmdlet Add-Content para agregar varias líneas en el archivo file.txt.
Utilice el cmdlet Agregar contenido:
$filePath = "E:\Test\file.txt"
$content = @("This is the fifth line.",
"This is the sixth line.",
"This is the seventh line.")
Add-Content -Path $filePath -value $content
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.
This is the fifth line.
This is the sixth line.
This is the seventh line.Utilice el cmdlet Add-Content para agregar contenido tabular (contenido formateado) en el archivo file.txt.
Utilice el cmdlet Agregar contenido:
$filePath = "E:\Test\file.txt"
$content = @("First`tLast`tAge",
"John`tWilliamson`t50",
"Mary`tPurell`t30",
"Sam`tAnderson`t35")
Add-Content -Path $filePath -value $content
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.
This is the fifth line.
This is the sixth line.
This is the seventh line.
First Last Age
John Williamson 50
Mary Purell 30
Sam Anderson 35Utilice el cmdlet Add-Content para agregar una línea que tenga comillas simples y dobles en el archivo file.txt.
Utilice el cmdlet Agregar contenido:
$filePath = "E:\Test\file.txt"
$content = "This is the eighth line having `'single quote`' and `"double qoutes`"."
Add-Content -Path $filePath -value $content
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.
This is the fifth line.
This is the sixth line.
This is the seventh line.
First Last Age
John Williamson 50
Mary Purell 30
Sam Anderson 35
This is the eighth line having 'single quote' and "double quotes".Usamos Add-Content para agregar contenido al archivo dado. Podemos usar este cmdlet especificando el texto en el comando directamente o almacenarlo en un objeto y usar ese objeto mientras usamos el cmdlet Add-Content. Por ejemplo, almacenamos el contenido en la variable $content y usamos esa variable mientras usamos este cmdlet; consulte las vallas de código anteriores.
Los ejemplos de esta sección son similares a aquellos que utilizan el cmdlet Out-File. Nuevamente, definimos e inicializamos $filePath y $content para contener la ruta del archivo y el contenido. El Get-Content se usó para obtener contenido del archivo file.txt y mostrarlo en el terminal. El contenido almacenado en la variable $content fue formateado exactamente como lo hicimos en la sección anterior mientras usábamos el cmdlet Out-File; puedes referirte a eso.
En todos los ejemplos de esta sección, utilizamos los parámetros -Path y -value con el cmdlet Add-Content para especificar $filePath. y $content.
Add-Contentcreará el archivo de texto con un nombre específico si aún no existe. Si no se proporciona la ruta, el archivo de texto se creará en el directorio actual.
Usar operador de redirección (>>)
Utilice el operador >> para agregar contenido en la misma línea en el archivo file.txt.
Utilice el operador de redirección:
$filePath = "E:\Test\file.txt"
$content = "This is the second line."
$content>>$filePath
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.Utilice el operador >> para agregar contenido en la nueva línea del archivo file.txt.
Utilice el operador de redirección:
$filePath = "E:\Test\file.txt"
$content = "This is the third line."
$content>>$filePath
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.Utilice el operador >> para agregar contenido con caracteres especiales (como tabulación) en el archivo file.txt.
Utilice el operador de redirección:
$filePath = "E:\Test\file.txt"
$content = "`tThis fourth line is with tab character."
$content>>$filePath
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.Utilice el cmdlet>> para agregar varias líneas en el archivo file.txt.
Utilice el operador de redirección:
$filePath = "E:\Test\file.txt"
$content = @("This is the fifth line.",
"This is the sixth line.",
"This is the seventh line.")
$content>>$filePath
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.
This is the fifth line.
This is the sixth line.
This is the seventh line.Utilice el operador >> para agregar contenido tabular (contenido formateado) en el archivo file.txt.
Utilice el cmdlet Agregar contenido:
$filePath = "E:\Test\file.txt"
$content = @("First`tLast`tAge",
"John`tWilliamson`t50",
"Mary`tPurell`t30",
"Sam`tAnderson`t35")
$content>>$filePath
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.
This is the fifth line.
This is the sixth line.
This is the seventh line.
First Last Age
John Williamson 50
Mary Purell 30
Sam Anderson 35Utilice el operador >> para agregar una línea que tenga comillas simples y dobles en el archivo file.txt.
Utilice el cmdlet Agregar contenido:
$filePath = "E:\Test\file.txt"
$content = "This is the seventh line having `'single quote`' and `"double quotes`"."
$content>>$filePath
Get-Content $filePathPRODUCCIÓN :
This is the first line.This is the second line.
This is the third line.
This fourth line is with tab character.
This is the fifth line.
This is the sixth line.
This is the seventh line.
First Last Age
John Williamson 50
Mary Purell 30
Sam Anderson 35
This is the seventh line having 'single quote' and "double quotes".Estos ejemplos, cmdlets y variables son los mismos que en las secciones anteriores, pero usamos el operador de redirección para agregar el archivo file.txt.
El operador de redirección creará el archivo de texto en el directorio especificado (o en el directorio actual si no se proporciona) si aún no existe.
Agregar un archivo de texto a otro
Utilice Add-Content para agregar el contenido de un archivo de texto a otro archivo de texto en PowerShell.
Contenido del archivo file1.txt:
This is the file1 line.Contenido del archivo file2.txt:
This is the file2 line.Utilice el cmdlet Agregar contenido:
$sourceFile = "E:\Test\file2.txt"
$destinationFile = "E:\Test\file1.txt"
$sourceFileContent = Get-Content -Path $sourceFile
Add-Content -Path $destinationFile -value $sourceFileContent
Get-Content $destinationFileSALIDA:
This is the file1 line.This is the file2 line.Se trata de cómo agregar datos a un archivo usando PowerShell.
