Skip to content

Instantly share code, notes, and snippets.

@isnikulin
Created October 31, 2025 10:29
Show Gist options
  • Select an option

  • Save isnikulin/dd18b18082e81514b4e83ad53aa7dc41 to your computer and use it in GitHub Desktop.

Select an option

Save isnikulin/dd18b18082e81514b4e83ad53aa7dc41 to your computer and use it in GitHub Desktop.
Generate secure password from terminal and automatically save to clipboard
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Generates a strong random password.
Supports length, simple mode (no special chars), and JSON output.
#>
param(
[Parameter(Position = 0)]
[int]$Length = 8,
[switch]$Simple, # Exclude special characters
[switch]$Json # Output in JSON format
)
if ($Length -lt 8) {
Write-Error "Password length should be at least 8 characters."
exit 1
}
# Define character sets
$Lowercase = 'abcdefghijklmnopqrstuvwxyz'
$Uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
$Digits = '0123456789'
$Special = if (-not $Simple) { '!@#$%^&*' } else { '' }
# Combine all allowed characters
$AllChars = ($Lowercase + $Uppercase + $Digits + $Special)
if ([string]::IsNullOrEmpty($AllChars)) {
Write-Error "No characters available for password generation."
exit 1
}
# Initialize RNG
$Rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
function Get-RandomChar([string]$Charset) {
# Securely select one character from the given charset
$bytes = New-Object byte[] 4
$Rng.GetBytes($bytes)
$index = [BitConverter]::ToUInt32($bytes, 0) % $Charset.Length
return $Charset[$index]
}
# Ensure at least one of each character type
$PasswordChars = @(
(Get-RandomChar $Lowercase)
(Get-RandomChar $Uppercase)
(Get-RandomChar $Digits)
)
if (-not $Simple) {
$PasswordChars += (Get-RandomChar $Special)
}
# Fill remaining length
for ($i = $PasswordChars.Count; $i -lt $Length; $i++) {
$PasswordChars += Get-RandomChar $AllChars
}
# Shuffle securely
for ($i = $PasswordChars.Count - 1; $i -gt 0; $i--) {
$bytes = New-Object byte[] 4
$Rng.GetBytes($bytes)
$j = [BitConverter]::ToUInt32($bytes, 0) % ($i + 1)
$temp = $PasswordChars[$i]
$PasswordChars[$i] = $PasswordChars[$j]
$PasswordChars[$j] = $temp
}
$Password = -join $PasswordChars
# Output result
if ($Json) {
# Simple JSON structure: {"password":"..."}
$Obj = @{ password = $Password } | ConvertTo-Json -Compress
$Password | Set-Clipboard
Write-Output $Obj
} else {
$Password | Set-Clipboard
Write-Output "Generated Password: $Password"
}
$Rng.Dispose()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment