Monday, 8 June 2015

Create a File If Not Exists via PowerShell

We can check if a file exist or not by using the PowerShell cmdlet Test-Path and create new file using New-Item cmdlet.
The below powershell script will check whether the file sample.txt is already exists or not under the path C:\Share. It creates new file if it not exists already and add new text content by using Add-Content cmdlet if file already exists.
if (!(Test-Path "C:\Share\sample.txt"))
{
   New-Item -path C:\Share -name sample.txt -type "file" -value "my new text"
   Write-Host "Created new file and text content added"
}
else
{
  Add-Content -path C:\Share\sample.txt -value "new text content"
  Write-Host "File already exists and new text content added"
}

Advertisements
Advertisements

No comments:

Post a Comment