Batch – Script to Query BitLocker Info – Multiple Machines

email me

I created this script to query a list of computers. For me, I just needed the raw BitLocker data from the client machines dumped to a text file.

cls

@Echo off
Title BitLocker Report
color 0a
Setlocal EnableDelayedExpansion

REM INTERNAL VARIABLES
REM —————————————————————————-

REM ENTER NAME OF COMPUTER TEXT FILE
Set PCList=C:\scripts\_AD_Scripts\_ENGINE\computers.txt

REM CREATES DATE AND TIME TIMESTAMP
rem sets a static timestamp
for /F “tokens=2-4 delims=/- ” %%p in (‘date/T’) do set mdate=%%r%%p%%q
for /F “tokens=1-2 delims=:- ” %%p in (‘time/T’) do set mtime=%%p%%q
Set ReportN=%mdate%_%mtime%_%report%.txt
REM PROGRAM ROUTINE
:CYCLE
for /f “tokens=* delims=%%a in (%PCList%) do (

REM sets dynamic timestamp 
FOR /F “TOKENS=*” %%B IN (‘DATE/T’) DO SET NowD=%%B
FOR /F “TOKENS=*” %%A IN (‘TIME/T’) DO SET NowT=%%A

cls
echo Contacting %%a workstation name…
ping %%a | find “Reply” > nul
if errorlevel 1 (echo !NowD! !NowT!, %%a, OFFLINE >> “%ReportN%”
) else ( 
echo !NowD! !NowT!, %%a, ONLINE >> “%ReportN%cls
echo Found %%arem ———————————-
echo Reporting BitLocker Data %%a
ping -n 2 127.0.0.1>nul
echo.
manage-bde -cn %%a -protectors -get c:>>C:\scripts\_AD_Scripts\_ENGINE\RawData.txt
rem ———————————-

echo.
)
)

endlocal
exit /b 0

Script to Query BitLocker Info – Single Machine

email me

I created this script to query Bitlocker info directly from the computer. I was going down a spreadsheet, so I added the loop to make things faster (I’m using this to audit machines). Note, I did add querying for computer name and IP address. If seems like manage-bde was being temperamental, and only sometimes accepting the name.

Screenshot

Code

@echo off
color 0b
Setlocal EnableDelayedExpansion
Title Return Bitlocker Info

:LOOP
cls
rem enter the name of the computer you want to query
Echo Enter Computer Name:
Set /p PC=

