Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: how to read an environment variable?

Tags:

powershell

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"
}
like image 802
arynhard Avatar asked Jan 26 '26 10:01

arynhard


1 Answers

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

 "$env:userprofile\Desktop\log.txt" 
like image 71
Andy Arismendi Avatar answered Jan 29 '26 03:01

Andy Arismendi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!