由於經常需要重裝開發環境,每次都手動生成並上傳這些 Token 到 GitHub,這一過程讓我感到繁瑣不便。因此,我撰寫了一個腳本來簡化這項工作。
$personalAccessToken = "your totken" $yourRepo ="NextJS.git" $githubUser = "MarkKu666" $githubEmail = "[email protected]" ## 設定Git資料 $gitRepo = "[email protected]:$githubUser/$yourRepo" $destinationFolder = "C:\Your\Destination\Folder"
Write-Host "Generating SSH key..." ssh-keygen -t rsa -b 4096 -C $githubEmail
Write-Host "Your new SSH key:" $sshPublicKey = Get-Content "$env:USERPROFILE\.ssh\id_rsa.pub" | Out-String | ForEach-Object { $_ -replace "`n","" -replace "`r","" } $sshPublicKey
Write-Host "Updating GitHub SSH key..." $headers = @{ Authorization = "token $personalAccessToken" Accept = "application/vnd.github.v3+json" } $body = @{ title = "PowerShell generated key" key = $sshPublicKey } | ConvertTo-Json Invoke-RestMethod -Uri "https://api.github.com/user/keys" -Method Post -Body $body -Headers $headers
if(!(Test-Path -Path $destinationFolder )){ Write-Host "Creating destination folder..." New-Item -ItemType directory -Path $destinationFolder }
Write-Host "Cloning git repository..." git clone $gitRepo $destinationFolder