[英]PowerShell: Using $env:userprofile in a desktop shortcut statically between users
我有一个 PowerShell 程序,可以在系统上生成一些新的用户帐户。 在每个用户中,我都有一个在用户帐户中某处创建的日志文件夹,以及一个链接到该日志文件夹的关联桌面快捷方式。 为此,我将快捷方式的目标路径设置为$env:userprofile + "\LogsFolder"
我遇到的问题是,在当前帐户(生成新帐户和日志文件夹的帐户)上,快捷方式本身将保留 $env:userprofile 变量。 So when I navigate to C:\Users\NewUser\shortcut
, I don't see the shortcut going to C:\Users\NewUser\LogsFolder
, but instead it leads to C:\Users\CurrentUser\LogsFolder
, which is entirely different .
如果我登录 NewUser,快捷方式将正确导航到C:\Users\NewUser\LogsFolder
,但当我重新登录 CurrentUser 时会导致错误的文件夹。 我的问题是,当我生成这些快捷方式时,如何静态存储 $env:userprofile 路径,而不是$env:userprofile\LogsFolder
我得到C:\Users\NewUser\LogsFolder
,所以快捷方式路径仍然是 ZA81259CEF8E959C624DF1D456E5D329Z7 之间不同的用户?
我的代码示例供参考:
$shell = New-Object -ComObject ("Wscript.shell")
# Correctly generates the shortcut on the new user/user who is running the script
$shortcut = $shell.createshortcut("$($env:USERPROFILE)\shortcut.lnk")
# Path changes depending on who is logged in
$shortcut.TargetPath = "$($env:USERPROFILE)\LogsFolder"
$shortcut.Save()
期望的行为:$shortcut.TargetPath 静态设置为“C:\Users\NewUser\LogsFolder”
当前行为:$shortcut.TargetPath 是“C:\Users\CurrentUser\LogsFolder”或“C:\Users\NewUser\LogsFolder”,具体取决于当前用户。
使用可扩展(双引号)字符串( "..."
) "$($env:USERPROFILE)\..."
(可以简化为"$env:USERPROFILE\..."
),立即展开到当时定义的USERPROFILE
环境变量的值,因此使用生成新用户的帐户的路径,而不是新用户的路径。
因此,您需要以下内容:
# Path changes depending on who is logged in
$shortcut.TargetPath = '%USERPROFILE%\LogsFolder'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.