17

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?

Community
  • 1
  • 1
banditFox
  • 173
  • 1
  • 1
  • 5

1 Answers1

25

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
}
arco444
  • 22,002
  • 12
  • 63
  • 67
  • This worked! Thank you so much. Things that didn't work '==' a comparison operator. Now that the problem is solved, what is actually taking place with (($env:userprofile = rmullins)) Am I actually changing my user-profile? Whatever is going on, when I run commands like, 'md %userprofile%/desktop' a path gets created with %userprofile% (percentages and all).... Thanks again folks for the help. – banditFox May 20 '14 at 15:46
  • 3
    @banditFox The assignment operator means that your are changing the value of the $env:userprofile variable in that specific PowerShell session (it does not have any effect on other PowerShell sessions or anything else on the rest of the OS). `==` is not a comparison operator either, in PowerShell. The PowerShell comparison operator for equals is `-eq`. I suggest you run the PowerShell command `Get-Help about_Comparison_Operators` to learn more about the comparison operators in PowerShell. – Robert Westerlund May 20 '14 at 16:35
  • 1
    Why are you not using `$env:username` instead? Would be much more precise. – LUXS Jan 24 '22 at 14:13
  • 1
    As Luxs pointed out, you correctly mention the username but in the code you use userprofile to compare with a username - which always fails. So my advice is to correct it to `$env:username` instead of `$env:userprofile`. And your answer is not only valid for `windows 7` but for recent versions of powershell. – Timo Mar 13 '22 at 20:15
  • 1
    like @Timo said `Write-Output ("$env:userprofile\Desktop" -eq "C:\Users\$env:username\Desktop")` – Isaac Weingarten May 25 '22 at 19:36