Skip to content

Instantly share code, notes, and snippets.

@veeblefetzer2
Created August 10, 2021 14:21
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veeblefetzer2/9edfafef6009056dfc0d8288942e7770 to your computer and use it in GitHub Desktop.
Save veeblefetzer2/9edfafef6009056dfc0d8288942e7770 to your computer and use it in GitHub Desktop.
PowerShell Programming Guide/Reference
__________________________________________
| |
| Programming with PowerShell |
|________________________________________|
1. Introduction
2. Running PowerShell
3. PowerShell Variables
4. PowerShell Data Types
5. PowerShell Basic Operators
6. Common/Generic PowerShell Commands
7. Common PowerShell Cmdlets
8. Special Variables/Characters
9. Arrays and Hash Tables
10. PowerShell Operators
11. PowerShell .NET Methods
12. I/O and File-related Commands and Cmdlets
13. Functions, Arguments, and Global/Local Variables
14. Miscellaneous Information
Appendix A - Text of the Get_Options function
Appendix B - Text of the Cvt_Str2Nbr function
Appendix C - Text of the Get_GUI_DropDown function
Appendix D - Text of the Get_GUI_Date function
Appendix E - Text of the Get_GUI_CheckBox function
_____________________________________________________________________________________________________
1. Introduction
The purpose of this document is to teach people how to program in Window’s PowerShell. It
describes the PowerShell language and shows how to use the language to write scripts. It does
NOT show how to use PowerShell to do system administration since there are plenty of other
resources (books, the internet, etc) that do that. This document shows the various structures
of the language and how they can be used as a general programming language.
PowerShell Quote of the Day:
"That's because PowerShell, nice as it is, is also pointlessly and randomly obscurely different
and bizarre just for the sake of it. It's like the people who designed it had been locked away
by Microsoft for forty years in a commune somewhere, isolated from the whole history of the
computing universe, and then were told to create PowerShell untainted from anything that ever
existed before." - Alban on weblogs.asp.net
Actually, it has elements of Unix's Korn Shell, C, Perl, & Python in it.
_____________________________________________________________________________________________________
2. Running PowerShell
To start running PowerShell, you should first open a command window. Set the properties of the
command window, such as the quick-edit mode and the font name and size. Fonts that work well
with Powershell are:
Max Max
Name of Font Size Width Height
--------------- ---- ----- ------
Raster 8x12 160 80
Consolas 16 160 60
18 160 53
20 142 48
Lucida Console 16 128 60 (Most readable font)
When using a command window, you can then run PowerShell in one of two ways. Either
interactively by typing "PowerShell" or by running a PowerShell script. If the script is named
"test.ps1", then type:
Prompt> PowerShell.exe -ExecutionPolicy ByPass test.ps1
You can maximize the height of the window by entering the following the first time you run a
PowerShell script:
Prompt> PowerShell.exe -WindowStyle Maximized -ExecutionPolicy ByPass test.ps1
By default the execution policy is set to "Restricted". Instead of bypassing the execution
policy each time a script is run, it can be permanently set such that all local scripts can be
run as well as downloaded scripts signed by a trusted publisher. Do this by running the
following in a PowerShell window:
PS> Set-ExecutionPolicy RemoteSigned
_____________________________________________________________________________________________________
3. PowerShell Variables
The names of all PowerShell variables start with a dollar sign ($), regardless if they are
single-value variables or arrays. PowerShell detects that it has reached the end of a name when it
encounters a non-alphanumeric character (something other than a letter, a digit, or an underscore).
Braces ({}) can be used after the dollar sign to enclose the variable name. Semicolons indicate
the end of a line, but are optional and are only needed when you double up multiple commands on a
line. Typical value assignments are:
PS> $var1 = "abc"
PS> $var2 = "${var1}def" ; $var3 = $var2 + "ghi"
You can display a value or a variable by just typing it at the PowerShell prompt:
PS> $var3
abcdefghi
PS> "xyz"
xyz
This works well for interactive mode, but in scripts it forces you to always give a value to a
variable when it is being declared with a data type.
_____________________________________________________________________________________________________
4. PowerShell Data Types
It is safer and less error-prone to declare the types for each of the variables. Here are the
main types supported by PowerShell:
Type Description of data type
------ -------------------------------------
[int] 32-bit signed integer (same as [int32])
[long] 64-bit signed integer (same as [int64])
[string] A string of Unicode characters
[char] A Unicode 16-bit character
[byte] An 8-bit unsigned character
[bool] Boolean True/False value
[decimal] A 128-bit decimal value
[single] Single-precision 32-bit floating point number (same as [float])
[double] Double-precision 64-bit floating point number
[datetime] A date/time value that will be formatted when displayed
[hashtable] A Hash table (sometimes called an associative array).
Most of the above types can also be arrays, for example:
[int[]] An array of 32-bit signed integers
[string[]] An array of 1 or more strings of Unicode characters
With PowerShell the variables can either be strongly (explicitly) typed by having their data
types declared, or loosely (implicitly) typed by not having their data types declared. If you
don’t declare the type, PowerShell will handle the variable as a number if it is all digits or
as a string if it is in quotes. Quotes can either be double quotes or single quotes. The only
difference is that variables inside single quotes are not converted to values.
If you declare a variable without specifying a value, PowerShell will display the default value
for that type (since the value of variables are always displayed to the screen if no value is
present). Because of this, you have to always declare a value (which can also be a null value,
which is signified by the special variable $Null).
Indexes and subscripts are all based on zero (like PERL) instead of starting at 1 like some other
(more user-friendly) languages.
_____________________________________________________________________________________________________
5. PowerShell Basic Operators
Operator Description
--------- -------------------------------------------------------------
= value assignment
+ or += addition (number), concatenation (string), or add to an array
- or -= subtraction
* or *= multiplication of numbers or strings
/ or /= division
% or %= modulus (remainder, sometimes called the modulo operator)
++ increment (by 1)
-- decrement (by 1)
-and logical AND
-or logical OR
! logical NOT
-is check to see if a variable is of a data type
-isnot check to see if a variable is not of a data type
-as as a data type (no error if conversion fails)
-eq is equal (case-insensitive)
-ceq is case-sensitive equal
The following shows loosely typed variables being compared for untyped variables:
PS> $nbr = 123
PS> $str = "123"
PS> if ($nbr -is [int] -and $str -isnot [int]) { "nbr IS INT, str IS NOT" }
The output shows whether or not the variables contain integers:
nbr IS INT, str IS NOT
If you add the two variables, using the integer first:
PS> $k = $nbr + $str
PS> if ($k -is [int]) { "k=$k, k IS AN INTEGER" }
The output shows that the string is converted to an integer:
k=246, k IS AN INTEGER
If you add the two variables, using the string first:
PS> $m = $str + $nbr
PS> if ($m -isnot [int]) { "m=$m, m IS NOT AN INTEGER" }
The output shows that the integer was converted to a string:
m=123123, m IS NOT AN INTEGER
Since the results vary according to the order of the variables, you can see why it is
safer to declare the data types of the variables.
To force a conversion, use the '-as' operator:
PS> $n = $str as [int]
PS> if ($n -is [int]) { "n IS AN INT" }
The result is:
n IS AN INT
When you multiply a string by a number, PowerShell will replicate it that number of times:
PS> "ABCD_" * 3
The result is:
ABCD_ABCD_ABCD
The modulus operator will display the remainder:
PS> $n = 11 % 6
The result is: 5
If a variable contains the value, then the modulus can be calculated this way:
PS> $m = 23
PS> $m %= 6
The result is: 5
_____________________________________________________________________________________________________
6. Common/Generic PowerShell Commands
#-----------------#
exit [status] # EXIT command #
#-----------------#
if (condition) #-----------------#
{ # IF command #
commands #-----------------#
}
elseif (other condition)
{
other commands
}
else
{
alternate commands
}
#-----------------#
do # DO command #
{ #-----------------#
commands
[break|continue] # break or continue
}
while (condition)
#-----------------#
for (init; condition; repeat) # FOR command #
{ #-----------------#
commands
[break|continue] # break out of the loop or continue
}
#-----------------#
foreach (item in collection) # FOREACH command #
{ #-----------------#
commands
[break|continue] # break or continue to the top of the loop
}
#-----------------#
# SWITCH command #
#-----------------#
switch [-regex | -wildcard -exact] [-casesensitive] ($item) | -file filename
{
value_1 {commands_1 [; break | continue] }
value_2 {commands_2 [; break | continue] }
. .
. .
. .
[default {default_commands } ]
}
Example: See the section on ARRAYS.
#-----------------#
while (condition) # WHILE command #
{ #-----------------#
commands
[break|continue] # continue got to the top of the loop
}
There are also single-character commands: '&', '.', and '|'
. (period/dot) - Use to run a script in-process (anything created will remain).
& (ampersand) - Use to run a script as a sub-process (and wait until complete).
| (pipe/vertical bar) - Use to pipe the output into another command.
` (back-tick/back-quote) - Use to continue commands onto another line or to escape special
characters (such as quotes, etc).
_____________________________________________________________________________________________________
7. Common PowerShell Cmdlets
PowerShell users typically make use of 'cmdlets', which are instances of .NET framework classes.
Some of the most useful ones are listed here, except for any related to file I/O, which are in
their own section.
-------- --------------------------------------------------------
Get-Date Get current date and time
-------- --------------------------------------------------------
Syntax: Get-Date [-format string]
where:
-format string = Display the date and time in the .NET format as indicated by 'string'
representing a format specifier:
Format Description | Format Description
------ ---------------------- | ------ ------------------------
s Seconds from 1-60 | m Minute from 0-59
ss Seconds from 01-60 | mm Minute from 00-59
h Hour from 1-12 | t A or P (for AM or PM)
H Hour from 1-24 | tt AM or PM
hh Hour from 01-12 | yy Year as 2-digit
HH Hour from 01-24 | yyyy Year as 4-digit
M Month from 1-12 | dd Day of month 01-31
MM Month from 01-12 | ddd Day of month as
MMM Abbreviated Month Name | abbreviated weekday name
MMMM Month name | dddd Weekday name
z Timezone as one digit |
zz Timezone as 2-digit | zzz Timezone
Date/Time Commands:
Get-Date display date/time
(Get-Date).Second display just the second
(Get-Date).Minute display just the minute
(Get-Date).Hour display just the hour
(Get-Date).Day display just the day
(Get-Date).Month display just the month
(Get-Date).Year display just the year
(Get-Date).ToShortTimeString example: 1:55 PM
(Get-Date).ToShortDateString example: 10/25/2021
(Get-Date).AddSeconds(137) add 137 seconds to current time
(Get-Date).AddMinutes(137) add 137 minutes to current time
(Get-Date).AddHours(137) add 137 hours to current time
(Get-Date).AddDays(137) add 137 days to current date
(Get-Date).AddMonths(137) add 137 months to current date
(Get-Date).AddYears(137) add 137 years to current date
Get-Date -format FORMAT use various formats:
Get-Date example using elapsed time:
$start_time = Get-Date
$Elapsed_time = (Get-Date) - $start_time
Get-Date example using '-format':
Get-Date -format "dd-MMM-yyyy HH:mm"
----------------- --------------------------------------------------------
Invoke-Expression Run a PowerShell expression
----------------- --------------------------------------------------------
Syntax: Invoke-Expression [-command] string
where:
-command string = A literal string (or variable that contains a string) that is a valid
PowerShell expression.
This example will programmatically set the value of one variable to another's value.
PS> $t = ""
PS> $b = "bb"
PS> $s = "`$t = `$b"
PS> Invoke-Expression "$s"
PS> $t
The result displayed is "bb".
-------- --------------------------------------------------------
Out-Host Send output to the screen/console
-------- --------------------------------------------------------
Syntax: Out-Host [-paging] [-input object]
where:
-input object = The object(s) to be written to the console (may be piped). A command,
expression or variable that contains the objects.
-paging = Display one page of output at a time, and wait for user input before
displaying more.
Example:
Get-Content "C:\Temp\outfile.txt" | Out-Host -Paging
--------- --------------------------------------------------------
Read-Host Read a line of input from the host console
--------- --------------------------------------------------------
Syntax: [$var =] Read-Host [-AsSecureString] "Prompt for input"
Where :
-AsSecureString = Data entered will be masked (shown as asterisks)
Note: When Read-Host is used with a prompt and without the "-AsSecureString" option, the
user cannot enter a value that starts with "!". One work-around is for the user to
enter two exclamation marks. Another is to prompt using "Write-Host" and read using
"Read-Host":
Write-Host -NoNewline "Enter value> "
$value = Read-Host
------------- --------------------------------------------------------
Send-SmtpMail Send an email via SMTP
------------- --------------------------------------------------------
Syntax: Send-SMTPmail -to -from -subject -body
[-smtpserver ] [-port ] [-attachment ] [-html]
[-cc ] [-bcc ] [-alert] [-timeout ]
Example:
Send-SmtpMail -SmtpHost name.com -from user1@name.com -to user2@name.com -body "Hello"
---------------- --------------------------------------------------------
Send-MailMessage Send an email message
---------------- --------------------------------------------------------
Syntax: Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string>
[[-Body] <string>] [[-SmtpServer] <string>]
[-Attachments <string[]>] [-Bcc <string[]>]
[-BodyAsHtml] [-Cc <string[]>]
[-Credential <PSCredential>]
[-DeliveryNotificationOption {None|OnSuccess|OnFailure|Delay|Never}]
[-Encoding <Encoding>]
[-Priority {Normal | Low | High}] [-UseSsl]
------------- --------------------------------------------------------
Select-String Find a substring in a string or a file
------------- --------------------------------------------------------
This is equivalent to 'grep', 'find', and 'findstr'.
Syntax: $string = Select-String [-Path [folder\]file.ext]
[-Pattern "string"]
[-CaseSensitive]
[-Context (before,after)]
[-NotMatch]
[-Quiet]
[-SimpleMatch]
[-Encoding]
Where:
-Path = Folder and filename to search for the pattern.
-Pattern = String or regular expression to search for.
-Context = Number of lines to display before and after the match.
-NotMatach = Display only non-matching lines.
-Quiet = Return only TRUE (found a match) or FALSE.
-SimpleMatch = If specified, then PATTERN is NOT a regular expression.
-Encoding = Values inclue 'ASCII', 'Unicode', 'Default', among others.
The default is UTF8.
Examples:
Select-String -Path *.txt -Pattern "Princess" -Casesensitive
$events | Select-String -Pattern "failed" -Context 2,3 -SimpleMatch
----------- --------------------------------------------------------
Sort-Object Sort an object
----------- --------------------------------------------------------
Syntax:
Sort-Object [-CaseSensitive] [-Descending] [-Unique]
----------- --------------------------------------------------------
Start-Sleep Make the process go to sleep
----------- --------------------------------------------------------
Syntax:
Start-Sleep [-milliseconds] time_in_seconds
Example:
Start-Sleep 5 # sleep for 5 seconds
---------- --------------------------------------------------------
Tee-Object Send text to both a logfile and the screen
---------- --------------------------------------------------------
Syntax:
Tee-Object -FilePath filename
Example:
Write-Host "string" | Tee-Object -FilePath $logfile
---------- --------------------------------------------------------
Write-Host Write to the host/screen
---------- --------------------------------------------------------
Syntax: Write-Host [-foregroundcolor color] [-backgroundcolor color] [-NoNewline] "Text"
Color options:
DarkBlue, DarkGreen, DarkRed, DarkCyan, DarkMagenta, DarkYellow, DarkGray,
Blue, Green, Red, Cyan, Magenta, Yellow, Gray,
Black, White
------------- --------------------------------------------------------
Write-Warning Write a warning message
------------- --------------------------------------------------------
Syntax:
Write-Warning message
Example:
Write-Warning "No input was found"
The output will be displayed in yellow letters: WARNING: No input was found
_____________________________________________________________________________________________________
8. Special Variables/Characters
The list below shows Special PowerShell variables:
Variable Name Description
------------- -----------------------------------
$_ The current pipeline object; used in script blocks, filters,
the process clause of functions, where-object, foreach-object,
and the switch command.
$^ Contains the first token of the last line input into the shell.
$$ Contains the last token of last line input into the shell.
$? Contains the status of the last statement (last program run).
$Args Used in creating functions that require parameters.
$Error If an error occurred, the object is saved in here.
$LastExitCode Return status from the last program run.
$foreach Refers to the enumerator in a foreach loop.
$HOME The user's home directory; set to %HOMEDRIVE%\%HOMEPATH%.
$Input Input piped to a function or code block.
$Match A hash table consisting of items found by the "match" operator.
$MyInvocation Information about the current script or command-line.
$Host Information about the currently executing host.
$True Boolean TRUE.
$False Boolean FALSE.
$Null A null object.
$OFS Output Field Separator, used when converting an array to a string.
By default, this is set to an empty string.
The list below show Special PowerShell characters, which use a back-quote (back-tick) to escape
special characters:
Escape Sequence Special Character
--------------- ----------------------------------------------
`n newline (linefeed)
`r carriage-return
`t tab (horizontal)
`v tab (vertical, has no affect on screens)
`f form-feed (no affect on screens)
`a alert (bell/beep)
`b backspace
`" double-quote
`' single-quote
`` back-quote
`0 null (back-quote and zero, not the same as $Null)
`$ dollar sign (not needed if inside single-quotes)
` and newline continue command on the next line
_____________________________________________________________________________________________________
9. Arrays and Hash Tables
------
Arrays
------
Arrays can be declared with values in the following ways:
$a = @() # declare an empty array, or re-initialize an existing array.
$a = @("a3","a1","a4","a2") # declare an array of values
Multi-Dimensional Arrays
$array = (1,2,3), (4,5,6), (7,8,9) # a 3x3 array
Write-Host $array[0][2] # the output is: 3
[0][0] [0][1] [0][2] [1][0] [1][1] [1][2] [2][0] [2][1] [2][2]
$array = ( 1 , 2 , 3 ),( 4 , 5 , 6 ),( 7 , 8 , 9 )
Array example 1:
$a = @("a3", "a1", "a4", "a2") # set values for array $a
$a = $a | Sort-Object [-Unique] # sort the array
$b = @("b1", "b2") # set values for array $b
$c = $a + $b # array $c is array $b appended to array $a
Write-Host "$c" # display array $c
The results are:
a1 a2 a3 a4 b1 b2
Array example 2:
[string] $s = "" # string variable
[string[]] $a = @("a1","a2","a3") # string array
foreach ($s in $a)
{
switch ($s) # 'switch' is case insensitive
{
"A1" {Write-Host "Value is a1" ; break}
"A2" {Write-Host "Value is a2" ; break}
"A3" {Write-Host "Value is a3" ; break}
$Null {Write-Host "Value is null" ; break}
default {Write-Host "Value is something else" }
}
}
This will not work:
$i[0] = 1 # use $i += 1
$i[1] = 2 # use $i += 2
If you want to display an array entry, you have to be careful. In the example below, when you
display the entry and use the subscripted array variable, it will display the entire array as
shown in lines marked #1. The other lines work correctly, you have to do the following to get
each one to work:
Line #2: You have to enclose the array entry in "$( ... )".
Line #3: You can remove the quotes, but then have to put back-ticks around any special
characters ('#' character, left parenthesis) and have to compensate for the fact
that only one single space will be displayed between each variable or word.
Line #4: You have to put the array entry into a variable, then use the variable for the
display.
[array] $a = @("x","y","z")
for ($i=0 ;$i -le 2; $i++)
{
Write-Host "#1: (Wrong!) Entry $i is $a[$i]" # The whole array $nn is written out.
Write-Host "#2: (Right!) Entry $i is $($a[$i])" # Each entry of the array is written out.
Write-Host `#3: `(Right!`) " " Entry $i is $a[$i] # Use a back-quote with special characters.
$s = $a[$i] # You can put the entry into a variable,
Write-Host "#4: (Right!) Entry $i is $s" # then use the variable for the display.
}
The output is:
#1: (Wrong!) Entry 0 is x y[0]
#2: (Right!) Entry 0 is x
#3: (Right!) Entry 0 is x
#4: (Right!) Entry 0 is x
#1: (Wrong!) Entry 1 is x y[1]
#2: (Right!) Entry 1 is y
#3: (Right!) Entry 1 is y
#4: (Right!) Entry 1 is y
To remove entries from the front of an array, you can do it this way:
$array = @("a","b","c","d")
$Null,$Null,$array = $array
The array now contains:
$array[0] is "c"
$array[1] is "d"
The array can also be split into variables and a different array:
$array = @("a","b","c","d")
$str1,$str2,$a = $array
The variables now contain:
$str1 is "a"
$str2 is "b"
$a[0] is "c"
$a[1] is "d"
To remove entries of an array, you have to append parts of the array. In this example, you remove
the 4th and 5th entries:
$array = @("a","b","c","d","e","f","g","h")
$a = $array[0..2] + $array[5..7]
The new array values are: "a", "b", "c", "f", "g", "h"
-----------
HASH Tables
-----------
Hash tables, which are sometimes called "dictionaries" in other computer languages, are
key/value arrays. Hash keys are case insensitive! Here are the operations that can be
performed:
$hash_tbl = @{} Declare the hash table
4 Ways to ADD to hash tables
$hash_tbl.Add("key1","value1") 1: add a value for key1
$hash_tbl["key1"] = "value1" 2: add a value for key1
$hash_tbl."key1" = "value1" 3: add a value for key1
$hash_tbl += @{"key1" = "value1" } 4: add a value for key1
3 Ways to GET the value of hash tables
$val = $hash_tbl.Get_Item("key1") 1: get a value for key1
$val = $hash_tbl["key1"] 2: get a value for key1
$val = $hash_tbl."key1" 3: get a value for key1
3 Ways to CHANGE value for hash tables
$hash_tbl.Set_Item("key1","newval1") 1: change value for key1
$hash_tbl["key1"] = "newval1" 2: change value for key1
$hash_tbl."key1" = "newval1" 3: change value for key1
2 Ways to EMPTY a hash table
$hash_tbl.Clear 1: empty the hash table
$hash_tbl = @{} 2: empty the hash table
Other/misc methods/properties/etc
$hash_tbl.Remove("key1") Remove value for key1
$hash_tbl.ContainsKey("key1") True if key is there
$hash_tbl.ContainsValue("value1") True if value is there
$nbr = $hash_tbl.Count Get number of keys in the hash table
if ($hash_tbl."key1" -eq $Null) Check for no entry for the key
foreach ($key in $hash_tbl.Keys) Loop through all keys
{$value = $hash_tbl.$key } and get all values
To order keys in a hash table:
$newHashtbl = $hash_tbl.GetEnumerator() | Sort-Object Name [-Descending]
To add multiple keys/values into a hash table:
$Hash_Table = @{"Key1" = "value1"; "Key2" = "val2"; "Key3" = 3; ... }
_____________________________________________________________________________________________________
10. PowerShell Operators
PowerShell has a number of native operators for math and/or strings. They are CASE-INSENSITIVE
by default.
--------- -----------------------------------------------------------
-contains True if an array entry exactly matches the string provided.
--------- -----------------------------------------------------------
Syntax: $array -Contains $string # return TRUE/FALSE
$boolean = $array -Contains $string # return TRUE/FALSE
Example:
$a = @("abc", "defg", "hijkl") # $a is an array
if ($a -Contains "defg")
{Write-Host "Array contains an entry equal to 'defg'" }
Variants:
-ccontains = case-sensitive match
-icontains = case-insensitive match (same as -contains)
-notcontains = not a case-sensitive match
-cnotcontains = not a case-sensitive match
-inotcontains = not a case-insensitive match (same as -notcontains)
--------- --------------------------------------------------------
-f Format Operator
--------- --------------------------------------------------------
Syntax: $string = "{0} {1} ..." -f $var1,$var2,...
The format is "{F,ML:TZ} ......." -f $field1,...
where: F = number of FIELD: first field is 0
M = MINUS sign: use to left justify the data
L = total LENGTH of field
T = TYPE of data (c,C,d,hh,mm,p,x,X,etc)
Z = length of decimal field with leading ZEROS
Examples:
Operator Description Example Results
-------- -------------------------------- ----------------------------- --------
{0} Display a particular element "{0} {1}" -f "a", "b" a b
{0:x} Display a number in Hexadecimal "0x{0:x}" -f 181342 0x2c45e
{0:X} Display a number in Hexadecimal "0x{0:X}" -f 181342 0x2C45E
using uppercase
{0:dn} Display a decimal number right "|{0,5:d4}|" -f 123 | 0123|
justified, zero padded
{0,n} Display a decimal number right "|{0,5}|" -f 3 | 123|
justified, space padded
{0,-n} Display a decimal number left "|{0,-5}|" -f 3 |123 |
justified
{0:p} Display a number as a percentage "{0:p}" -f .123 12.30 %
{0:c} Display a number as currency "{0:c}" -f 12.34 $12.34
{0,n} Display with field width n, "|{0,5}|" -f "hi" | hi|
right aligned
{0,-n} Display with field width n, "|{0,-5}| -f "hi" |hi |
left aligned
{0:hh}
{0:mm} Display the hours and minutes "{0:hh}:{0:mm}" -f (Get-Date) 01:34
from Get-Date
{0:C} Display using the local currency "|{0,8:C}|" -f 12.3 | $12.40|
symbol
--------- --------------------------------------------------------
-in Comparison of value with values in an array.
--------- --------------------------------------------------------
Syntax: $String -in $Array # returns TRUE/FALSE
$boolean = $String -in $Array # returns TRUE/FALSE
Note: '-in' does not use regular expressions or wildcards ('*').
Examples:
$Array = @("a1","a2","a3")
"a" -in $Array # returns FALSE because there is no match
"a1" -in $Array # returns TRUE because it matches 1st entry of array.
Variants:
-cin = case-sensitive match
-iin = case-insensitive match
-notin = True if not in array
-cnotin = True if not in array (case-sensitive)
-inotin = True if not in array (case-insensitive)
--------- --------------------------------------------------------
-join Join all the elements of an array together.
--------- --------------------------------------------------------
Syntax: $OutString = -join $Array # join without a separator
$OutString = $Array -join separator # join with a separator
Where: separator = String of characters to put between each array entry.
Note: You can also join all elements of an array this way:
$OutString = [string]$Array # join without a separator
$OFS = separator # this will stay until over-ridden
$OutString = [string]$Array # join with a separator
--------- --------------------------------------------------------
-like Comparison with optional wildcards ('*').
--------- --------------------------------------------------------
Syntax: $String1 -Like $String2 # returns True/False
$Array -Like $String # returns all that match
Note: '-like' does not use regular expressions, just wildcards ('*').
Examples:
"abcd" -like "D" # returns TRUE (contains a 'd')
"abcd" -like "b*" # returns TRUE
$array = @("a1","a2","a3")
$array -like "a" # returns FALSE because there is no match
$array -like "a*" # returns "a1 a2 a3" because all 3 match 'a*'
Variants:
-clike = case-sensitive match
-ilike = case-insensitive match
-notlike = True if not alike
-cnotlike = True if not alike (case-sensitive)
-inotlike = True if not alike (case-insensitive)
--------- --------------------------------------------------------
-match Regular expression comparison
--------- --------------------------------------------------------
Syntax: $String1 -Match $String2 # returns True/False
$Array -Match $String # return all that match
Note: '-match' uses the following special regular expression characters:
\w = alphanumeric characters (word)
\s = whitespace characters
\d = digits
\W = non-alphanumeric characters
\S = non-whitespace characters
\D = non-digits
Examples:
"2468" -Match "\d" # returns TRUE (all digits)
"abcd" -Match "b" # returns TRUE
$Array = @("a1","a2","a3")
$Array -Match "a" # returns "a1 a2 a3" because all 3 contain an 'a'
Variants:
-cmatch = case-sensitive match
-imatch = case-insensitive match
-notmatch = True if not a match
-cnotmatch = True if not a match (case-sensitive)
-inotmatch = True if not a match (case-insensitive)
--------- --------------------------------------------------------
-replace Replace a substring with another substring.
--------- --------------------------------------------------------
Syntax:
-Replace(OriginalSubString,NewSubString)
$Out = $In -Replace($old,$new)
Example:
$original = "This string is original"
$newstring = $original -Replace("original","new")
$newstring now contains: "This string is new"
Note: Regular expressions can be used.
Variants:
-creplace = case-sensitive replace
-ireplace = case-insensitive replace
--------- --------------------------------------------------------
-split Split a string into an array
--------- --------------------------------------------------------
Syntax: -Split separator[,max][,option]
where:
separator = The delimiter used to split the string on. This is a string of
one or more characters.
max = The maximum number of array entries that will be created. A value
zero means that there is no maximum.
option = An option, such as "SimpleMatch", which causes the split to NOT
use Regular Expressions. The default is "RegexMatch".
Examples:
[string[]] $a = () # array
[string] $s = "a b c d" # string of characters separated by a space
$a = $s -split " ",0,"SimpleMatch" # split the string into an array
As opposed to PERL, which automatically handles multiple spaces as one space,
PowerShell will split on every space and end up with empty entries in the
resulting array. The following code with get around this:
[string[]] $a = () # array
[string] $old = "a b c d" # string of characters separated by spaces
[string] $new = "" # a new string
$new = $old -replace "\s{2,}" # new string with single spaces between
# letters
$a = $new -split " ",0,"SimpleMatch" # split the string into an array
# max_entries of zero means no maximum
Or the last 2 lines can be merged:
$a = ($old -replace "\s{2,}"," ") -split " ",0,"SimpleMatch"
$s = "a<~>b<~>c<~>d" # separator is "<~>"
$a = $s -split "<~>",0,"SimpleMatch" # split on multiple character separators
Variants:
-csplit = case-sensitive split
-isplit = case-insensitive split (same as -split)
_____________________________________________________________________________________________________
11. PowerShell .NET Methods
Besides its own native operators, PowerShell supports .NET string methods. These are all case
SENSITIVE.
------------ --------------------------------------------------------
Contains() Check for a substring within a string
------------ --------------------------------------------------------
Syntax: $Boolean = $InString.Contains(substring)
Returns: "True" if a specified comparison string (substring) is in a string
or if the comparison string is empty. False is returned otherwise.
Example:
[bool $b = $False
$b = ("Hello").Contains("ll")
$b will be True
------------ --------------------------------------------------------
EndsWith() Tests whether the string ends with a specified string.
------------ --------------------------------------------------------
Syntax: $Boolean = $InString.EndsWith(string)
Returns: "True" if a string ends with a specified substring.
Example:
("Hello").EndsWith("lo")
This will return True.
------------ --------------------------------------------------------
IndexOf() Returns the index of the first occurrence of a substring.
------------ --------------------------------------------------------
Syntax: $integer = $InString.IndexOf(substring[,offset[,count]])
Where: substring = the string being searched for.
offset = optional position to start searching.
count = optional number of characters to search through.
Returns: -1 if the substring is not found and the position of the first character if it
is found.
Example:
("Hello").IndexOf("L")
This will return -1 since the 'L' is not found because it is uppercase and .NET
methods are case sensitive. If the 'L' had been lowercase, a value of 2 would
have been returned.
------------ --------------------------------------------------------
IndexOfAny() Returns the index of the first occurrence of any character
------------ in a comparison string.
--------------------------------------------------------
Syntax: $integer = $InString.IndexOfAny(string)
Example:
$n = ("Hello").IndexOfAny("loe")
This will return the value 1 since 'e' is the first character to be found (of the
3 characters: 'l', 'o', and 'e') and it is in position 1 (the second position).
------------ --------------------------------------------------------
Insert() Inserts new string at a specified index in an existing string.
------------ --------------------------------------------------------
Syntax: $OutString = $InString.Insert(position,new_string)
Where: 'position' is where the 'new_string' is inserted.
Example: $s = ("Hello World").Insert(6,"Brave New ")
This will return the string "Hello Brave New World".
------------- --------------------------------------------------------
LastIndexOf() Finds the index of the last occurrence of a substring.
------------- --------------------------------------------------------
Syntax: $integer = $InString.LastIndexOf(substring)
Returns: -1 if the string is not found and the position of the first character of the
last occurence of the string if it is found.
Example:
$n = ("Hello").LastIndexOf("l")
This will return a value of 3.
---------------- --------------------------------------------------------
LastIndexOfAny() Finds the index of the last occurrence of any character
---------------- of a specified string.
--------------------------------------------------------
Syntax: $integer = $InString.LastIndexOfAny(string)
Returns: -1 if the none of the characters are found and the position of the last
character to be found otherwise.
Example:
$n = ("Hello World").LastIndexOfAny("loe")
This will return a value of 9, the location of 'l' in 'World'.
------------ --------------------------------------------------------
PadLeft() Pads string to a specified length and adds characters
------------ (default is spaces) to the left (right-aligned string).
--------------------------------------------------------
Syntax: $Out = $In.PadLeft(length_to_pad_string_to[,pad_char])
------------ --------------------------------------------------------
PadRight() Pads string to a specified length and adds characters
------------ (default is spaces) to the right (left-aligned string).
--------------------------------------------------------
Syntax: $Out = $In.PadRight(length_to_pad_string_to[,pad_char])
------------ --------------------------------------------------------
Remove() Removes the specified number of characters starting from
------------ a particular position.
--------------------------------------------------------
Syntax: $out = $in.Remove(position,nbr_to_remove)
Returns: The string with the characters removed.
Note: If 'nbr_to_remove' is greater than the number of characters available, an
error will occur. An error will also occur if the position is beyond the end
of the string. If 'nbr_to_remove' is not specified, then all characters will
be removed from the position given to the end of the string.
Example:
$s = ("Hello World").Remove(5,6)
This will return the string " Hello".
------------ --------------------------------------------------------
Replace() Replaces characters with other characters.
------------ --------------------------------------------------------
Syntax: $OutString = $InString.Replace(old,new)
Note: By default all occurences of a string are replaced:
Example: $OutString = ("Hexxo Worxd").Replace("x","l")
This will return the string "Hello World".
To replace only the first occurence of a string:
$s = "123a567a890a"
$regex = [Regex] "a"
$regex.Replace($s,"b",1) # The third parameter specifies the maximum
# number of times to replace the string.
This will return: "123b567a890a"
------------ --------------------------------------------------------
Split() Converts a string with specified splitting points into an array.
------------ --------------------------------------------------------
Syntax: $OutArray = $InString.Split(separator[,option|max_entries]) # if 2 parameters
$OutArray = $InString.Split(separator[,max_entries,option]) # if 3 parameters
Where: separator = A character that will be used to split the input string when found.
option = Either "None" or "RemoveEmptyEntries" (when you have 2 separators
side-by-side).
max_entries = The maximum number of array entries to that the string will be
split into.
Examples:
Set up a string, an array, and an option for '.Split':
[string] $s = "a,,b,c"
[string[]]$a = @()
[StringSplitOptions] $opt = "RemoveEmptyEntries"
Splitting on back-to-back separators will result in null elements:
$a = $s.Split(",")
Result: $a[0] = "a"
$a[1] = $Null
$a[2] = "b"
$a[3] = "c"
No nulls if we "Remove Empty Entries":
$a = $s.Split(",",$opt)
Result: $a[0] = "a"
$a[1] = "b"
$a[2] = "c"
Split on a maximum of 2 entries:
$a = $s.Split(",",2)
Result: $a[0] = "a"
$a[1] = ",b,c"
Maximum entries is 2, plus remove the empty entries:
$a = $s.Split(",",2,$opt)
Result: $a[0] = "a"
$a[1] = "b,c"
Split on a multi-character separator:
$s = "a<~>b<~>c<~>d" # separator is "<~>"
[string[]] $sep = "<~>" # an array: 1st entry is the separator
[StringSplitOptions] $opt = "None" # set a value for the option
$a = $s.Split($sep,$opt) # split into an array using <~> as
# the separator
Result: $a[0] = "a"
$a[1] = "b"
$a[2] = "c"
$a[3] = "d"
------------ --------------------------------------------------------
StartsWith() Tests whether a string begins with certain character(s).
------------ --------------------------------------------------------
Syntax: $Result = $InString.StartsWith(substring)
Returns: True if the substring is found at the beginning of the specified string.
Examples:
[bool] $b = ("Hello World").StartsWith("He")
[int] $n = ("Hello World").StartsWith("He")
The returned values are $b = $True and $n = 1.
------------ --------------------------------------------------------
Substring() Extracts characters from a string.
------------ --------------------------------------------------------
Syntax: $OutString = $InString.Substring(position,length)
Returns: The number of specified characters starting at the specified position. If
'length' is not supplied, then the substring from 'position' to the end of the
string is returned. Negative values of 'position' and 'length' are not valid.
Example:
$s = ("Hello World").Substring(4,3)
This will return the string "o W".
------------- --------------------------------------------------------
ToCharArray() Converts a string into a character array.
------------- --------------------------------------------------------
Syntax: $OutArray = $InString.ToCharArray()
Example: $a = ("abc").ToCharArray()
The array will contain:
$a[0] = "a"
$a[1] = "b"
$a[2] = "c"
------------ --------------------------------------------------------
ToLower() Converts a string to lowercase.
------------ --------------------------------------------------------
Syntax: $OutString = $InString.ToLower()
Example: $s = ("Hello World").ToLower()
The result will be: "hello world"
------------ --------------------------------------------------------
ToUpper() Converts a string to uppercase.
------------ --------------------------------------------------------
Syntax: $OutString = $InString.ToUpper()
------------ --------------------------------------------------------
ToString() Converts a number to a string (without formatting it)
------------ --------------------------------------------------------
Syntax: $OutString = $InNumber.ToString()
------------ --------------------------------------------------------
Trim() Removes blank characters to the right and left.
------------ --------------------------------------------------------
Syntax: $OutString = $InString.Trim(string|array)
Where: The argument is either a string of one or more characters to remove, or an
array with each entry being a string of one or more characters to remove. If
not present, the default is to trim all whitespace.
------------ --------------------------------------------------------
TrimEnd() Removes blank characters on the right.
------------ --------------------------------------------------------
Syntax: $OutString = $InString.TrimEnd(string|array)
------------ --------------------------------------------------------
TrimStart() Removes blank characters on the left.
------------ --------------------------------------------------------
Syntax: $OutString = $InString.TrimStart(string|array)
------------ --------------------------------------------------------
Chars() Retrieves a character at the specified position.
------------ --------------------------------------------------------
Syntax: $OutString = $InString.Chars(position)
Example: $OutString = ("Hello").Chars(1)
The output of this will be "e".
------------ --------------------------------------------------------
Length Return the length of a string or the number of entries
------------ in an array.
--------------------------------------------------------
Syntax: $Integer = $String.Length
$Integer = $Array.Length
This is not a method (no parentheses), but a property.
------------ --------------------------------------------------------
Count The number of entries in an array.
------------ --------------------------------------------------------
Syntax: $Integer = $Array.Count
This is not a method (no parentheses), but a property.
The .NET methods can be stacked together. For example:
$s = "Hello There" # start with this string
$x = $s.ToUpper() # make it uppercase
$y = $x.Replace("THERE","WORLD") # replace the string
$y = $s.ToUpper().Replace("THERE","WORLD") # combined methods
_____________________________________________________________________________________________________
12. I/O and File-related Commands and Cmdlets
-------------- --------------------------------------------------------
Add-Content Append data to a file.
-------------- --------------------------------------------------------
Syntax: Add-Content file $array
Example: Add-Content "dir\file.txt" $data
-------------- --------------------------------------------------------
Get-ChildItem Get child items (contents of a folder)
-------------- --------------------------------------------------------
Syntax: Get-ChildItem [ [-Path] string[] | [-LiteralPath] string[] ]
[-Exclude string[] [-Name]
where:
-Path = The paths to the items from which content is to be retrieved.
Wildcards are permitted. Default is the current directory (.)
-LiteralPath = Like Path above, only the value is used exactly as typed. No
characters are interpreted as wildcards. If the path includes any
escape characters then enclose the path in single quotation marks.
-Exclude = Omit the specified items from the Path.
-Name = Retrieve only the names of the items. This is useful when
piping the names of the child items to another command.
Examples:
To see if a file is empty:
Get-ChildItem c:\scripts\file.ext | Where-Object {$_.length -eq 0}
To find file's that are named 'xxx':
Get-ChildItem c:\scripts | Where-Object {$_.name -eq "xxx"}
To find file's that have extensios named 'ini':
Get-ChildItem c:\scripts | Where-Object {$_.extension -eq ".ini"}
To get a list of files and save in an array:
$list = Get-ChildItem c:\scripts\file.*
Loop through the list of files in the array:
foreach ($file in $list)
Combined command to loop through the list of matching files:
foreach ($file in Get-ChildItem C:\scripts\file.*)
-------------- -------------------------------------------------------
Get-Content Read all lines of a file into an array. Each line is an
-------------- -------------------------------------------------------
Syntax: $array = Get-Content [-Encoding Byte] [-ReadCount n] file
Where: ReadCount = The number of bytes read in at a time. Zero means read all bytes
in at once (which will result in the fastest reading speeds).
Note: Each line is an array entry. Large files will use a large amount of memory.
Example:
$data = Get-Content -Encoding Byte -ReadCount 0 "dir\file.txt"
-------------- --------------------------------------------------------
New-Item Create a new object, such as a new folder/directory
-------------- --------------------------------------------------------
Syntax: New-Item -Path folder_name -ItemType directory > "out.log"
where:
-Path = Name of the new folder/directory to create
-------------- --------------------------------------------------------
Out-File Send output to a file
-------------- --------------------------------------------------------
Syntax: Out-File [-filePath path] string [-append] [-force] [-width n] [-encoding ASCII]
where:
-force = Over-writes a read-only file
-width n = Set width of output, defaults to cmd window width (80)
-------------- --------------------------------------------------------
Remove-Item Delete an item/file
-------------- --------------------------------------------------------
Syntax: Remove-Item "C:\Temp\outfile.txt"
Examples:
Delete all temporary files:
foreach ($file in Get-ChildItem .\*.tmp)
{Remove-Item $file }
Does not work:
Remove-Item filename*.ext
Using INCLUDE and EXCLUDE:
Remove-Item .\* [-include *.ex1,*.ex2] [-exclude abc*.ex2]
-------------- --------------------------------------------------------
Rename-Item Change the name of an existing item
-------------- --------------------------------------------------------
Syntax: Rename-Item [-Force] oldname.ext newname.ext
Where: -Force = Override the read-only attribute.
Example:
Rename-Item "oldname.ext" "newname.ext"
-------------- --------------------------------------------------------
Split-Path Return part of a path
-------------- --------------------------------------------------------
Syntax: $outstring = Split-Path file_spec [-Parent] [-Leaf]
[-Qualifier] [-NoQualifier]
Where: -Parent = Return just the file_spec without the filename
and without the extension (the default action).
-Leaf = Return just the filename and extension.
-Qualifier = Return just the device name.
-NoQualifier = Return the folder (path) without the device name.
-------------- --------------------------------------------------------
Test-Path TRUE if the path/file exists, otherwise return FALSE
-------------- --------------------------------------------------------
Syntax: Test-Path "Folder\Subfolder\filename.ext" [-PathType [container|leaf]]
[-Include files(s)] [-Exclude file(s)]
Examples:
True if folder 'data' exists and is a folder:
if (Test-Path C:\data -PathType container)
True if 'xyz' exists and is NOT a folder:
if (Test-Path C:\data\xyz -PathType leaf)
True if 'file.txt' exists:
if (Test-Path "C:\data\file.txt")
True if any '.txt' files exist:
if (Test-Path C:\data\*.txt)
True if any '.txt' or '.dat' files exist:
if (Test-Path C:\data\* - include *.txt,*.dat)
True if any files besides '.txt' or '.dat' exist
if (Test-Path C:\data\* - exclude *.txt,*.dat)
-------------- --------------------------------------------------------
I/O Example: Copy a file using .NET I/O
-------------- --------------------------------------------------------
$OutFile = [System.IO.StreamWriter] "file_out.txt"
foreach ($line in [System.IO.File]::ReadLines("file_in.txt"))
{
$OutFile.WriteLine($line)
}
$OutFile.Close()
Note: The 'foreach' file input format works with PowerShell 3.0 or later only.
_____________________________________________________________________________________________________
13. Functions, Arguments, and Global/Local Variables
Functions & Arguments
---------------------
PowerShell supports subroutines, which are called functions. One or more parameters can
optionally be passed into the functions and one or more return values can be passed back. The
formats for function calls are:
FuncName [$val1 [,$val2,...]] No return values
$ret = FuncName [$val1 [,$val2,...]] One return value
($ret1[,$ret2,...]) = FuncName [$val1 [,$val2,...]] Two or more return values
The format for the function itself is shown below. Each argument can optionally have a default
value.
function FuncName[([datatyp]$arg1[=def1],[datatyp]$arg2[=$def2]),...]
{ Body of function
... if no return values
}
{ Body of function
... if one return value
return $ret1
}
{ Body of function
... if two or more return values
return ($ret1[,$ret2,...])
}
The number of return values that the function call expects and the number of values that the
function returns must exactly match. When a function is called, the actual number of arguments
passed to the function can vary, but if the function expects some of them to be optional, they
should be given default values. Otherwise they will be null ($Null) if they do not have a
datatype declared or will be an empty string if the datatype is '[string]', the value zero if the
datatype is '[int]', 'False' ($False) if the datatype is '[bool]', etc. The function must be
declared before it is referenced, which forces the main routine to be at the bottom of a script.
Functions are called by using the name of the function and the arguments separated by spaces:
FuncName "Val1" "" "Val3" # Correct (no commas, no parentheses)
FuncName("Val1",,"Val3") # INCORRECT - will NOT work!
Arguments Passed Into Scripts
-----------------------------
When running a script all parameters that are used are passed into the script via the array
'$args'. Users can use the array to see how parameters were passed and to see what values were
included. PowerShell has a built-in function named 'Param' that helps you define your parameters.
You can then use the $args variable to get them. However, a function has already been created
which does all that for you. It is in Appendix A and includes the necessary documentation.
Global/Local Variables
----------------------
Variables can be made global in the main routine, and then they can be read and updated anywhere,
including the functions. The way to make them global can be seen in this example:
Set-Variable USERNAME -option Allscope
[string] $USERNAME = ""
Global variables should have a naming convention that indicates that they are global. Be sure to
remember that variable names are case-insensitive ($USERNAME, $UserName, and $username are the
SAME variable). Some suggestions are:
1. Name global variables using uppercase letters: $USERNAME
Name local variables using different lowercase letters: $usrname
2. Name global variables using mixed-case letters: $UserName
Name local variables using different lowercase letters: $usrname
3. Name global variables using a special global prefix: $global_username
or: $gbl_username
Name local variables using a special local prefix: $loc_username
or no prefix at all: $username
The main routine of a script can declare local variables. If a function uses a local variable
that has the same name as a local variable in the main routine, the variable will have the value
that it had in the main routine. If the function changes the value, it will only be changing the
value of its local variable. That local variable will cease to exist when the function exits.
Local variables in a function are always private. To make local variables in the main routine
private, you have to declare them as in this example:
[string] $private:option = "None"
Once declared, the variable can be referenced by the name without "private:". In the example
above, that would be "$option".
_____________________________________________________________________________________________________
14. Miscellaneous Information
Running a command file
----------------------
$CmdFile = [System.IO.StreamWriter] "file.cmd"
$CmdFile.WriteLine("echo Value of TEMP is %TEMP%")
$CmdFile.Close()
& ".\file.cmd"
Getting the value of an Environmental Variable
----------------------------------------------
$s = $Env:TEMP # get value of TEMP
if ($s) # if $s is not $Null or $False
{Write-Host "Value of TEMP is: $s" } # then display the value
Dynamically executing a PowerShell command
------------------------------------------
$List = "abc"
Write-Host "List (before) is ==>$List<=="
$string = "`$List = `"def`""
Invoke-Expression $string
Write-Host "List (after) is ==>$List<=="
Using PowerShell 'here-strings'
-------------------------------
A 'here-string' is a way to easily get multiple lines to be displayed or into a variable
and to be able to ignore quotes. Note that variables do not get translated when they are
inside single quotes.
$money = "10.00"
Write-Host @"
You owe "Bob" $money
so pay him now.
"@
$string = @'
You owe "Bob" $money
so pay him now.
'@
Write-Host $string
When run, the output is:
You owe "Bob" 10.00
so pay him now.
You owe "Bob" $money
so pay him now.
Using a "here-string" with file output:
$OutFile = [System.IO.StreamWriter] "file.dat"
$OutFile.WriteLine(@"
Data that will be put into the output file
when the script is run.
"@)
$OutFile.Close()
Set width/height/title/color of window
--------------------------------------
You can set the width, height, title, and color of a command window used by PowerShell by
using the following commands:
$pswindow = (get-host).UI.RawUI # get powershell window structure/pointer
$newsize = $pswindow.buffersize # use if manually setting window size
$newsize.Width = 150 # if manually setting size, re-size buffer first ...
$newsize.Height = 3000 # both width and height
$pswindow.Buffersize = $newsize # save the new buffer size
$newsize = $pswindow.WindowSize # get the window size
$newsize.Width = 150 # not needed if using 'mode con' below
$newsize.Height = 75 # not needed if "PowerShell.exe -WindowStyle Maximized ..."
$pswindow.WindowSize = $newsize # only needed if setting width or height
$pswindow.WindowTitle = "Cincom Systems, Inc. - Program/Utility/Script"
$pswindow.BackgroundColor = "black"
$pswindow.ForegroundColor = "white"
$host.UI.RawUI.CursorPosition.X = 1
$host.UI.RawUI.CursorPosition.Y = 2
If you have maximized the height of the window using "-WindowStyle Maximized", then you get the
height of the window and set the width of the window using these commands (where the width is
set using $WIDTH_OF_WINDOW and the height of the window (in lines) is put in $HEIGHT_OF_WINDOW.
$buffer = $Host.UI.RawUI.BufferSize
if ($WIDTH_OF_WINDOW -lt $buffer.Width)
{$WIDTH_OF_WINDOW = $buffer.Width }
$buffer.Width = $WIDTH_OF_WINDOW
$buffer.Height = 4096
$Host.UI.RawUI.Set_BufferSize($buffer)
$maxWS = $Host.UI.RawUI.Get_MaxWindowSize()
$ws = $Host.UI.RawUI.WindowSize
$ws.Width = $maxWS.Width
$ws.Height = $maxWS.Height - 1
$WIDTH_OF_WINDOW = $ws.Width
$HEIGHT_OF_WINDOW = $ws.Height
$Host.UI.RawUI.Set_WindowSize($ws)
$Host.UI.RawUI.WindowTitle = "Cincom Systems, Inc. - Program/Utility/Script"
$Host.UI.RawUI.BackgroundColor = "black"
$Host.UI.RawUI.ForegroundColor = "white"
You can use .NET to get the maximum window width and height:
$max_x = [Console]::LargestWindowWidth
$max_y = [Console]::LargestWindowHeight
And also to set the height, width, and title:
[console]::WindowHeight = 45
[console]::WindowWidth = 128
[console]::Title = "Cincom Systems, Inc. - Program/Utility/Script"
Sort a file in a PowerShell script
----------------------------------
sort.exe /O "outfile.txt" "infile.txt"
Linefeeds (newlines) in file I/O
--------------------------------
This line:
$XxxFile.Writeline("xyz`n")
will write out an extra line, but it will have just a linefeed (newline) character for
carriage-control. A better way would be to use either:
$XxxFile.Writeline("xyz`r`n")
or make 2 lines:
$XxxFile.Writeline("xyz")
$XxxFile.Writeline("")
Mix strings and non-strings
---------------------------
Use the .NET function: Concat
[string]::Concat("Today is ", (Get-Date)) # This will display today's date/time
Join elements of an array into a string
---------------------------------------
Use the .NET function: join
$string = [string]::join(",", $array) # This will append all elements of the array, with
# each element separated by a comma.
Get the FULLNAME, DIRNAME, and BASENAME for the script being run.
-----------------------------------------------------------------
$FULLNAME = $MyInvocation.MyCommand.Path # C:\folder\subfolder\name.ps1
$FILENAME = Split-Path $FULLNAME -Leaf # name.ps1
$BASENAME = $FILENAME.Replace(".ps1","") # name
$DIRNAME = Split-Path $FULLNAME -Parent # C:\folder\subfolder
Get the version of PowerShell that is running
---------------------------------------------
To get the major version of PowerShell (such as 2, 3, or 4):
$version = $PSVersionTable.PSVersion.Major
Converting to loosely-typed variables
---------------------------------------------
Strongly (explicitly) typed values are converted by PowerShell for you when you move a value
from one type of field to another, since PowerShell knows what type the variable was and the
type that it has to be converted to. You will get an error if the value is not valid for the
type (such as alphabetic characters in a numeric field). When data is copied to fields that
are not typed (and which will get implicitly typed), you have to cast or convert the data.
Some conversions have multiple ways they can be done.
Convert a string to a number Convert a number to a string
---------------------------------- ----------------------------
$nbr = [int] $str $str = [int] $nbr
$nbr = $str -as [int] $str = $nbr -as [string]
$nbr = [convert]::ToInt32($str) $str = $nbr.ToString()
Note: If a string cannot be converted to a number (because it contains non-numeric data) when
using "-as [int]" and that field had no data type declared, then you do not get an
error and the field will be null.
Get the ordinal value of a character
---------------------------------------------
$n = [int][char]$s # $n = decimal value of character in $s
[char]$c = $s.Substring(1,0) # or put in char field, then
$n = [int]$c # convert to type [int]
_______________________________________________________________________________________________________________
Appendix A - Text of the Get_Options function
#########################################################################(v3)#
# Purpose: To get command line input, which include switches, options, #
# required parameters, and optional parameters. #
# For example: scrpt.ps1 -verbose -logfile out.log inpfile inp_nbr #
# -------- ---------------- ------- ------- #
# switch option + value reqparm optparm #
# Input : $argm = The array of command-line parameters (args). #
# $switches = List of switches and options with values to set. #
# Format: [type]$VAR=val, ... , ... #
# where: [type] = Optional type of field, the default #
# is "[string]". Valid values are #
# [string], [int], and [bool]. #
# $VAR = The name of the variable. #
# "=val" = Optional value for a switch or option.#
# The default value for a [bool] type #
# is "$True". #
# $reqparms = List of required parameters: names of variables to #
# hold the required input (comma separated). #
# Format: [type]$VAR1,[type]$VAR2, ... #
# $optparms = List of optional parameters: names of variables to #
# hold the optional input (comma separated). #
# Format: [type]$VAR1,[type]$VAR2, ... #
# #
# Example: To call --> get_options $args $switches $rparms $oparms #
# where: $args = command-line arguments (use literally) #
# $switches = '[bool]$VERBOSE,[string]$LOGFILE' #
# $rparms = '[string]$INPFILE' #
# $oparms = '[int]$INP_NBR' #
# Note 1: The list of parameters HAS to be in single-quotes. #
# Note 2: Calls 'display_usage' if '-?' is seen. #
# Note 3: The main entry point should have the following set up #
# for this example: #
# Set-Variable VERBOSE -option Allscope #
# [bool] $VERBOSE = $False #
# Set-Variable INPFILE -option Allscope #
# [string] $INPFILE = "" #
# Set-Variable LOGFILE -option Allscope #
# [string] $LOGFILE = "" #
# Set-Variable INP_NBR -option Allscope #
# [int] $INP_NBR = 0 #
##############################################################################
function get_options([string[]]$argm,[string]$switches="",[string]$reqparms="",[string]$optparms="")
{
if ($switches.Count -eq 0 -and $reqparms.Count -eq 0 -and $optparms -eq 0)
{Write-Host "*ERROR* No values passed to get_options ... exiting."
exit 1
}
######################################################################
# Set up the local variables that will be used within the function #
######################################################################
$var = "" # variable with undeclared type
[int] $len = 0 # length of value
[int] $n = 0 # temp value of subscript
[int] $ndx = 0 # index into input option list
[int] $numreq = -1 # required parms number
[int] $numopt = -1 # optional parms number
[int] $optnbr = -1 # option nbr for names/values
[int] $maxopt = 0 # maximum optional parameters
[int] $maxreq = 0 # maximum required parameters
[string] $opt = "" # option
[string] $s = "" # temp string
[string] $param = "" # a single parameter
[string] $value = "" # a single value
[string[]] $t = @() # temp array
[string[]] $arg = @() # array of options
[string[]] $rparms = @() # array of required parameters
[string[]] $oparms = @() # array of optional parameters
[string[]] $sw_name = @() # array of switch names
[string[]] $sw_type = @() # array of switch types
[string[]] $sw_data = @() # array of switch values
######################################################################
# Parse and save option strings that were passed into the function #
######################################################################
if ($argm.Count -gt 0) # if nothing entered & some required
{if ($switches -ne "" -and $switches -ne ".")
{$arg = $switches.Split(",") # get OPTIONS
foreach ($opt in $arg)
{
if ($opt.Substring(0,1) -eq "[") # if data-type included
{$n = $opt.IndexOf("]") + 1 # find the end of the type: [...]
if ($n -le 0)
{Write-Host "*ERROR* Invalid specification: missing right bracket: $opt"
exit 1
}
$sw_type += $opt.Substring(0,$n) # save data-type
$opt = $opt.Substring($n) # option without data-type
}
else
{$sw_type += "" } # no data-type
if ($opt.Contains("="))
{$t = $opt.Split("=")
if ($t[0] -eq "")
{Write-Host "*ERROR* Variable name missing on option: $opt"
exit 1
}
if ($t[1] -eq "")
{Write-Host "*ERROR* Value missing on option: $opt"
exit 1
}
$s = $t[0] # name of option
$sw_data += $t[1]
}
else
{$s = $opt # name of option
$sw_data += ""
}
$opt = $s.Replace("$","-")
$sw_name += $opt # save option name
}
}
}
if ($reqparms -ne "" -and $reqparms -ne ".") # get REQUIRED parameters
{$rparms = $reqparms.Split(",") # parse on commas: req parms
$maxreq = $rparms.Count
}
if ($optparms -ne "" -and $optparms -ne ".") # get OPTIONAL parameters
{$oparms = $optparms.Split(",") # parse on commas: optional parms
$maxopt = $oparms.Count
}
######################################################################
# Parse and check parameters that were entered on the command-line #
######################################################################
if ($argm.Count -le 0 -and $maxreq -gt 0) # if nothing entered & some required
{Write-Host "*ERROR* Parameters required is $maxreq, but none entered"
display_usage # parameters, then display usage
exit 0 # and exit
}
foreach ($opt in $argm)
{if ($optnbr -ge 1000) # if special flag was set get value
{$optnbr -= 1000 # then subtract 1000 (orig opt nbr)
$sw_data[$optnbr] = $opt # save the next cmd line value
$opt = $sw_name[$optnbr] # and get the original switch
$optnbr = -1
}
$len = $opt.Length # length of argument
if ($len -eq 2 -and $opt -eq "-?")
{display_usage # Make sure you have a function
exit 0 # written to show proper usage!
}
else ##########################
{if ($len -gt 1 -and $opt.Substring(0,1) -eq "-") # GET SWITCHES (OPTIONS) #
{$ndx = -1 ##########################
$optnbr = -1
foreach ($param in $sw_name)
{$ndx++
$s = $sw_type[$ndx]
if ($len -le $param.Length) # if len(input option) <= arg name
{if ($opt -eq $param.Substring(0,$len))
{if ($optnbr -ge 0)
{$s = $sw_name[$optnbr]
Write-Host "*ERROR* Ambiguous option for $opt ($param and $s)"
exit 1
}
$optnbr = $ndx
}
}
}
if ($optnbr -lt 0)
{Write-Host "*ERROR* Unknown option: $opt"
exit 1
}
else
{$param = $sw_name[$optnbr].Replace("-","$")
if ($sw_data[$optnbr] -ne "") # get the value for switch
{if ($sw_type[$optnbr] -eq "") # if no data type, assume string
{$value = "`"" + $sw_data[$optnbr] + "`"" }
else
{if ($sw_type[$optnbr] -eq "[int]") # if data has to be an integer
{$value = $sw_data[$optnbr ]
$var = $value -as [int] # convert to type 'int'
if ($var -isnot [int]) # if not a valid number ...
{$param = $sw_name[$optnbr]
Write-Host "*ERROR* Invalid numeric input for: $param, value=$value"
exit 1
}
}
elseif ($sw_type[$optnbr] -eq "[bool]")
{$value = $sw_data[$optnbr] }
else
{$value = "`"" + $sw_data[$optnbr] + "`"" }
}
Invoke-Expression "$param=$value"
}
else # No value specified with switch,
{if ($sw_type[$optnbr] -ne "") # but it has a data type,
{if ($sw_type[$optnbr] -eq "[bool]") # and the type is boolean ...
{Invoke-Expression "$param=`$True" } # then set to TRUE
else
{$optnbr += 1000 } # special flag for switch with a value
}
else
{$optnbr += 1000 } # special flag for switch with a value
}
}
} ###########################
else # GET REQUIRED PARAMETERS #
{ ###########################
$numreq++ # one more required parm (maybe)
if ($numreq -lt $maxreq) # too many ?
{$s = $rparms[$numreq]
Invoke-Expression "$s=`"$opt`"" # no, pick up value, assign it
} ###########################
else # GET OPTIONAL PARAMETERS #
{$numopt++ ###########################
if ($numopt -ge $maxopt) # unless too many
{Write-Host "*ERROR* Too many parameters were provided."
display_usage
exit 1
}
else
{$s = $oparms[$numopt]
Invoke-Expression "$s=`"$opt`"" # no, pick up value, assign it
}
}
}
}
}
if ($optnbr -ge 1000) # if option nbr > 999
{$optnbr -= 1000 # then subtract 1000 (orig opt nbr)
$opt = $sw_name[$optnbr] # and get the original switch
Write-Host "*ERROR* No value was provided with option $opt"
exit 1
}
$numreq++
if ($numreq -lt $maxreq)
{Write-Host "*ERROR* Not enough required parameters provided."
display_usage
exit 1
}
}
_______________________________________________________________________________________________________________
Appendix B - Text of the Cvt_Str2Nbr function
##########################################################################
# Purpose: To check an input field to see if it is a valid number with- #
# out having a PowerShell error being displayed. Use when #
# checking for a valid positive number in a string field (such #
# as user input) and needing it converted to an [int] field. #
# Input : $instring = A character string that may be numeric. #
# Output : $outnumber = Either a valid number in a [int] field or -1 if #
# it is not a valid number. #
##########################################################################
function Cvt_Str2Nbr([string]$instring)
{
$var = "" # variable with undeclared type
[int] $outnumber = -1 # output number to return: -1 or value
#
if ($instring -notmatch "\s") # if there is no whitespace ...
{$var = $instring -as [int] # convert to type 'int'
if ($var -is [int]) # if a valid number ...
{$outnumber = $var } # then use the numeric value
}
return $outnumber # otherwise return -1
}
_______________________________________________________________________________________________________________
Appendix C - Text of the Get_GUI_DropDown function
##########################################################################
# Purpose: Generic routine to display a drop-down menu and return the #
# choice that was clicked using the mouse. #
# Input : $instring = A comma-separated list to be displayed in the #
# drop-down menu. #
# $item = The name of the entity to be chosen. #
# Returns: The value that was selected. #
##########################################################################
function Get_GUI_DropDown([string]$instring,[string]$item="Value")
{
[int] $i = 0
[string] $return_val = ""
[string[]] $inp_array = $instring.Split(",")
if (!$instring)
{Write-Host "No input for DropDown ... exiting"
exit 1
}
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "$item Selection"
$Form.Size = New-Object System.Drawing.Size(450,400)
$Form.StartPosition = "CenterScreen"
#
$Form.KeyPreview = $True
#
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(30,310)
$OKButton.Size = New-Object System.Drawing.Size(100,30)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$Form.AcceptButton = $OKButton
#
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(200,310)
$CancelButton.Size = New-Object System.Drawing.Size(100,30)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$Form.CancelButton = $CancelButton
#
$Label = New-Object System.Windows.Forms.Label
$Label.Location = New-Object System.Drawing.Size(20,20)
$Label.Size = New-Object System.Drawing.Size(260,20)
$Label.Text = "Please select a $item :"
#
$ListBox = New-Object System.Windows.Forms.ListBox
$ListBox.Location = New-Object System.Drawing.Size(20,50)
$ListBox.Size = New-Object System.Drawing.Size(360,20)
$ListBox.Height = 240
#
for ($i=0; $i -lt $inp_array.Count; $i++)
{[void] $ListBox.Items.Add($inp_array[$i]) }
#
$Form.Controls.AddRange(@($OKButton,$CancelButton,$Label,$ListBox))
$Form.Topmost = $True
#
if ($Form.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{$return_val = $ListBox.SelectedItem }
$Form.Dispose()
return $return_val # Return selected value
}
Appendix D - Text of the Get_GUI_Date function
##########################################################################
# Purpose: Generic routine to display a calendar from which the user can #
# choose the date that they desire. #
# Input : $title = A string that is displayed in the calendar after the #
# word "Select ". #
# Returns: The date that was chosen or '01/01/1900' if the "CANCEL" #
# button was chosen. #
##########################################################################
function Get_GUI_Date([string]$title="Select a Date")
{
[datetime] $date = "01/01/1900"
#
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#
$Form = New-Object Windows.Forms.Form
#
$Form.Text = $title
$Form.Size = New-Object Drawing.Size @(243,230)
$Form.StartPosition = "CenterScreen"
#
$Calendar = New-Object System.Windows.Forms.MonthCalendar
$Calendar.ShowTodayCircle = $False
$Calendar.MaxSelectionCount = 1
$Form.Controls.Add($Calendar)
#
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(38,165)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$Form.AcceptButton = $OKButton
$Form.Controls.Add($OKButton)
#
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(113,165)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$Form.CancelButton = $CancelButton
$Form.Controls.Add($CancelButton)
#
$Form.Topmost = $True
#
if ($Form.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{$date = $Calendar.SelectionStart }
$Form.Dispose()
return $date
}
Appendix E - Text of the Get_GUI_CheckBox function
#####################################################################
# Purpose: To display a series of checkboxes along with initial #
# values for each. #
# Input : $optname = Array of strings which will be displayed as #
# the name of each option. #
# $optlst = Comma-separated list of indexes for the #
# options which are to be initialized to TRUE. #
# The indexes of the options start with zero. #
# Example: "0,10" -> all options will be set to #
# $False except $optname[0] and $optname[10]. #
# $title = The main title of the checkbox window. #
# The default is "Choose Selections" #
# $width = The width to set the checkbox window, #
# specified in pixels. The default is 450. #
# Returns: A string that that contains a comma-separated list of #
# the numbers of the options that were selected. The #
# first option is numbered zero. The list is the same #
# format as the $optlst input parameter. #
#####################################################################
function Get_GUI_CheckBox([string[]]$optname,[string]$optlst,[string]$title="Choose Selections",[int]$max_width=450)
{
[string] $result = "" # result string returned
[string] $comma = "" # do not start $result with a comma
[string] $str = "" # temp string
[int] $inbr = $optname.Count # nbr of input lines (checkboxes)
[int] $max_height = ($inbr * 20) + 100 # maximum window height
[int] $btnpos = ($inbr * 20) + 21 # button (OK and CANCEL) positions
[string[]] $a = @() # temp array
[hashtable] $init_true = @{} # hash table of TRUE initial values
#
if ($inbr -gt 28) # if the array has too many values
{Write-Host "*ERROR* The number of array entries ($inbr) is greater than the max allowed (28)"
exit 1
}
$a = $optlst.Split(",") # make an array out of the list of indexes
foreach ($str in $a)
{$init_true[$str] = 1 } # set each entry to 1
#
Add-Type -AssemblyName System.Windows.Forms
#
# create FORM
$Form = New-Object system.Windows.Forms.Form
$Form.text = $title
$Form.height = $max_height
$Form.width = $max_width
$Form.formborderstyle = 3
#
# create OK button
$OKButton = New-Object system.Windows.Forms.Button
$OKButton.text = "OK"
$OKButton.height = 25
$OKButton.width = 75
$OKButton.top = $btnpos
$OKButton.left = 15
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$Form.AcceptButton = $OKButton
$Form.Controls.add($OKButton)
#
# create Cancel button
$CancelButton = New-Object system.Windows.Forms.Button
$CancelButton.text = "Cancel"
$CancelButton.height = 25
$CancelButton.width = 75
$CancelButton.top = $btnpos
$CancelButton.left = 105
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$Form.CancelButton = $CancelButton
$Form.Controls.add($CancelButton)
#
# Create check box 0
$check0 = New-Object system.Windows.Forms.CheckBox
$check0.width = 500
$check0.Text = $($optname[0])
$check0.Top = 10
$check0.Left = 15
if ($init_true.ContainsKey("0")) {$check0.Checked = $True }
else {$check0.Checked = $False }
#
$Form.Controls.add($check0)
#
if ($inbr -gt 1)
{# Create check box 1
$check1 = New-Object system.Windows.Forms.CheckBox
$check1.width = 500
$check1.Text = $($optname[1])
$check1.Top = 30
$check1.Left = 15
if ($init_true.ContainsKey("1")) {$check1.Checked = $True }
else {$check1.Checked = $False }
#
$Form.Controls.add($check1)
}
if ($inbr -gt 2)
{# Create check box 2
$check2 = New-Object system.Windows.Forms.CheckBox
$check2.width = 500
$check2.Text = $($optname[2])
$check2.Top = 50
$check2.Left = 15
if ($init_true.ContainsKey("2")) {$check2.Checked = $True }
else {$check2.Checked = $False }
#
$Form.Controls.add($check2)
}
if ($inbr -gt 3)
{# Create check box 3
$check3 = New-Object system.Windows.Forms.CheckBox
$check3.width = 500
$check3.Text = $($optname[3])
$check3.Top = 70
$check3.Left = 15
if ($init_true.ContainsKey("3")) {$check3.Checked = $True }
else {$check3.Checked = $False }
#
$Form.Controls.add($check3)
}
if ($inbr -gt 4)
{# Create check box 4
$check4 = New-Object system.Windows.Forms.CheckBox
$check4.width = 500
$check4.Text = $($optname[4])
$check4.Top = 90
$check4.Left = 15
if ($init_true.ContainsKey("4")) {$check4.Checked = $True }
else {$check4.Checked = $False }
#
$Form.Controls.add($check4)
}
if ($inbr -gt 5)
{# Create check box 5
$check5 = New-Object system.Windows.Forms.CheckBox
$check5.width = 500
$check5.Text = $($optname[5])
$check5.Top = 110
$check5.Left = 15
if ($init_true.ContainsKey("5")) {$check5.Checked = $True }
else {$check5.Checked = $False }
#
$Form.Controls.add($check5)
}
if ($inbr -gt 6)
{# Create check box 6
$check6 = New-Object system.Windows.Forms.CheckBox
$check6.width = 500
$check6.Text = $($optname[6])
$check6.Top = 130
$check6.Left = 15
if ($init_true.ContainsKey("6")) {$check6.Checked = $True }
else {$check6.Checked = $False }
#
$Form.Controls.add($check6)
}
if ($inbr -gt 7)
{# Create check box 7
$check7 = New-Object system.Windows.Forms.CheckBox
$check7.width = 500
$check7.Text = $($optname[7])
$check7.Top = 150
$check7.Left = 15
if ($init_true.ContainsKey("7")) {$check7.Checked = $True }
else {$check7.Checked = $False }
#
$Form.Controls.add($check7)
}
if ($inbr -gt 8)
{# Create check box 8
$check8 = New-Object system.Windows.Forms.CheckBox
$check8.width = 500
$check8.Text = $($optname[8])
$check8.Top = 170
$check8.Left = 15
if ($init_true.ContainsKey("8")) {$check8.Checked = $True }
else {$check8.Checked = $False }
#
$Form.Controls.add($check8)
}
if ($inbr -gt 9)
{# Create check box 9
$check9 = New-Object system.Windows.Forms.CheckBox
$check9.width = 500
$check9.Text = $($optname[9])
$check9.Top = 190
$check9.Left = 15
if ($init_true.ContainsKey("9")) {$check9.Checked = $True }
else {$check9.Checked = $False }
#
$Form.Controls.add($check9)
}
if ($inbr -gt 10)
{# Create check box 10
$check10 = New-Object system.Windows.Forms.CheckBox
$check10.width = 500
$check10.Text = $($optname[10])
$check10.Top = 210
$check10.Left = 15
if ($init_true.ContainsKey("10")) {$check10.Checked = $True }
else {$check10.Checked = $False }
#
$Form.Controls.add($check10)
}
if ($inbr -gt 11)
{# Create check box 11
$check11 = New-Object system.Windows.Forms.CheckBox
$check11.width = 500
$check11.Text = $($optname[11])
$check11.Top = 230
$check11.Left = 15
if ($init_true.ContainsKey("11")) {$check11.Checked = $True }
else {$check11.Checked = $False }
#
$Form.Controls.add($check11)
}
if ($inbr -gt 12)
{# Create check box 12
$check12 = New-Object system.Windows.Forms.CheckBox
$check12.width = 500
$check12.Text = $($optname[12])
$check12.Top = 250
$check12.Left = 15
if ($init_true.ContainsKey("12")) {$check12.Checked = $True }
else {$check12.Checked = $False }
#
$Form.Controls.add($check12)
}
if ($inbr -gt 13)
{# Create check box 13
$check13 = New-Object system.Windows.Forms.CheckBox
$check13.width = 500
$check13.Text = $($optname[13])
$check13.Top = 270
$check13.Left = 15
if ($init_true.ContainsKey("13")) {$check13.Checked = $True }
else {$check13.Checked = $False }
#
$Form.Controls.add($check13)
}
if ($inbr -gt 14)
{# Create check box 14
$check14 = New-Object system.Windows.Forms.CheckBox
$check14.width = 500
$check14.Text = $($optname[14])
$check14.Top = 290
$check14.Left = 15
if ($init_true.ContainsKey("14")) {$check14.Checked = $True }
else {$check14.Checked = $False }
#
$Form.Controls.add($check14)
}
if ($inbr -gt 15)
{# Create check box 15
$check15 = New-Object system.Windows.Forms.CheckBox
$check15.width = 500
$check15.Text = $($optname[15])
$check15.Top = 310
$check15.Left = 15
if ($init_true.ContainsKey("15")) {$check15.Checked = $True }
else {$check15.Checked = $False }
#
$Form.Controls.add($check15)
}
if ($inbr -gt 16)
{# Create check box 16
$check16 = New-Object system.Windows.Forms.CheckBox
$check16.width = 500
$check16.Text = $($optname[16])
$check16.Top = 330
$check16.Left = 15
if ($init_true.ContainsKey("16")) {$check16.Checked = $True }
else {$check16.Checked = $False }
#
$Form.Controls.add($check16)
}
if ($inbr -gt 17)
{# Create check box 17
$check17 = New-Object system.Windows.Forms.CheckBox
$check17.width = 500
$check17.Text = $($optname[17])
$check17.Top = 350
$check17.Left = 15
if ($init_true.ContainsKey("17")) {$check17.Checked = $True }
else {$check17.Checked = $False }
#
$Form.Controls.add($check17)
}
if ($inbr -gt 18)
{# Create check box 18
$check18 = New-Object system.Windows.Forms.CheckBox
$check18.width = 500
$check18.Text = $($optname[18])
$check18.Top = 370
$check18.Left = 15
if ($init_true.ContainsKey("18")) {$check18.Checked = $True }
else {$check18.Checked = $False }
#
$Form.Controls.add($check18)
}
if ($inbr -gt 19)
{# Create check box 19
$check19 = New-Object system.Windows.Forms.CheckBox
$check19.width = 500
$check19.Text = $($optname[19])
$check19.Top = 390
$check19.Left = 15
if ($init_true.ContainsKey("19")) {$check19.Checked = $True }
else {$check19.Checked = $False }
#
$Form.Controls.add($check19)
}
if ($inbr -gt 20)
{# Create check box 20
$check20 = New-Object system.Windows.Forms.CheckBox
$check20.width = 500
$check20.Text = $($optname[20])
$check20.Top = 410
$check20.Left = 15
if ($init_true.ContainsKey("20")) {$check20.Checked = $True }
else {$check20.Checked = $False }
#
$Form.Controls.add($check20)
}
if ($inbr -gt 21)
{# Create check box 21
$check21 = New-Object system.Windows.Forms.CheckBox
$check21.width = 500
$check21.Text = $($optname[21])
$check21.Top = 430
$check21.Left = 15
if ($init_true.ContainsKey("21")) {$check21.Checked = $True }
else {$check21.Checked = $False }
#
$Form.Controls.add($check21)
}
if ($inbr -gt 22)
{# Create check box 22
$check22 = New-Object system.Windows.Forms.CheckBox
$check22.width = 500
$check22.Text = $($optname[22])
$check22.Top = 450
$check22.Left = 15
if ($init_true.ContainsKey("22")) {$check22.Checked = $True }
else {$check22.Checked = $False }
#
$Form.Controls.add($check22)
}
if ($inbr -gt 23)
{# Create check box 23
$check23 = New-Object system.Windows.Forms.CheckBox
$check23.width = 500
$check23.Text = $($optname[23])
$check23.Top = 470
$check23.Left = 15
if ($init_true.ContainsKey("23")) {$check23.Checked = $True }
else {$check23.Checked = $False }
#
$Form.Controls.add($check23)
}
if ($inbr -gt 24)
{# Create check box 24
$check24 = New-Object system.Windows.Forms.CheckBox
$check24.width = 500
$check24.Text = $($optname[24])
$check24.Top = 490
$check24.Left = 15
if ($init_true.ContainsKey("24")) {$check24.Checked = $True }
else {$check24.Checked = $False }
#
$Form.Controls.add($check24)
}
if ($inbr -gt 25)
{# Create check box 25
$check25 = New-Object system.Windows.Forms.CheckBox
$check25.width = 500
$check25.Text = $($optname[25])
$check25.Top = 510
$check25.Left = 15
if ($init_true.ContainsKey("25")) {$check25.Checked = $True }
else {$check25.Checked = $False }
#
$Form.Controls.add($check25)
}
if ($inbr -gt 26)
{# Create check box 26
$check26 = New-Object system.Windows.Forms.CheckBox
$check26.width = 500
$check26.Text = $($optname[26])
$check26.Top = 530
$check26.Left = 15
if ($init_true.ContainsKey("26")) {$check26.Checked = $True }
else {$check26.Checked = $False }
#
$Form.Controls.add($check26)
}
if ($inbr -gt 27)
{# Create check box 27
$check27 = New-Object system.Windows.Forms.CheckBox
$check27.width = 500
$check27.Text = $($optname[27])
$check27.Top = 550
$check27.Left = 15
if ($init_true.ContainsKey("27")) {$check27.Checked = $True }
else {$check27.Checked = $False }
#
$Form.Controls.add($check27)
}
#
# show FORM
if ($Form.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{##########################################################
# OK Button was clicked: Get results of what was checked #
##########################################################
if ($check0.Checked) {$result += $comma + "0" ; $comma = "," }
if ($check1.Checked) {$result += $comma + "1" ; $comma = "," }
if ($check2.Checked) {$result += $comma + "2" ; $comma = "," }
if ($check3.Checked) {$result += $comma + "3" ; $comma = "," }
if ($check4.Checked) {$result += $comma + "4" ; $comma = "," }
if ($check5.Checked) {$result += $comma + "5" ; $comma = "," }
if ($check6.Checked) {$result += $comma + "6" ; $comma = "," }
if ($check7.Checked) {$result += $comma + "7" ; $comma = "," }
if ($check8.Checked) {$result += $comma + "8" ; $comma = "," }
if ($check9.Checked) {$result += $comma + "9" ; $comma = "," }
if ($check10.Checked) {$result += $comma + "10" ; $comma = "," }
if ($check11.Checked) {$result += $comma + "11" ; $comma = "," }
if ($check12.Checked) {$result += $comma + "12" ; $comma = "," }
if ($check13.Checked) {$result += $comma + "13" ; $comma = "," }
if ($check14.Checked) {$result += $comma + "14" ; $comma = "," }
if ($check15.Checked) {$result += $comma + "15" ; $comma = "," }
if ($check16.Checked) {$result += $comma + "16" ; $comma = "," }
if ($check17.Checked) {$result += $comma + "17" ; $comma = "," }
if ($check18.Checked) {$result += $comma + "18" ; $comma = "," }
if ($check19.Checked) {$result += $comma + "19" ; $comma = "," }
if ($check20.Checked) {$result += $comma + "20" ; $comma = "," }
if ($check21.Checked) {$result += $comma + "21" ; $comma = "," }
if ($check22.Checked) {$result += $comma + "22" ; $comma = "," }
if ($check23.Checked) {$result += $comma + "23" ; $comma = "," }
if ($check24.Checked) {$result += $comma + "24" ; $comma = "," }
if ($check25.Checked) {$result += $comma + "25" ; $comma = "," }
if ($check26.Checked) {$result += $comma + "26" ; $comma = "," }
if ($check27.Checked) {$result += $comma + "27" ; $comma = "," }
}
else #################################################################
{$result = "*" } # Otherwise return '*' to indicate that selection was cancelled #
$Form.Dispose() #################################################################
return $result
}
######################################################################################################
# # # #
# # ''~`` # #
# # ( o o ) # ____________ #
# __________________ # +--oooO--(_)--Oooo-----------+ # ( ) #
# / \ # | | # ( Don't Have ) #
# ( Look, a dragonfly! ) # | | # ( A Cow, Man ) #
# \__________________/ # | T h e E n d . | # (____________) #
# o # | | # O #
# o # | | # O ^__^ #
# o @..@ # | oooO | # o (oo)\_______ #
# (----) # | ( ) Oooo | # (__)\ )\/\ #
# ( )--( ) # +---\ (-----( )------------+ # ||----w | #
# o0..0o # \_) ) / # || || #
# # (_/ # #
# # # #
######################################################################################################
# 07-Aug-2021
@IrgendwasMitSchnittlauch

Just read the first 3 Points, but looks insane

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment