1

I am pretty new to powershell, this question is going to sound super basic i imagine. but i want my code to check to see if the user has a file in their app data. if the script does not find it. the script will start a process.

i have tried wmi methods but i feel that there is a faster simpler almost one line way to do this i cant think of

$app = Test-Path C:\Users\bobsaget\AppData\Local\Apps\2.0
 if($app = "False"){ Start-Process 'an executable' "/s"}

it changes $app to be false and i see where its happening i just dont fully understand what i am doing wrong with my IF statment.

chupathingy
  • 31
  • 1
  • 5

2 Answers2

3
  1. The = operator in PowerShell assigns a value. For comparison, you want -eq, not =.

  2. If the $app variable contains a boolean value, you don't want to compare it to the string False - you should say -not $app (i.e., the $app variable contains the boolean value $false).

  3. You usually don't need Start-Process to invoke a program. Just use the program's command line. If the executable's name or its path contains white space, prefix it with the & (invocation) operator.

  4. You don't really need the $app variable if you're not going to use it later. You can simply write this:

    if ( Test-Path "C:\Users\bobsaget\AppData\Local\Apps\2.0" ) {
      & "C:\Path\my program.exe" /s
    }
    
Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62
0

A better way to check if a path exists or not in PowerShell

There is a couple ways to do this if you look at the article above. The most basic way to check if a file exists and then execute code would be this:

if (Test-Path $path){
   do stuff 
}

Or this if you want it to execute some code when a path doesn't exist:

if (!(Test-Path $path)){
   do stuff
}
techguy1029
  • 743
  • 10
  • 29