PoshCode Logo PowerShell Code Repository

Password Generator Form (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2022"></script>download | new post

Creates a form that allows you to generate a random password based on the requirements listed within the code. Can then print out the form to give to user. Password also saved to clipboard and can be pasted into the password reset dialog.

  1.  
  2. Function Create-Password {
  3.         #How many characters in the password
  4.         [int]$passwordlength = 14
  5.        
  6.         ##Make sure that number of characters below are not greater than $passwordlength!!
  7.        
  8.         #Minimum Upper Case characters in password
  9.         [int]$min_upper = 3
  10.        
  11.         #Minimum Lower Case characters in password
  12.         [int]$min_lower = 3
  13.        
  14.         #Minimum Numerical characters in password
  15.         [int]$min_number = 3
  16.        
  17.         #Minimum Symbol/Puncutation characters in password
  18.         [int]$min_symbol = 3
  19.        
  20.         #Misc password characters in password
  21.         [int]$min_misc = ($passwordlength - ($min_upper + $min_lower + $min_number + $min_symbol))
  22.        
  23.         #Characters for the password
  24.         $upper = @("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z")
  25.         $lower = @("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")
  26.         $number = @(1,2,3,4,5,6,7,8,9,0)
  27.         $symbol = @("!","@","#","%","&","(",")","`"",".","<",">","+","=","-","_")
  28.         $combine = $upper + $lower + $number + $symbol
  29.        
  30.         $password = @()
  31.        
  32.         #Start adding upper case into password
  33.         1..$min_upper | % {$password += Get-Random $upper}
  34.         #Add lower case into password            
  35.         1..$min_lower | % {$password += Get-Random $lower}
  36.         #Add numbers into password
  37.         1..$min_number | % {$password += Get-Random $number}
  38.        
  39.         #Add symbols into password
  40.         1..$min_symbol | % {$password += Get-Random $symbol}    
  41.        
  42.         #Fill out the rest of the password length
  43.         1..$min_misc | % {$password += Get-Random $combine}            
  44.        
  45.         #Randomize password
  46.         Get-Random $password -count $passwordlength | % {[string]$randompassword += $_}
  47.         Return $randompassword    
  48.     }
  49. #Generated Form Function
  50. function GenerateForm {
  51.  
  52. #region Import the Assemblies
  53. [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
  54. [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
  55. #endregion
  56.  
  57. #Show popup if not running in -STA mode
  58. If (((get-host).RunSpace).ApartmentState -ne "STA") {
  59.     [System.Windows.Forms.MessageBox]::Show("You are not running Powershell in (Single Threaded Apartment) STA mode! Please restart powershell in STA mode (powershell.exe -STA)","Warning") | Out-Null
  60.     Break
  61.     }
  62.  
  63. #region Generated Form Objects
  64. $form1 = New-Object System.Windows.Forms.Form
  65. $textBox1 = New-Object System.Windows.Forms.TextBox
  66. $lbl_summary = New-Object System.Windows.Forms.Label
  67. $lbl_passwordlabel = New-Object System.Windows.Forms.Label
  68. $btn_generate = New-Object System.Windows.Forms.Button
  69. $chk_printreport = New-Object System.Windows.Forms.CheckBox
  70. $lbl_bottomheader = New-Object System.Windows.Forms.Label
  71. $lbl_topheader = New-Object System.Windows.Forms.Label
  72. $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
  73. #endregion Generated Form Objects
  74.  
  75. #----------------------------------------------
  76. #Generated Event Script Blocks
  77. #----------------------------------------------
  78. #Provide Custom Code for events specified in PrimalForms.
  79. $btn_generate_OnClick= {
  80.     #Saving password to variable
  81.     $password = Create-Password
  82.  
  83.     #Displaying password to screen
  84.     $textBox1.Text = $password
  85.     Start-Sleep -Seconds 1
  86.  
  87.     If ($($chk_printreport.Checked) -eq $True) {
  88.         #Define Printer - Uses Default printer
  89.        
  90. $code = @'
  91. using System;
  92. using System.Runtime.InteropServices;
  93. using System.Drawing;
  94. using System.Drawing.Imaging;
  95. namespace ScreenShotDemo
  96. {
  97.  /// <summary>
  98.  /// Provides functions to capture the entire screen, or a particular window, and save it to a file.
  99.  /// </summary>
  100.  public class ScreenCapture
  101.  {
  102.    /// <summary>
  103.    /// Creates an Image object containing a screen shot of the entire desktop
  104.    /// </summary>
  105.    /// <returns></returns>
  106.    public Image CaptureScreen()
  107.    {
  108.      return CaptureWindow( User32.GetForegroundWindow() );
  109.    }
  110.    /// <summary>
  111.    /// Creates an Image object containing a screen shot of a specific window
  112.    /// </summary>
  113.    /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
  114.    /// <returns></returns>
  115.    public Image CaptureWindow(IntPtr handle)
  116.    {
  117.      // get te hDC of the target window
  118.      IntPtr hdcSrc = User32.GetWindowDC(handle);
  119.      // get the size
  120.      User32.RECT windowRect = new User32.RECT();
  121.      User32.GetWindowRect(handle,ref windowRect);
  122.      int width = windowRect.right - windowRect.left;
  123.      int height = windowRect.bottom - windowRect.top;
  124.      // create a device context we can copy to
  125.      IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
  126.      // create a bitmap we can copy it to,
  127.      // using GetDeviceCaps to get the width/height
  128.      IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height);
  129.      // select the bitmap object
  130.      IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
  131.      // bitblt over
  132.      GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
  133.      // restore selection
  134.      GDI32.SelectObject(hdcDest,hOld);
  135.      // clean up
  136.      GDI32.DeleteDC(hdcDest);
  137.      User32.ReleaseDC(handle,hdcSrc);
  138.      // get a .NET image object for it
  139.      Image img = Image.FromHbitmap(hBitmap);
  140.      // free up the Bitmap object
  141.      GDI32.DeleteObject(hBitmap);
  142.      return img;
  143.    }
  144.    /// <summary>
  145.    /// Captures a screen shot of a specific window, and saves it to a file
  146.    /// </summary>
  147.    /// <param name="handle"></param>
  148.    /// <param name="filename"></param>
  149.    /// <param name="format"></param>
  150.    public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
  151.    {
  152.      Image img = CaptureWindow(handle);
  153.      img.Save(filename,format);
  154.    }
  155.    /// <summary>
  156.    /// Captures a screen shot of the entire desktop, and saves it to a file
  157.    /// </summary>
  158.    /// <param name="filename"></param>
  159.    /// <param name="format"></param>
  160.    public void CaptureScreenToFile(string filename, ImageFormat format)
  161.    {
  162.      Image img = CaptureScreen();
  163.      img.Save(filename,format);
  164.    }
  165.  
  166.    /// <summary>
  167.    /// Helper class containing Gdi32 API functions
  168.    /// </summary>
  169.    private class GDI32
  170.    {
  171.      
  172.      public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
  173.      [DllImport("gdi32.dll")]
  174.      public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
  175.        int nWidth,int nHeight,IntPtr hObjectSource,
  176.        int nXSrc,int nYSrc,int dwRop);
  177.      [DllImport("gdi32.dll")]
  178.      public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth,
  179.        int nHeight);
  180.      [DllImport("gdi32.dll")]
  181.      public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
  182.      [DllImport("gdi32.dll")]
  183.      public static extern bool DeleteDC(IntPtr hDC);
  184.      [DllImport("gdi32.dll")]
  185.      public static extern bool DeleteObject(IntPtr hObject);
  186.      [DllImport("gdi32.dll")]
  187.      public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
  188.    }
  189.  
  190.    /// <summary>
  191.    /// Helper class containing User32 API functions
  192.    /// </summary>
  193.    private class User32
  194.    {
  195.      [StructLayout(LayoutKind.Sequential)]
  196.      public struct RECT
  197.      {
  198.        public int left;
  199.        public int top;
  200.        public int right;
  201.        public int bottom;
  202.      }
  203.      [DllImport("user32.dll")]
  204.      public static extern IntPtr GetDesktopWindow();
  205.      [DllImport("user32.dll")]
  206.      public static extern IntPtr GetWindowDC(IntPtr hWnd);
  207.      [DllImport("user32.dll")]
  208.      public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
  209.      [DllImport("user32.dll")]
  210.      public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);
  211.      [DllImport("user32.dll")]
  212.      public static extern IntPtr GetForegroundWindow();      
  213.    }
  214.  }
  215. }
  216. '@
  217.  
  218. add-type $code -ReferencedAssemblies 'System.Windows.Forms','System.Drawing'    
  219.        
  220.         #Print Form
  221.                 $form1.FormBorderStyle = 0
  222.         $form1.Activate()
  223.         $fph = New-Object ScreenShotDemo.ScreenCapture
  224.         $img = $fph.CaptureScreen()
  225.         $pd = New-Object System.Drawing.Printing.PrintDocument
  226.         $pd.Add_PrintPage({$_.Graphics.DrawImage(([System.Drawing.Image]$img), 0, 0)})
  227.         $pd.Print()            
  228.  
  229.         $form1.FormBorderStyle = 5
  230.         }    
  231.     #Pasting password to clipboard
  232.     #This will only work if Powershell is running in Single Threaded Apartment (STA): powershell.exe -sta or run from ISE
  233.     #You can check by running the following command: ((get-host).RunSpace).ApartmentState
  234.     [Windows.Forms.Clipboard]::SetText($password)    
  235.  
  236. }
  237.  
  238. $handler_form1_Load=
  239. {
  240.     $form1.TopMost = $True
  241.     $form1.Activate()
  242.  
  243. }
  244.  
  245. $OnLoadForm_StateCorrection=
  246. {#Correct the initial state of the form to prevent the .Net maximized form issue
  247.         $form1.WindowState = $InitialFormWindowState
  248. }
  249.  
  250. #----------------------------------------------
  251. #region Generated Form Code
  252. $form1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,1,3,0)
  253. $form1.BackColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
  254. $form1.Text = "Password Generator"
  255. $form1.AllowDrop = $True
  256. $form1.Name = "form1"
  257. $form1.DataBindings.DefaultDataSourceUpdateMode = 0
  258. $System_Drawing_Size = New-Object System.Drawing.Size
  259. $System_Drawing_Size.Width = 685
  260. $System_Drawing_Size.Height = 496
  261. $form1.ClientSize = $System_Drawing_Size
  262. $form1.FormBorderStyle = 5
  263. $form1.add_Load($handler_form1_Load)
  264.  
  265. $System_Drawing_Size = New-Object System.Drawing.Size
  266. $System_Drawing_Size.Width = 227
  267. $System_Drawing_Size.Height = 19
  268. $textBox1.Size = $System_Drawing_Size
  269. $textBox1.DataBindings.DefaultDataSourceUpdateMode = 0
  270. $textBox1.ReadOnly = $True
  271. $textBox1.BorderStyle = 0
  272. $textBox1.Text = "NOTVALID1"
  273. $textBox1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",12,1,3,0)
  274. $textBox1.Name = "textBox1"
  275. $textBox1.BackColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
  276. $System_Drawing_Point = New-Object System.Drawing.Point
  277. $System_Drawing_Point.X = 304
  278. $System_Drawing_Point.Y = 268
  279. $textBox1.Location = $System_Drawing_Point
  280. $textBox1.TabIndex = 7
  281. $textBox1.add_TextChanged($handler_textBox1_TextChanged)
  282.  
  283. $form1.Controls.Add($textBox1)
  284.  
  285. $lbl_summary.TabIndex = 6
  286. $System_Drawing_Size = New-Object System.Drawing.Size
  287. $System_Drawing_Size.Width = 619
  288. $System_Drawing_Size.Height = 156
  289. $lbl_summary.Size = $System_Drawing_Size
  290. $lbl_summary.Text = "Ensure your password contains at least 3 special characters, 3 numbers, 3 uppercase and 3 lowercase letters for a total of at least 14 characters long. You will be unable to change this password for the next 24 hours."
  291. $lbl_summary.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",12,1,3,0)
  292.  
  293. $System_Drawing_Point = New-Object System.Drawing.Point
  294. $System_Drawing_Point.X = 41
  295. $System_Drawing_Point.Y = 85
  296. $lbl_summary.Location = $System_Drawing_Point
  297. $lbl_summary.DataBindings.DefaultDataSourceUpdateMode = 0
  298. $lbl_summary.Name = "lbl_summary"
  299.  
  300. $form1.Controls.Add($lbl_summary)
  301.  
  302. $lbl_passwordlabel.TabIndex = 4
  303. $lbl_passwordlabel.TextAlign = 64
  304. $System_Drawing_Size = New-Object System.Drawing.Size
  305. $System_Drawing_Size.Width = 111
  306. $System_Drawing_Size.Height = 47
  307. $lbl_passwordlabel.Size = $System_Drawing_Size
  308. $lbl_passwordlabel.Text = "Password:"
  309. $lbl_passwordlabel.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",12,1,3,0)
  310.  
  311. $System_Drawing_Point = New-Object System.Drawing.Point
  312. $System_Drawing_Point.X = 184
  313. $System_Drawing_Point.Y = 254
  314. $lbl_passwordlabel.Location = $System_Drawing_Point
  315. $lbl_passwordlabel.DataBindings.DefaultDataSourceUpdateMode = 0
  316. $lbl_passwordlabel.Name = "lbl_passwordlabel"
  317.  
  318. $form1.Controls.Add($lbl_passwordlabel)
  319.  
  320. $btn_generate.TabIndex = 3
  321. $btn_generate.Name = "btn_generate"
  322. $System_Drawing_Size = New-Object System.Drawing.Size
  323. $System_Drawing_Size.Width = 104
  324. $System_Drawing_Size.Height = 39
  325. $btn_generate.Size = $System_Drawing_Size
  326. $btn_generate.UseVisualStyleBackColor = $True
  327.  
  328. $btn_generate.Text = "Generate"
  329. $btn_generate.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,1,3,0)
  330.  
  331. $System_Drawing_Point = New-Object System.Drawing.Point
  332. $System_Drawing_Point.X = 304
  333. $System_Drawing_Point.Y = 364
  334. $btn_generate.Location = $System_Drawing_Point
  335. $btn_generate.DataBindings.DefaultDataSourceUpdateMode = 0
  336. $btn_generate.add_Click($btn_generate_OnClick)
  337.  
  338. $form1.Controls.Add($btn_generate)
  339.  
  340.  
  341. $chk_printreport.UseVisualStyleBackColor = $True
  342. $chk_printreport.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9,1,3,0)
  343. $System_Drawing_Size = New-Object System.Drawing.Size
  344. $System_Drawing_Size.Width = 104
  345. $System_Drawing_Size.Height = 24
  346. $chk_printreport.Size = $System_Drawing_Size
  347. $chk_printreport.TabIndex = 2
  348. $chk_printreport.Text = "Print Report"
  349. $System_Drawing_Point = New-Object System.Drawing.Point
  350. $System_Drawing_Point.X = 304
  351. $System_Drawing_Point.Y = 323
  352. $chk_printreport.Location = $System_Drawing_Point
  353. $chk_printreport.DataBindings.DefaultDataSourceUpdateMode = 0
  354. $chk_printreport.Name = "chk_printreport"
  355. $chk_printreport.checked = $True
  356.  
  357.  
  358. $form1.Controls.Add($chk_printreport)
  359.  
  360. $lbl_bottomheader.TabIndex = 1
  361. $lbl_bottomheader.ImageAlign = 512
  362. $lbl_bottomheader.TextAlign = 32
  363. $System_Drawing_Size = New-Object System.Drawing.Size
  364. $System_Drawing_Size.Width = 662
  365. $System_Drawing_Size.Height = 59
  366. $lbl_bottomheader.Size = $System_Drawing_Size
  367. $lbl_bottomheader.Text = "FOR OFFICIAL USE ONLY"
  368. $lbl_bottomheader.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",20.25,1,3,0)
  369. $lbl_bottomheader.ForeColor = [System.Drawing.Color]::FromKnownColor("Green")
  370.  
  371. $System_Drawing_Point = New-Object System.Drawing.Point
  372. $System_Drawing_Point.X = 11
  373. $System_Drawing_Point.Y = 425
  374. $lbl_bottomheader.Location = $System_Drawing_Point
  375. $lbl_bottomheader.DataBindings.DefaultDataSourceUpdateMode = 0
  376. $lbl_bottomheader.Name = "lbl_bottomheader"
  377. $lbl_bottomheader.add_Click($handler_label2_Click)
  378.  
  379. $form1.Controls.Add($lbl_bottomheader)
  380.  
  381. $lbl_topheader.TabIndex = 0
  382. $lbl_topheader.ImageAlign = 512
  383. $lbl_topheader.TextAlign = 32
  384. $System_Drawing_Size = New-Object System.Drawing.Size
  385. $System_Drawing_Size.Width = 662
  386. $System_Drawing_Size.Height = 59
  387. $lbl_topheader.Size = $System_Drawing_Size
  388. $lbl_topheader.Text = "FOR OFFICIAL USE ONLY"
  389. $lbl_topheader.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",20.25,1,3,0)
  390. $lbl_topheader.ForeColor = [System.Drawing.Color]::FromKnownColor("Green")
  391.  
  392. $System_Drawing_Point = New-Object System.Drawing.Point
  393. $System_Drawing_Point.X = 11
  394. $System_Drawing_Point.Y = 6
  395. $lbl_topheader.Location = $System_Drawing_Point
  396. $lbl_topheader.DataBindings.DefaultDataSourceUpdateMode = 0
  397. $lbl_topheader.Name = "lbl_topheader"
  398. $lbl_topheader.add_Click($handler_label1_Click)
  399.  
  400. $form1.Controls.Add($lbl_topheader)
  401.  
  402. #endregion Generated Form Code
  403.  
  404. #Save the initial state of the form
  405. $InitialFormWindowState = $form1.WindowState
  406. #Init the OnLoad event to correct the initial state of the form
  407. $form1.add_Load($OnLoadForm_StateCorrection)
  408. #Show the Form
  409. $form1.ShowDialog()| Out-Null
  410. } #End Function
  411.  
  412. #Call the Function
  413. GenerateForm

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me