How to reload user profile from script file in PowerShell

后端 未结 8 564
情深已故
情深已故 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:04
    & $profile   
    

    works to reload the profile.

    If your profile sets aliases or executes imports which fail then you will see errors because they were already set in the previous loading of the profile.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题