git-credential-config.ps1 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # Git Credential Configuration Script
  2. param(
  3. [string]$Username = "",
  4. [string]$Email = "",
  5. [SecureString]$Password = $null,
  6. [switch]$Global = $false
  7. )
  8. # ========== Configure your username, email and password here ==========
  9. $defaultUsername = "yichael" # Change to your Git username
  10. $defaultEmail = "2812319400@qq.com" # Change to your Git email
  11. $defaultPassword = "Qwerty123" # Change to your Git password or access token
  12. # ======================================================================
  13. # Use default values if parameters not provided
  14. if (-not $Username) { $Username = $defaultUsername }
  15. if (-not $Email) { $Email = $defaultEmail }
  16. if (-not $Password) {
  17. $Password = ConvertTo-SecureString $defaultPassword -AsPlainText -Force
  18. }
  19. # Get remote repository URL
  20. $RemoteUrl = git config --get remote.origin.url 2>$null
  21. # Convert SecureString to plain string (only when needed)
  22. $passwordPlain = $null
  23. if ($Password) {
  24. $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
  25. $passwordPlain = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
  26. }
  27. # Set Git configuration
  28. $scope = if ($Global) { "--global" } else { "--local" }
  29. $success = $true
  30. if ($Username) {
  31. git config $scope user.name $Username 2>$null
  32. if ($LASTEXITCODE -ne 0) { $success = $false }
  33. }
  34. if ($Email) {
  35. git config $scope user.email $Email 2>$null
  36. if ($LASTEXITCODE -ne 0) { $success = $false }
  37. }
  38. # Clear old credentials
  39. if ($RemoteUrl -and $RemoteUrl -match "https?://([^/]+)") {
  40. $domain = $Matches[1]
  41. cmdkey /delete:"LegacyGeneric:target=git:https://$domain" 2>$null | Out-Null
  42. git credential-cache exit 2>$null | Out-Null
  43. }
  44. # Set new credentials
  45. if ($passwordPlain -and $RemoteUrl -and $RemoteUrl -match "https?://([^/]+)") {
  46. $domain = $Matches[1]
  47. $credentialInput = "protocol=https`nhost=$domain`nusername=$Username`npassword=$passwordPlain`n`n"
  48. $credentialInput | git credential approve 2>$null
  49. if ($LASTEXITCODE -ne 0) { $success = $false }
  50. # Clear plain password from memory
  51. [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR)
  52. $passwordPlain = $null
  53. }
  54. # Show result
  55. if ($success) {
  56. Write-Host "[OK] Configuration successful" -ForegroundColor Green
  57. } else {
  58. Write-Host "[X] Configuration failed" -ForegroundColor Red
  59. exit 1
  60. }