使用Powershell在桌面上创建“ mydocuments”快捷方式

时间:2019-03-09 01:20:14

标签: powershell shortcut

我正在尝试使用以下脚本在本地PC上创建“ MyDocuments”快捷方式。但是,当我通过Azure Intune运行脚本时,它会创建一个快捷方式,但目标是“ This PC”。

$ShortcutPath = "$env:Public\Desktop\Docu.lnk" 
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($ShortcutPath)
$Shortcut.TargetPath = [environment]::GetFolderPath('MyDocuments')
$Shortcut.Save()

1 个答案:

答案 0 :(得分:0)

尝试这个。您需要管理员权限才能运行此脚本,因为您正在读取其他用户配置文件。

Add-Type -AssemblyName System.DirectoryServices.AccountManagement

$user = "YourUsername" # User to set link to desktop

# get user sid and profilepath

$sid         = (Get-WmiObject -Class win32_useraccount -Filter "name = '$user'").SID
$profilePath = (Get-WmiObject -Class Win32_UserProfile -Filter "SID = '$sid'").LocalPath

if( $profilePath -ne $null ) {

    $currentUser = [System.DirectoryServices.AccountManagement.UserPrincipal]::Current
    $currentSid  = $currentUser.Sid.Value

    # if another user load reg hive

    if( $currentSid -ne $sid ) {
        $pathReg = Resolve-Path "$profilePath\..\$user\NTUSER.DAT"
        reg load "HKU\$sid" $pathReg | Out-Null
    }

    New-PSDrive -Name 'HKUser' -PSProvider Registry -Root "HKEY_USERS" | Out-Null


    # get desktop folder of user

    $shellFolders  = Get-Item "HKUser:\$sid\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
    $desktopFolder = $shellFolders.GetValue("Desktop")
    [void]$shellFolders.Close()
    [void]$shellFolders.Dispose()

    Remove-PSDrive -Name 'HKUser'

    # if another user unload reg hive

    if( $currentSid -ne $sid ) {
        [System.GC]::Collect()
        [System.GC]::WaitForPendingFinalizers()
        try {
            reg unload "HKU\$sid" | Out-Null
        }
        catch {}
    }

    # finally create shortcut

    if( $desktopFolder.Length -gt 0 ) {

        $ShortcutPath = $desktopFolder + '\Docu.lnk'
        $WshShell = New-Object -ComObject WScript.Shell
        $Shortcut = $WshShell.CreateShortcut($ShortcutPath)
        $Shortcut.TargetPath = [environment]::GetFolderPath('MyDocuments')
        [void]$Shortcut.Save()

    }
}