cls
Echo Checking for %PC%Echo.
rem check to see if the pc is online
ping %PC% | find “Reply” > nul
if errorlevel 1 (Echo %PC% was not found
ping -n 6 127.0.0.1>nul
) else (Echo Found %PC%
Echo.
Echo.
Echo.
Echo Trying by computer name first…
Echo.
rem return protectors to screen
manage-bde -cn %PC% -protectors -get c:

rem find ip address
for /f “tokens=1,2,3 delims=%%a in (‘ping %PC%’) do (
set IP1=%%a
set IP2=%%b
set IP3=%%c
echo !IP3! | find “[” && set IP=!IP3!
set PCIP=!IP:~1,-1!
)
Echo.
Echo.
Echo.
Echo Trying by IP address next…
Echo.
rem return protectors with ip address
manage-bde -cn !PCIP! -protectors -get c:
pause
)

goto :LOOP

 

Update 11/14/2016

I went ahead and added the Active Directory import. So, not only will the script return the Bitlocker info to screen, it will also attempt to import the remote computer’s Bitlocker info into AD. The additional parts are in bold.

@echo off
color 0b
Setlocal EnableDelayedExpansion
Title Return Bitlocker Info

:LOOP
cls
rem enter the name of the computer you want to query
Echo Enter Computer Name:
Set /p PC=
cls
Echo Checking for %PC%…
Echo.
rem check to see if the pc is online
ping %PC% | find “Reply” > nul
if errorlevel 1 (Echo %PC% was not found
ping -n 6 127.0.0.1>nul
) else (Echo Found %PC%
Echo.
Echo.
Echo.
Echo Trying by computer name first…
Echo.
rem return protectors to screen
manage-bde -cn %PC% -protectors -get c:

rem find ip address
for /f “tokens=1,2,3 delims= ” %%a in (‘ping %PC%’) do (
set IP1=%%a
set IP2=%%b
set IP3=%%c
echo !IP3! | find “[” && set IP=!IP3!
set PCIP=!IP:~1,-1!
)
Echo.
Echo.
Echo.
Echo Trying by IP address next…
Echo.
rem return protectors with ip address
manage-bde -cn !PCIP! -protectors -get c:
echo.
echo.
Echo Attempting Active Directory Import
for /f “skip=4 tokens=2 delims=:” %%g in (‘”manage-bde -cn !PCIP! -protectors -get c:”‘) do set MyVar=%%g
ping.exe -n 6 127.0.0.1>nul
REM IMPORT BITLOCKER INFO INTO AD
echo.
echo Returned ID is !MyVar!
echo.
\\%computername%\C$\Windows\system32\manage-bde.exe -cn !PCIP! -protectors -adbackup c: -id!MyVar!
pause
)

goto :LOOP

 

Notes

see this PowerShell script to write to computer description field in AD

C# Text File and Arrays

email me

Using Visual Studio 2015, I selected File–New–Project–Visual C#–Console Application, and began testing text file creation, writing and reading, loading items from the text file into an array, and returning specific elements from the array.

using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\CSharpLabs\computers.txt";

// See if file exists, if not exists, create file
if (!File.Exists(path))

{
// Create a file to write to.
string[] createText = { "computer1", "computer2", "computer3" };
File.WriteAllLines(path, createText);
}

// Append to last line
string appendText = "computer99" + Environment.NewLine;
File.AppendAllText(path, appendText);

// Read each line
string[] readText = File.ReadAllLines(path);
foreach (string s in readText)

{
//output to screen
Console.WriteLine(s);
}

//select a couple of array items to output
Console.WriteLine("Array 1 is: {0}", readText[0]);
Console.WriteLine("Array 2 is: {0}", readText[1]);
Console.ReadLine();
}
}

Tableau Reader Silent Install

email me

Recently, Tableau has made a slight change to how its Reader app is installed.

When packaging, it used to be
tableau_setup.msi /qn

Now it is
tableau_setup.msi /qn ACCEPTEULA=”1″

VBScript will look something like this
InstallTableau = “msiexec.exe /i tableau_setup.msi /qn ACCEPTEULA=””1″” “
wshShell.Run InstallTableau,0,true

 

I found that bit of information in the MSI using Orca


Notes

Remove older versions
msiexec.exe /X{601C7D83-2B27-424A-82A4-A7F2768508F4} /QN
msiexec.exe /X{CAFF89F1-3C19-4F86-84A9-9410BC014EB4} /QN
msiexec.exe /X{3D054388-8F96-4BDD-BC9D-9889FC7C2892} /QN
msiexec.exe /X{7a03ede8-74de-4c02-94bf-333c5b49c474} /QN

Testing Some Basics in C# – Part 2 of 2

email me

Part 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Decisions
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Behind the Door!";
string Success = "1";
string message = "";
string UserValue = "";
Console.WriteLine("");

do
{
Console.WriteLine("Eddie's TV Show");
Console.WriteLine("Choose a door: 1, 2, 3: ");
UserValue = Console.ReadLine();

if (UserValue == "1")
{
message = "You have won a vacation to Hawaii!";
Success = "0";
}
else if (UserValue == "2")
{
message = "You have won a jetski!";
Success = "0";
}
else if (UserValue == "3")
{
message = "You have won a cruise!";
Success = "0";
}
else
{
Console.WriteLine("");
Console.WriteLine("I did not recognize your answer!");
System.Threading.Thread.Sleep(3000);
Console.Clear();

}
Console.WriteLine(message);

} while (Success == "1");

Console.WriteLine("");
Console.WriteLine("Press Enter to exit.");
Console.ReadLine();

}
}
}

Install Windows Updates Remotely

email me

If you have ever had to install Windows updates, as in patching servers, you know you have to log into servers and allow updates to install, suppressing reboots along the way. To remotely install updates, try some of these methods.

