我有一個 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,因此快捷方式路徑在不同用戶之間保持靜態?
快速更新以獲得更好的解釋:由于管理員帳戶可以導航到其他用戶檔案夾,我希望管理員帳戶能夠單獨訪問每個用戶的日志檔案夾,而不是必須登錄到不同的用戶才能獲取他們的日志。
腳本布局更新:管理員帳戶運行創建實際新用戶帳戶的用戶生成器腳本,然后讓這些用戶帳戶運行在桌面上創建新快捷方式的快捷方式/日志記錄腳本。我沒有為快捷方式/日志記錄腳本提供任何用戶名或引數,并且由于它由新用戶帳戶運行,因此 $env:userprofile 變數用于告訴腳本將每個快捷方式放置在何處。我想避免手動將每個帳戶的用戶名提供給腳本,因為它似乎 $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”,具體取決于當前用戶。
uj5u.com熱心網友回復:
使用可擴展(雙引號)字串 ( "..."),"$($env:USERPROFILE)\..."(可以簡化為"$env:USERPROFILE\..."),立即擴展為當時定義的USERPROFILE環境變數的值,因此使用生成新用戶的帳戶的路徑,而不是新用戶的一個。
因此,您需要以下內容:
# 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- 樣式、未展開的環境變數參考,這些參考在打開快捷方式時展開,當以新用戶身份登錄時,它將展開到他們的組態檔目錄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/420892.html
標籤:
