PoshCode Archive  Artifact [4ee3924d8a]

Artifact 4ee3924d8a5f8cf49f6c6cbebfff53f6c2da14ff492e23a2af0a31b270fe5ed5:

  • File New-RandomPassword.ps1 — part of check-in [898666f303] at 2018-06-10 13:17:07 on branch trunk — Creates a random password with the specified length and number of non-alphanumeric characters. Returns clear text or a secure string depending on whether switch AsSecureString is specified. (user: Andy Arismendi size: 2173)

# encoding: ascii
# api: powershell
# title: New-RandomPassword
# description: Creates a random password with the specified length and number of non-alphanumeric characters. Returns clear text or a secure string depending on whether switch AsSecureString is specified.
# version: 0.1
# type: function
# author: Andy Arismendi
# license: CC0
# function: New-RandomPassword
# x-poshcode-id: 2929
# x-archived: 2011-11-05T16:30:27
# x-published: 2011-08-26T14:13:00
#
#
function New-RandomPassword {
	[CmdletBinding()]
	param(
		[Int16] $Length = 6,

		[Int16] $NumberOfNonAlphaNumericCharacters = 3,
				
		[Switch] $AsSecureString
	)

	Begin {
		try {
			# Load required assembly.
		$assem = [System.Reflection.Assembly]::LoadWithPartialName('System.Web')
		} catch {
			throw 'Failed to load required assembly [System.Web.Security]. The error was: "{0}".' -f $_
		}
	}
	
	Process {
		try {
			$generatedPassword = [System.Web.Security.Membership]::GeneratePassword($Length, $NumberOfNonAlphaNumericCharacters)
			if ($AsSecureString) {
				return ConvertTo-SecureString -String $generatedPassword -AsPlainText -Force
			} else {
				return $generatedPassword
			}
		} catch {
			throw 'Failed to generate random password. The error was: "{0}".' -f $_
		}
	}
	
	End {
		Get-Variable | Where-Object {$_.Name -eq 'generatedPassword'} | Remove-Variable -Force
	}
	
	<#
		.SYNOPSIS
			Generates a random password.
	
		.PARAMETER  Length
			The password length.
	
		.PARAMETER  NumberOfNonAlphaNumericCharacters
			The number of non-alphanumeric characters to include in the password.
			
		.PARAMETER  AsSecureString
			Return the password in the form of a secure string instead of clear text.
	
		.EXAMPLE
			PS C:\> New-RandomPassword
	
		.EXAMPLE
			PS C:\> New-RandomPassword -AsSecureString
	
		.INPUTS
			None.
	
		.OUTPUTS
			System.String, System.Security.SecureString
	
		.NOTES
			Revision History
				2011-08-26: Andy Arismendi - Created.
	
		.LINK
			http://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword.aspx
	#>
}

New-RandomPassword -Length 14