PowerShell

Invoke-Command -ComputerName ServerName {wusa.exe C:\Updates\Windows6.1-KB894199-x64.msu /quiet /norestart}

 
 

VBScript

Set objShell = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

set filetxt = objFSO.OpenTextFile("C:\Servers.txt",1)
strPSExec = "C:\PSExec.exe"
rbcopy = "c:\Windows\System32\Robocopy.exe"

strPSExec = objFSO.GetFile(strPSExec).ShortPath
rbcopy = objFSO.GetFile(rbcopy).ShortPath

Do Until filetxt.AtEndOfStream
strServerName = filetxt.Readline
strServerName = trim(strServerName)

'Copy updates
strCmd = "%comspec% /c " & rbcopy & " C:\Updates" & " \\" & strServerName & "\c$\Updates"
WScript.echo strCmd
objShell.Run strCmd, 1, True

'Run updates
strCmd = "cmd /C " & strPSExec & " \\" & strServerName & " ""C:\Updates\"" /quiet"
WScript.echo strcmd
objShell.Run strCmd, 1, True

Loop

 
 

Command in Script

psexec \\ServerName -c -s -u Domain\Administrator -p P@$$W0rd \\ShareName\PathToWUInstall\WUInstall.exe /install

 
 

Notes

If you have issues with PSExec, try PAExec.

wusa.exe “\\ServerName\winupdates\windows6.1-kb894199-x64.msu”

https://blogs.technet.microsoft.com/heyscriptingguy/2011/08/13/use-powershell-to-audit-and-install-windows-patches/

https://gallery.technet.microsoft.com/scriptcenter/Force-Install-Updates-on-ef821f9a

Some PowerShell Basics

email me

You ever needed just to write a quick script, but you don’t have time to learn the ins and outs of scripting? Well, here are some PowerShell basics to get you up and running. By using the code here, you can quickly create some simple scripts. Just open notepad, paste the segments you need, update the paths and/or file names, and save as script.ps1.

Let me know if you’d like to see something else.

#========================================================================
# Created on: 10/13/2016 11:48 AM
# Created by: Eddie Jackson
# Organization: Commlink Industries
# Filename: script.ps1
#========================================================================

# Create Registry Key
$Date = Date
New-ItemProperty -Path HKCU:\Contoso.com\App1 -Name Timestamp -Value "$Date" -Force

# Read Registry Key
$RegPath = "HKCU:\Contoso.com\App1"
$Reg = Get-ItemProperty $RegPath -Name Timestamp
$(New-Object -comobject "WScript.Shell").Popup($Reg,0,"Reg Key",0)

# Delete Registry Key
$RegPath = "HKCU:\Contoso.com\App1"
$Reg = Remove-ItemProperty $RegPath -Name Timestamp
$(New-Object -comobject "WScript.Shell").Popup("The Reg Key was deleted!",0,"Reg Key",0)

# Copy File
$SourceFile = "Test.txt"
$NewFile = "Test2.txt"
if ([System.IO.File]::Exists($SourceFile)) {
Copy-Item $SourceFile $NewFile
"Source File ($SourceFile) copied to ($newFile)"
}

# Delete File
$FileName = "test3.txt"
if ([System.IO.File]::Exists($FileName)) {
Remove-Item $FileName
}

# Check Folder, Create or Delete Folder
$FolderPath = "c:\_PS\sample1\test\"
if ([system.io.Directory]::Exists($FolderPath)) {
$(New-Object -comobject "WScript.Shell").Popup("That folder does exists!",0,"Folder Path",0)
Remove-Item -Path $FolderPath
$(New-Object -comobject "WScript.Shell").Popup("The folder was deleted!",0,"Folder Path",0)
}

Else {
$(New-Object -comobject "WScript.Shell").Popup("That folder does not exist",0,"Folder Path",0)
New-Item -path $FolderPath -itemType "directory"
$(New-Object -comobject "WScript.Shell").Popup("The folder was created!",0,"Folder Path",0)
}

# Create text file
$CreateFile | Out-File 'test3.txt'

