Skip to content

Instantly share code, notes, and snippets.

@jdhitsolutions
Last active March 16, 2023 11:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jdhitsolutions/06cb62bf3eb4f0a1f7d82ed39b1e56ca to your computer and use it in GitHub Desktop.
Save jdhitsolutions/06cb62bf3eb4f0a1f7d82ed39b1e56ca to your computer and use it in GitHub Desktop.
A PowerShell script to create a new gist on Github.
#requires -version 4.0
Function New-GitHubGist {
[cmdletbinding(SupportsShouldProcess,DefaultParameterSetName = "Content")]
Param(
[Parameter(Position = 0, Mandatory, HelpMessage = "What is the name for your gist?",ValueFromPipelineByPropertyName)]
[ValidateNotNullorEmpty()]
[string]$Name,
[Parameter(ParameterSetName="path",Mandatory,ValueFromPipelineByPropertyName)]
[ValidateNotNullorEmpty()]
[Alias("pspath")]
[string]$Path,
[Parameter(ParameterSetName="Content",Mandatory)]
[ValidateNotNullorEmpty()]
[string[]]$Content,
[string]$Description,
[Alias("token")]
[ValidateNotNullorEmpty()]
[string]$UserToken = $gitToken,
[switch]$Private,
[switch]$Passthru
)
Begin {
Write-Verbose "[BEGIN ] Starting: $($MyInvocation.Mycommand)"
#create the header
$head = @{
Authorization = 'Basic ' + $UserToken
}
#define API uri
$base = "https://api.github.com"
} #begin
Process {
#display PSBoundparameters formatted nicely for Verbose output
[string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd()
Write-Verbose "[PROCESS] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*2)$_"}) | Out-String) `n"
#json section names must be lowercase
#format content as a string
switch ($pscmdlet.ParameterSetName) {
"path" {
$gistContent = Get-Content -Path $Path | Out-String
}
"content" {
$gistContent = $Content | Out-String
}
} #close Switch
$data = @{
files = @{$Name = @{content = $gistContent}}
description = $Description
public = (-Not ($Private -as [boolean]))
} | Convertto-Json
Write-Verbose ($data| out-string)
Write-Verbose "[PROCESS] Posting to $base/gists"
If ($pscmdlet.ShouldProcess("$name [$description]")) {
#parameters to splat to Invoke-Restmethod
$invokeParams = @{
Method = 'Post'
Uri = "$base/gists"
Headers = $head
Body = $data
ContentType = 'application/json'
}
$r = Invoke-Restmethod @invokeParams
if ($Passthru) {
Write-Verbose "[PROCESS] Writing a result to the pipeline"
$r | Select @{Name="Url";Expression = {$_.html_url}},
Description,Public,
@{Name = "Created";Expression = {$_.created_at -as [datetime]}}
}
} #should process
} #process
End {
Write-Verbose "[END ] Ending: $($MyInvocation.Mycommand)"
} #end
} #end function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment