-
-
Save eizedev/be7211b0e0cdd04050225054722c306d to your computer and use it in GitHub Desktop.
A PowerShell script to create a new gist on Github.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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