# Writing to a text file
$AddTextToFile = 'This is some sample text'
$AddTextToFile | Out-File 'test3.txt'

# Appending to a text file
$AddTextToFile = 'This is another line'
$AddTextToFile | Out-File 'test3.txt' -Append

# Reading from a text file
$TheTextFile = Get-Content test3.txt
$(New-Object -comobject "WScript.Shell").Popup($TheTextFile,0,"Contents of file",0)

# Create Event Log
New-Eventlog -Logname Application -Source 'AppName1' -ErrorAction SilentlyContinue
Write-Eventlog -Logname Application -Message 'Your Message Goes Here' -Source 'AppName1' -id 777 -entrytype Information -Category 0

# Launch Process
Start-Process notepad.exe
#-Wait -WindowStyle Maximized

Tableau Automation

email me

Command Line Tool Options and Script Automation

Using scripting languages or manual operations via the Command Prompt, you can activate online, refresh, and deactivate your license keys. For Tableau Desktop, the application itself provides the command line interface. For Tableau Server, the executable is named tabinstallck.exe and can be used prior to configuring Tableau Server.

When performing quiet installations of Tableau Desktop or Tableau Server, use the online activation parameter to avoid having Tableau prompt the user to manually enter the license key for each installation. In addition, you can use the “return” parameter to retrieve a license and deactivate it without having to manually remove it from an individual machine.

Note: To successfully use the licensing parameters, you must run scripts or perform manual operations as an administrator. For me, I used desktop management software to deploy a compiled script, which ran in the system account.

Task Commands
Online activation Desktop (Windows) start /wait tableau.exe -activate <license-key>
Desktop (Mac) ./Applications/Tableau.app/Contents/MacOS/Tableau -activate <license key>
Server start/wait tabinstallck.exe-activate <license-key>
Refreshing license key Desktop (Windows) start /wait tableau.exe -refresh <license-key>
Desktop (Mac) ./Applications/Tableau.app/Contents/MacOS/Tableau -refresh <license key>
Server start /wait tabinstallck.exe -refresh <license-key>
Deactivating license key Desktop (Windows) start /wait tableau.exe -return <license-key>
Desktop (Mac) ./Applications/Tableau.app/Contents/MacOS/Tableau -return <license key>
Server start /wait tabinstallck.exe -return <license-key>

 

For example, a script that could be used to activate Tableau Desktop on a Windows computer would look like the following:

Batch Script

@echo on
Title Deactivate Tableau
cls
Echo Deactivating...
tableau.exe -return FD1Q-6QME-25V9-575F-27FPC
ping -n 4 127.0.0.1>nul
cls
echo Deactivation Complete!
ping -n 4 127.0.0.1>nul
exit /b 0

Dealing with the registration Pop up

AutoIT Script

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Res_requestedExecutionLevel=asInvoker
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#region ---Au3Recorder generated code Start (v3.3.7.0) ---

#region --- Internal functions Au3Recorder Start ---

Func _Au3RecordSetup()
Opt('WinWaitDelay',100)
Opt('WinDetectHiddenText',1)
Opt('MouseCoordMode',0)
EndFunc

Func _WinWaitActivate($title,$text,$timeout=0)
WinWait($title,$text,$timeout)
If Not WinActive($title,$text) Then WinActivate($title,$text)
WinWaitActive($title,$text,$timeout)
EndFunc

_AU3RecordSetup()

RegWrite("HKCU\Software\Tableau\Registration\Data", "company", "REG_SZ", "ABC")
RegWrite("HKCU\Software\Tableau\Registration\Data", "country", "REG_SZ", "FR")
RegWrite("HKCU\Software\Tableau\Registration\Data", "email", "REG_SZ", "ABC@xya.com")
RegWrite("HKCU\Software\Tableau\Registration\Data", "first_name", "REG_SZ", "ABD")
RegWrite("HKCU\Software\Tableau\Registration\Data", "last_name", "REG_SZ", "XYZ")

#endregion --- Internal functions Au3Recorder End ---

