PowerShell:在'IF'语句中使用$ env:userprofile

ban*_*Fox 8 powershell environment-variables desktop-shortcut

我正在使用PowerShell ISE(我认为4).

我正在编写登录脚本来替换旧的'*.BAT'文件.

我试图在从桌面"创建/删除"某些目录之前测试用户配置文件条件.

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

所以我运行以下内容来查看发生了什么:

md -Path $env:userprofile\Desktop\ITFILES
Run Code Online (Sandbox Code Playgroud)

路径在以下位置创建:C:\ Windows\System32 .........

上面的MD命令工作正常,直到我运行'IF'语句.我想我可能不明白这个$env:userprofile部分是如何工作的.

有任何想法吗?

arc*_*444 13

在Windows 7上:

[PS]> echo $ENV:UserProfile
C:\Users\arco444
Run Code Online (Sandbox Code Playgroud)

这将返回配置文件目录的路径.因此,我希望只查找用户名以使条件失败.我会做一个简单的比赛:

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

  • @banditFox 赋值运算符意味着您正在更改该特定 PowerShell 会话中 $env:userprofile 变量的值(它对其他 PowerShell 会话或操作系统其余部分没有任何影响)。在 PowerShell 中,“==”也不是比较运算符。PowerShell 的 equals 比较运算符是“-eq”。我建议您运行 PowerShell 命令“Get-Help about_Comparison_Operators”来了解有关 PowerShell 中比较运算符的更多信息。 (3认同)