How to reload user profile from script file in PowerShell

后端 未结 8 586
情深已故
情深已故 2020-12-29 01:02

I want to reload my user profile from a script file. I thought that dot sourcing it from within the script file would do the trick, but it doesn\'t work:

# f         


        
8条回答
  •  佛祖请我去吃肉
    2020-12-29 02:06

    I found this workaround:

    #some-script.ps1
    
    #restart profile (open new powershell session)
    cmd.exe /c start powershell.exe -c { Set-Location $PWD } -NoExit
    Stop-Process -Id $PID

    A more elaborated version:

    #publish.ps1
    # Copy profile files to PowerShell user profile folder and restart PowerShell
    # to reflect changes. Try to start from .lnk in the Start Menu or
    # fallback to cmd.exe.
    # We try the .lnk first because it can have environmental data attached
    # to it like fonts, colors, etc.
    
    [System.Reflection.Assembly]::LoadWithPartialName("System.Diagnostics")
    
    $dest = Split-Path $PROFILE -Parent
    Copy-Item "*.ps1" $dest -Confirm -Exclude "publish.ps1" 
    
    # 1) Get .lnk to PowerShell
    # Locale's Start Menu name?...
    $SM = [System.Environment+SpecialFolder]::StartMenu
    $CurrentUserStartMenuPath = $([System.Environment]::GetFolderPath($SM))
    $StartMenuName = Split-Path $CurrentUserStartMenuPath -Leaf                                 
    
    # Common Start Menu path?...
    $CAD = [System.Environment+SpecialFolder]::CommonApplicationData
    $allUsersPath = Split-Path $([System.Environment]::GetFolderPath($CAD)) -Parent
    $AllUsersStartMenuPath = Join-Path $allUsersPath $StartMenuName
    
    $PSLnkPath = @(Get-ChildItem $AllUsersStartMenuPath, $CurrentUserStartMenuPath `
                                            -Recurse -Include "Windows PowerShell.lnk")
    
    # 2) Restart...
    # Is PowerShell available in PATH?
    if ( Get-Command "powershell.exe" -ErrorAction SilentlyContinue ) {
    
        if ($PSLnkPath) {
    
            $pi = New-Object "System.Diagnostics.ProcessStartInfo"
            $pi.FileName = $PSLnkPath[0]
            $pi.UseShellExecute = $true
    
            # See "powershell -help" for info on -Command
            $pi.Arguments = "-NoExit -Command Set-Location $PWD"
    
            [System.Diagnostics.Process]::Start($pi)
        }
        else { 
    
            # See "powershell -help" for info on -Command
            cmd.exe /c start powershell.exe -Command { Set-Location $PWD } -NoExit
        }
    }
    else {
        Write-Host -ForegroundColor RED "Powershell not available in PATH."
    }
    
    # Let's clean up after ourselves...
    Stop-Process -Id $PID
    

提交回复
热议问题