Local $Ostype = RegRead("HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\", "PROCESSOR_ARCHITECTURE")

If $Ostype = "X86" Then
Run('C:\Program Files\Tableau\Tableau Reader 9.3\bin\tabreader.exe')
Else
Run('C:\Program Files (x86)\Tableau\Tableau Reader 9.3\bin\tabreader.exe')
EndIf

_WinWaitActivate("[Class:Qt5QWindowIcon]","",1)
Send("{ENTER}{ENTER}{ENTER}")
Local $PID = ProcessExists("tabreader.exe")
If $PID Then ProcessClose($PID)

 

Yet, another script

#include <MsgBoxConstants.au3>
BlockInput(1)

Run("C:\Program Files\Tableau\Tableau Reader 10.0\bin\tabreader.exe")
Global $i = 0

Sleep(6000)
;Main Timing
WinWait("Activate Tableau Reader", "", 30)

Sleep(1000)
DO
If WinExists("Activate Tableau Reader") Then
WinActivate("Activate Tableau Reader")
Send("ABC")
;Sleep(50)
WinActivate("Activate Tableau Reader")
Send("{TAB}")

WinActivate("Activate Tableau Reader")
Send("Inc")
;Sleep(50)
WinActivate("Activate Tableau Reader")
Send("{TAB}")

WinActivate("Activate Tableau Reader")
Send("Username")
;Sleep(50)
WinActivate("Activate Tableau Reader")
Send("{TAB}")

WinActivate("Activate Tableau Reader")
Send("You@Computer.com")
;Sleep(50)
WinActivate("Activate Tableau Reader")
Send("{TAB}")

WinActivate("Activate Tableau Reader")
Send("12345")
;Sleep(50)
WinActivate("Activate Tableau Reader")
Send("{TAB}")

WinActivate("Activate Tableau Reader")
Send("U")
;Sleep(50)
WinActivate("Activate Tableau Reader")
Send("{TAB}")

WinActivate("Activate Tableau Reader")
Send("F")
;Sleep(50)
WinActivate("Activate Tableau Reader")
Send("{TAB}")
Send("{ENTER}")
ExitLoop
$i = 20
EndIf
$i = $i + 1
;Sleep(1000)
UNTIL $i &gt; 14

BlockInput(0)
Run("taskkill /f /im tabreader.exe", "",@SW_HIDE)
Sleep(1000)

MsgBox($MB_OK, "Tableau 10.0", " Tableau has been activated.")

;@SW_HIDE = Hidden window (or Default keyword)
;@SW_MINIMIZE = Minimized window
;@SW_MAXIMIZE = Maximized window

 

VBScript Method

on error resume next

Set objShell = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

Const HKEY_LOCAL_MACHINE = &H80000002
Const OverwriteExisting = TRUE
'SETS CURRENT DIRECTORY TO VARIABLE
strCurrentDirectory = objShell.CurrentDirectory
strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objRegistry=GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\ProfileList"
objRegistry.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubkeys
For Each objSubkey In arrSubkeys
on error resume next
strValueName = "ProfileImagePath"
strSubPath = strKeyPath & "\" & objSubkey
objRegistry.GetExpandedStringValue HKEY_LOCAL_MACHINE,strSubPath,strValueName,strValue
Const POPUP_TITLE = "User To SID Conversion"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objAccount = objWMIService.Get("Win32_SID.SID='" & objSubkey & "'")
strUser = objAccount.AccountName
'strDomain = objAccount.ReferencedDomainName'returns referenced domain

'DISPLAY PROFILE NAME & SID
objSubkey = trim(objSubkey)'trims whitespace
strUser = trim(strUser)'trims whitespace
'msgbox "objSubkey: " & objSubkey'returns SID
'msgbox strUser'returns username

'LOGIC TO DETERMINE IF REGISTRY ACCOUNT IS TO BE LOADED
if strUser = "SYSTEM" then strUser=""
if strUser = "LOCAL SERVICE" then strUser=""
if strUser = "NETWORK SERVICE" then strUser=""
if strUser = "ADMINISTRATOR" then strUser=""

if strUser <> "" then
on error resume next
Wscript.Sleep 1000

'ADD REG KEYS
objShell.Run "%comspec% /c reg.exe add "&chr(34)&"HKEY_USERS\" & objSubkey & "\Software\Tableau\Registration\Data"&chr(34)&" /t REG_SZ /v ""company"" /d ""ABC Inc"" /f",0,true
objShell.Run "%comspec% /c reg.exe add "&chr(34)&"HKEY_USERS\" & objSubkey & "\Software\Tableau\Registration\Data"&chr(34)&" /t REG_SZ /v ""country"" /d ""US"" /f",0,true
objShell.Run "%comspec% /c reg.exe add "&chr(34)&"HKEY_USERS\" & objSubkey & "\Software\Tableau\Registration\Data"&chr(34)&" /t REG_SZ /v ""email"" /d ""You@email.com"" /f",0,true
objShell.Run "%comspec% /c reg.exe add "&chr(34)&"HKEY_USERS\" & objSubkey & "\Software\Tableau\Registration\Data"&chr(34)&" /t REG_SZ /v ""first_name"" /d ""User"" /f",0,true
objShell.Run "%comspec% /c reg.exe add "&chr(34)&"HKEY_USERS\" & objSubkey & "\Software\Tableau\Registration\Data"&chr(34)&" /t REG_SZ /v ""last_name"" /d ""Inc"" /f",0,true
objShell.Run "%comspec% /c reg.exe add "&chr(34)&"HKEY_USERS\" & objSubkey & "\Software\Tableau\Registration\Data"&chr(34)&" /t REG_SZ /v ""state"" /d ""TX"" /f",0,true

objShell.Run "%comspec% /c reg.exe add "&chr(34)&"HKEY_USERS\" & objSubkey & "\Software\Tableau\Tableau Reader 8.1"&chr(34)&" /t REG_SZ /v ""DefaultsInstalled"" /d ""8100.14.0510.1702"" /f",0,true

objShell.Run "%comspec% /c reg.exe add "&chr(34)&"HKEY_USERS\" & objSubkey & "\Software\Tableau\Tableau Reader 8.1\LicenseCache"&chr(34)&" /t REG_SZ /v ""Desktop"" /d ""ew752794|<license-cache><map key='feature' value='' /><map key='signature' value='' /><map key='maintenance-date' value='12/31/2028 12:00:00 AM' /><map key='expiration-date' value='12/31/2028 12:00:00 AM' /><map key='vendor-string' value='CAP=NOLICUI,NOSERVER,REG:SHORTLOC,WARN:0;DC_CAP=;DC_STD=default;EDITION=Standard;MAP_CAP=;MAP_STD=default;OEMNAME=;OFFLINE=true;TRIALVER=' /></license-cache>"" /f",0,true

end if

Next

PowerShell – Form – Input, Enter, Escape, OK Button

email me

This is the third example of a PowerShell form. In this version, I have added event handling for the ENTER and ESCAPE keys, created a single OK button (rather than Yes No), and have tied the ENTER key event to a Perform Click; it will access the button action $handler_OK_Button_Click. Something else you will notice, the previous example would close immediately once you selected Yes. This form is persistent.

What the form looks like

 

The Code

# Call Function 
CreateForm

function CreateForm { 

#Import Assemblies 
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$Form1 = New-Object System.Windows.Forms.Form 
$OKButton = New-Object System.Windows.Forms.Button 
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState 
$Label1 = New-Object System.Windows.Forms.Label
$textBox1 = New-Object System.Windows.Forms.TextBox
$Field1 = ""

# Check for ENTER and ESC presses
$Form1.KeyPreview = $True
$Form1.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {
	# if enter, perform click
	$OKButton.PerformClick()
	}
})
$Form1.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
   	{
	# if escape, exit
	$Form1.Close()
	}
})

# The action on the button
$handler_OK_Button_Click= 
{ 
	$Field1 = $textBox1.Text
	$Field1
	
	# Returns a message of no data
	if ($Field1 -eq "") {[System.Windows.Forms.MessageBox]::Show("You didn't enter anything!", "Data")}
	
	# Returns what they types. You could add your code here
	else {[System.Windows.Forms.MessageBox]::Show($Field1, "Data")}	 
}

$OnLoadForm_StateCorrection= 
{
$Form1.WindowState = $InitialFormWindowState 
}


# Form Code 
$Form1.Name = "Data_Form"
$Form1.Text = "Data Form" 
$Form1.MaximizeBox = $false #lock form
$Form1.FormBorderStyle = 'Fixed3D'
# None,FixedDialog,FixedSingle,FixedToolWindow,Sizable,SizableToolWindow

# Icon
$Form1.Icon = [Drawing.Icon]::ExtractAssociatedIcon((Get-Command powershell).Path)
# $NotifyIcon.Icon = [Drawing.Icon]::ExtractAssociatedIcon((Get-Command powershell).Path)

$Form1.DataBindings.DefaultDataSourceUpdateMode = 0 
$Form1.StartPosition = "CenterScreen"# moves form to center of screen
$System_Drawing_Size = New-Object System.Drawing.Size 
$System_Drawing_Size.Width = 300 # sets X
$System_Drawing_Size.Height = 150 # sets Y
$Form1.ClientSize = $System_Drawing_Size

