@@ -916,15 +916,19 @@ elseif ($args[0] -eq 'protocolhandle') {
916916}
917917
918918# 向用户的$Profile中注册导入fount-pwsh
919+ # 用 File IO 读写,避免 Get-Content/Set-Content 同文件流竞争导致 "Stream was not readable"
919920if ($Profile -and (Get-Module fount- pwsh - ListAvailable)) {
920- $ProfileContent = Get-Content $Profile - ErrorAction Ignore
921- $ProfileContent = $ProfileContent -split " `n "
922- $ProfileContent = $ProfileContent | Where-Object { $_ -notmatch ' Import-Module fount-pwsh' }
923- $ProfileContent = $ProfileContent -join " `n "
924- $ProfileContent += " `n Import-Module fount-pwsh`n "
925- $ProfileContent = $ProfileContent -replace ' \n+Import-Module fount-pwsh' , " `n Import-Module fount-pwsh"
926- if ($ProfileContent -ne (Get-Content $Profile - ErrorAction Ignore)) {
927- Set-Content - Path $Profile - Value $ProfileContent
921+ $profileDir = Split-Path - Parent $Profile
922+ if ($profileDir -and -not (Test-Path - LiteralPath $profileDir )) {
923+ New-Item - ItemType Directory - Path $profileDir - Force | Out-Null
924+ }
925+ $existing = if (Test-Path - LiteralPath $Profile ) { [IO.File ]::ReadAllText($Profile ) } else { ' ' }
926+ $nl = if ($existing.Contains (" `r`n " )) { " `r`n " } else { " `n " }
927+ $stripped = [regex ]::Replace($existing , ' (?m)^\s*Import-Module\s+fount-pwsh\s*\r?\n?' , ' ' )
928+ $stripped = $stripped.TrimEnd (" `r " , " `n " )
929+ $newContent = $ (if ($stripped ) { $stripped + $nl } else { ' ' }) + " Import-Module fount-pwsh$nl "
930+ if ($newContent -ne $existing ) {
931+ [IO.File ]::WriteAllText($Profile , $newContent )
928932 }
929933}
930934
@@ -1754,13 +1758,14 @@ elseif ($args[0] -eq 'remove') {
17541758
17551759 # Remove fount-pwsh from PowerShell Profile
17561760 Write-Host (Get-I18n - key ' remove.removingFountPwshFromProfile' )
1757- if (Test-Path $Profile ) {
1758- $ProfileContent = Get-Content $Profile - ErrorAction Ignore
1759- $ProfileContent = $ProfileContent -split " `n "
1760- $ProfileContent = $ProfileContent | Where-Object { $_ -notmatch ' Import-Module fount-pwsh' }
1761- $ProfileContent = $ProfileContent -join " `n "
1762- if ($ProfileContent -ne ((Get-Content $Profile - ErrorAction Ignore) -split " `n " -join " `n " )) {
1763- Set-Content - Path $Profile - Value $ProfileContent
1761+ if (Test-Path - LiteralPath $Profile ) {
1762+ $existing = [IO.File ]::ReadAllText($Profile )
1763+ $nl = if ($existing.Contains (" `r`n " )) { " `r`n " } else { " `n " }
1764+ $newContent = [regex ]::Replace($existing , ' (?m)^\s*Import-Module\s+fount-pwsh\s*\r?\n?' , ' ' )
1765+ $newContent = $newContent.TrimEnd (" `r " , " `n " )
1766+ if ($newContent ) { $newContent += $nl }
1767+ if ($newContent -ne $existing ) {
1768+ [IO.File ]::WriteAllText($Profile , $newContent )
17641769 }
17651770 Write-Host (Get-I18n - key ' remove.fountPwshRemovedFromProfile' )
17661771 }
0 commit comments