PowerShell: Using $env:userprofile in an 'IF' statement

banditFox picture banditFox · May 20, 2014 · Viewed 55.5k times · Source

I am using PowerShell ISE (I think 4).

I am writing logon scripts to replace the old '*.BAT' files.

I am trying to test for a user-profile condition before 'creating/deleting' certain directories from the desktop.

Example

If(($env:userprofile = "rmullins"))
    {
        Remove-Item $env:userprofile\Desktop\ITFILES -Recurse -Force
    }

So I run the following to see what's going on:

md -Path $env:userprofile\Desktop\ITFILES

The path is created in the following location: C:\Windows\System32.........

The MD command above works fine until I run that 'IF' statement. I think I might not understand how the $env:userprofile part works.

Any ideas?

Answer

arco444 picture arco444 · May 20, 2014

On Windows 7:

[PS]> echo $ENV:UserProfile
C:\Users\arco444

This returns the path to the profile directory. Therefore I'd expect looking only for the username to fail the condition. I'd do a simple match instead:

if ($env:userprofile -imatch "rmullins")
{
    Remove-Item $env:userprofile\Desktop\ITFILES -Recurse -Force
}