$OKButton.Name = "OK_Button" 
$System_Drawing_Size = New-Object System.Drawing.Size 
$System_Drawing_Size.Width = 45
$System_Drawing_Size.Height = 23

$OKButton.Size = $System_Drawing_Size 
$OKButton.UseVisualStyleBackColor = $True
$OKButton.Text = "OK"
$System_Drawing_Point = New-Object System.Drawing.Point 
$System_Drawing_Point.X = 30 
$System_Drawing_Point.Y = 113

$OKButton.Location = $System_Drawing_Point 
$OKButton.DataBindings.DefaultDataSourceUpdateMode = 0 
$OKButton.add_Click($handler_OK_Button_Click)
$Form1.Controls.Add($OKButton)

$InitialFormWindowState = $Form1.WindowState 
$Form1.add_Load($OnLoadForm_StateCorrection) 

$Label1.Location = New-Object System.Drawing.Point(10,20)
$Label1.Size = New-Object System.Drawing.Size(280,20)
$Label1.Text = "Enter data here:"
$Form1.Controls.Add($Label1)
 
$textBox1.TabIndex = 0 # Places cursor in field
$textBox1.Location = New-Object System.Drawing.Point(10,40)
$textBox1.Size = New-Object System.Drawing.Size(260,20)
$Form1.Controls.Add($textBox1)
$Form1.Topmost = $True # Moves form to top and stays on top
$Form1.Add_Shown({$textBox1.Select()})

# Show Form 
$Form1.ShowDialog()
}

 

PowerShell Form Input Field; GUI

email me

From our previous form example, we learned that GUI components can be created using PowerShell. Now, we add an input field, perform some logic on the input, and center our form on the screen.

What the form looks like

The pop up with data

The pop up without data

 

The Code

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$Form1 = New-Object System.Windows.Forms.Form
$Form1.Text = "Data Form"
$Form1.Size = New-Object System.Drawing.Size(300,200)
$Form1.StartPosition = "CenterScreen"
# Icon
$Form1.Icon = [Drawing.Icon]::ExtractAssociatedIcon((Get-Command powershell).Path)

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$Form1.AcceptButton = $OKButton
$Form1.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$Form1.CancelButton = $CancelButton
$Form1.Controls.Add($CancelButton)

$Label1 = New-Object System.Windows.Forms.Label
$Label1.Location = New-Object System.Drawing.Point(10,20)
$Label1.Size = New-Object System.Drawing.Size(280,20)
$Label1.Text = "Enter data here:"
$Form1.Controls.Add($Label1)

$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,40)
$textBox.Size = New-Object System.Drawing.Size(260,20)
$Form1.Controls.Add($textBox)

$Form1.Topmost = $True

$Form1.Add_Shown({$textBox.Select()})
$result = $Form1.ShowDialog()

if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$x = $textBox.Text
$x

if ($x -eq "") {[System.Windows.Forms.MessageBox]::Show("You didn't enter anything!", "Test Title")}
else {[System.Windows.Forms.MessageBox]::Show($x, "Test Title")}}