3

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"
}

1 Answer 1

7

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

 "$env:userprofile\Desktop\log.txt" 
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. That fixed it. Do all cmd.exe commands not work in powershell?
@AndrewRynhard If the command is implemented with cmd.exe then it will not work in PowerShell unless you invoke it via & cmd.exe /c <DOS COMMAND HERE>. If the command is actually a command line program like xcopy it will work fine in PowerShell.
Andy is spot on for commands, but the percent (%) indicator falls under a different, though like-minded, rule: if the feature is implemented by cmd.exe then you must find the analogous feature in PowerShell. In this instance, %xyz% indicates an environment variable under cmd.exe, while $env:xyz indicates the same env var in PowerShell.
@msorens Actually you can pass in cmd.exe operators. Try these: & cmd.exe /c echo '%userprofile%\Desktop\log.txt' and & cmd.exe /c dir '"%ProgramFiles%"' '&' dir '"%windir%"'. They just get sent as strings to cmd.exe which evaluates them at runtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.