PowerShell: Append to File

Overview

I ran into an issue the other day where I needed to append a web site to the exception site list for Java. I also needed to keep what sites, if any, that were already listed intact. I also needed to create the exception.sites file if there were no pre existing sites, because the file does not exist until a site is added.

The Details

The following script will either do one of two things: (1) Create the exception.sites file and append your website since it does not exist or (2) Read the content of the exception.sites list, since it already exist, and append the web site you are trying to add if it does not already exist.
Below is specially characters used when using adding content to your file.


0 -- Null
`a -- Alert
`b -- Backspace
`n -- New line
`r -- Carriage return
`t -- Horizontal tab
`' -- Single quote
`" -- Double quote

PowerShell Code

$filelocation = "$env:USERPROFILE\AppData\LocalLow\Sun\Java\Deployment\security\"
$file = "$env:USERPROFILE\AppData\LocalLow\Sun\Java\Deployment\security\exception.sites"
$site1 = "`nmicrosoft.com"

#check if exceptions.sites file exist
if (!(Test-Path"$file"))
{
    New-Item -Path$filelocation -nameexception .sites -type"file"
    Write-Host "exception.sites file has been created" -ForegroundColorYellow
    Add-Content -Path$file -Value$site1
    Write-Host "$site1 has been added to exception.sites" -ForegroundColorYellow
}
Else
{
    Write-Host "exception.sites has already exist" -ForegroundColorYellow
    
    #check if content exist withing the file
    IF (!(Get-Content $file).Contains($site1))
    {
        Write-Host "$site1 already exist" -ForegroundColor Yellow
    }
    Else
    {
        #add content to file since it does not exist
        Add-Content -Path$file -Value$site1
        Write-Host "$site1 has been added to exception.sites" -ForegroundColorYellow
    }
}

Screenshots


Post a Comment

0 Comments