PowerShell:在用户之间静态地在桌面快捷方式中使用 $env:userprofile

PowerShell: Using $env:userprofile in a desktop shortcut statically between users

我有一个 PowerShell 程序可以在系统上生成一些新的用户帐户。在每个用户中,我都有一个在用户帐户内某处创建的日志文件夹,以及一个链接到该日志文件夹的关联桌面快捷方式。为此,我将快捷方式的目标路径设置为 $env:userprofile + "\LogsFolder"

我 运行 遇到的问题是,在当前帐户(生成新帐户和日志文件夹的帐户)上,快捷方式本身将保留 $env:userprofile 变量。因此,当我导航到 C:\Users\NewUser\shortcut 时,我没有看到指向 C:\Users\NewUser\LogsFolder 的快捷方式,而是指向 C:\Users\CurrentUser\LogsFolder,这是完全不同的。

如果我登录到 NewUser,快捷方式将正确导航到 C:\Users\NewUser\LogsFolder,但当我重新登录到 CurrentUser 时,它会导致错误的文件夹。我的问题是,当我生成这些快捷方式时,如何静态存储 $env:userprofile 路径,这样我得到的不是 $env:userprofile\LogsFolder,而是 C:\Users\NewUser\LogsFolder,这样快捷方式路径在不同用户之间保持静态?

快速更新以获得更好的解释:由于管理员帐户可以导航到其他用户文件夹,我希望管理员帐户能够单独访问每个用户的日志文件夹,而不必登录到不同的文件夹用户以便获取他们的日志。

脚本布局更新:管理员帐户 运行 是创建实际新用户帐户的用户生成器脚本,然后它拥有这些用户帐户 运行 shortcut/logging 在桌面上创建新快捷方式的脚本。我没有向 shortcut/logging 脚本提供任何用户名或参数,并且由于新用户帐户是 运行,$env:userprofile 变量用于告诉脚本将每个快捷方式放在哪里.我想避免手动向脚本提供每个帐户的用户名,因为 $env:userprofile 似乎可以正常工作,但由于快捷方式本身在用户之间发生变化,似乎最有意义的解决方案是提供帐户名直接到 shortcut/logging 脚本,以便它可以静态生成快捷方式。然而,这需要修改 shortcut/logging 脚本的大修结构,这是主要问题,也是我想要 $env:userprofile 本身的实际内容的原因。

我的代码示例供参考:

$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”,具体取决于当前用户。

使用expandable (double-quoted) string ("...")"$($env:USERPROFILE)\..."(可以简化为"$env:USERPROFILE\..."),立即扩展为[=的值14=] 环境变量 当时定义的 ,因此使用 生成 新用户的帐户路径,而不是新用户。

因此,您需要:

# Create the shortcut file in the *new users*'s profile folder.
# This requires you to specify the path (ultimately) *literally, statically*.
# I'm assuming that the new user's username is stored in $newUser:
$newUserProfile = "C:\Users$newUser"
$shell.createshortcut("$newUserProfile\shortcut.lnk")

# For a shortcut file created in a dir. specific to the new user,
# you *can* use an environment-variable reference as follows:
$shortcut.TargetPath = '%USERPROFILE%\LogsFolder'
# Alternatively, for a *static* value, use:
#  "$newUserProfile\LogsFolder"

快捷方式文件 (.lnk) 支持 cmd.exe 风格,未扩展 environment-variable 引用,扩展 at打开快捷方式的时间,当以新用户身份登录时,它将扩展到他们的个人资料目录。