arynhard
arynhard

Reputation: 473

Powershell: how to read an environment variable?

This is the first powershell script I have attempted. When I run it, part one runs fine and creates the log.txt, but after running it again it still runs part 1. How can I check if the log file exists??

EDIT: I forgot to mention that I am running the script from PowerShell ISE if that makes a difference.

#Variables.
#Set working directory to scripts location.
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath

#Check if log file exists.
$ChkFile = "%userprofile%\Desktop\log.txt" 
$FileExists = (Test-Path $ChkFile -PathType Leaf)

#Set dir to script location.
Set-Location $dir

#Part 1.
If (!($FileExists)) 
{
    Write-Host "Part 1"
    echo 0 >>log.txt
}
#Part 2.
ElseIf ($FileExists)
{
    Write-Host "Part 2"
}

Upvotes: 3

Views: 28196

Answers (1)

Andy Arismendi
Andy Arismendi

Reputation: 52689

% is for cmd.exe variable expansion. You need a different syntax for PowerShell. Instead use:

 "$env:userprofile\Desktop\log.txt" 

Upvotes: 7

Related Questions