Category Archives: Powershell demo

How to Append Data to a Text File Using PowerShell

 Here’s we can discuss on how to add text to the end of a text file using the Add-Content cmdlet using PowerShell.  In our example let’s add “This is the last line” to the end of a file using add-content cmdlet to append data to a text file.

Add-Content "C:\dotnet-helpers\DummyfiletoDelete.txt" "This is the last line"

The above example above adds the text to the last line of the text, it doesn’t actually create a new line. We can use an escape character to tell PowerShell to add a carriage return, new line… while appending the text in existing file.

Escape characters:

‘n — New line
‘t — Horizontal tab
‘’ — Single quote
‘” — Double quote
‘0 — Null
‘a — Alert
‘b — Backspace
‘r — Carriage return

Append Text using Escape characters:

Add-Content -Path "C:\dotnet-helpers\DummyfiletoDelete.txt" -Value "`r`nThis is the last line".

The above example append the “This is the last line” as a new line at end of the text file with help of ‘n and’ r

Add-Content -Path "C:\dotnet-helpers\DummyfiletoDelete.txt" -Value "This is the last line added from $env:computername system"

 

 OUTPUT:

 

How to Delete a Folder or File using PowerShell

Use PowerShell to Delete a Single File or Folder

Before start executing the Delete powershell command we need to make sure you are logged in to the server or PC with an account that has full access to the objects you want to delete.

# Using PowerShell commnads to delete a file
Remove-Item -Path "C:\dotnet-helpers\DummyfiletoDelete.txt"

The above command will excute and delete the “DummyfiletoDelete.txt” file which present inside the “C:\dotnet-helpers” location.

Use PowerShell to Delete all File and Folders inside the folder

We can also use wildcard ‘*’ characters to remove multiple items. For example, this command removes all the files in “C:\dotnet-helpers\*.*”

# Using PowerShell commnads to delete all file
Remove-Item -Path "C:\dotnet-helpers\*.*"

# Using PowerShell commnads to delete all file and folders
Remove-Item -Path "C:\dotnet-helpers\*.*" -recurse

Recurse drills down and finds lots more files. The –recurse parameter will allow PowerShell to remove any child items without asking for permission. Additionally, the –force parameter can be added to delete hidden or read-only files.

Using -Force command to delete files force fully

# Using PowerShell commnads to delete all file force fully
Remove-Item -Path "C:\dotnet-helpers\*.*" -Force

The above command will delete all hidden or read-only files from the location “C:\dotnet-helpers\”