PowerShell, GitHub, and the GH Cli

Here’s another quick one – using the GitHub CLI to copy a repository from GitHub, bring it down to your local machine, and then copy it to a remote server. Great for quickly setting up a new automation server or re-baseline an existing box.

Before running the script, ensure:

  • You have permissions to access the remote server and write to the target directory.
  • PowerShell Remoting is enabled on the remote server if you’re using a PowerShell session for the transfer.
  • The GitHub CLI is installed and configured on your machine.

Here’s the script!

# Define variables
$repoUrl = "https://github.com/username/repository" # Replace with your GitHub repository URL
$tempDir = Join-Path -Path $env:TEMP -ChildPath "github_repo_temp"
$remoteServer = "\\remote-server\share" # Replace with your remote server share path
$remotePath = "path\to\destination\folder" # Replace with your remote destination path, relative to the share

# Ensure the temp directory does not already exist
if (Test-Path -Path $tempDir) {
    Remove-Item -Path $tempDir -Recurse
}

# Clone the repository to the temporary directory
gh repo clone $repoUrl $tempDir

# Assuming the remote server is accessible via a network share
$fullRemotePath = Join-Path -Path $remoteServer -ChildPath $remotePath

# Ensure the remote directory exists
if (-not (Test-Path -Path $fullRemotePath)) {
    New-Item -Path $fullRemotePath -ItemType Directory
}

# Copy the contents to the remote server
Copy-Item -Path "$tempDir\*" -Destination $fullRemotePath -Recurse

# Clean up the temporary directory
Remove-Item -Path $tempDir -Recurse

Write-Host "Repository contents have been copied to the remote server."

And that’s it! Consider putting it in a scheduler to always ensure that your remote automation servers are up to date and using your latest code.

Enjoy!