Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 319
banditFox Avatar asked May 20 '14 15:05

banditFox


People also ask

What is userprofile in PowerShell?

The directory pointed at with the environment variable %userprofile% stores personal data of a specific user. The value of %userprofile% usually is c:\Users\username ( username being lowercase of %username% ?)

How do I list all environment variables in PowerShell?

Environment variables in PowerShell are stored as PS drive (Env: ). To retrieve all the environment variables stored in the OS you can use the below command. You can also use dir env: command to retrieve all environment variables and values.


1 Answers

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
}
like image 91
arco444 Avatar answered Oct 17 '22 09:10

arco444