· 4 years ago · Jun 25, 2021, 09:48 PM
1get-variable
2
3# This will get the members of the Object that is returned from Get-Variable.
4# The Object resulting from the call (Get-Variable -Name PSVersionTable) is passed as an argument to the parameter InputObject.
5#The parenthesis sets the priority for it to be executed first.
6Get-Member -InputObject (Get-Variable -Name PSVersionTable)
7
8<# Now you will look at ways to create variable objects implicitly and explicitly.
9The PowerShell language parser simply parses text and creates objects based on syntax and context.
10When the parser encounters a dollar-sign (\$) it will see the text following as the name of a variable (\$)
11and checks does a variable already exists with that name, else will implicitly create one.
12If there is an assignment operator after the variable, PowerShell will assign the object
13(i.e. operand to the right of =) to the value property of the variable.
14Create a variable using the $\ = syntax called OneThousand that references the numeric object 1000.
15#>
16$OneThousand = 1000
17
18# The value property references an object
19Get-Member -InputObject (Get-Variable -Name OneThousand).Value
20
21# Alternative calling the GetType method on the Value (i.e. Object) property
22(Get-Variable -Name OneThousand).Value.GetType()
23
24<# The last tasks implicitly created a variable and assigned values to both the name and value properties of the variable object.
25This was done magically by the PowerShell engine and parser.
26Now you will more explicitly create a variable and assign it with a name and a value.
27What command can you use to create a new variable with the name TwoTrillion and the value 2000000000000?#>
28
29# The value property references an object
30New-Variable -Name TwoTrillion -Value 2000000000000
31
32<#
33The type of the object that was created when no explicit object
34type is specified in the PowerShell script will be determined implicitly by the PowerShell language parser.
35Notice how the types of the objects referenced by the variables are different for OneThousand and TwoTrillion.
36#>
37
38#When using the GetType method on the object you get back object of type type.
39#A type object has other interesting properties which we will review later.
40
41
42#Now delete the variable OneThousand. How can you accomplish that? What command or commands can you use
43# Remove Variable is the most obvious one to use
44Remove-Variable -Name OneThousand
45
46# If you are familiar with PowerShell Providers you can also access the Variable via its path and remove using Remove-Item cmdlet
47Remove-Item -Path Variable:\OneThousand
48
49$Number = 1TB
50
51<# The syntax for a type is square-brackets [] with Type Name inside eg. [System.String].
52They type often needs to be prefixed with a namespace. There are however so-called Accelerators (i.e. aliases for types)
53as well as a new Keyword Namespace in PowerShell 5.x which allow only you to specify the typename.#>
54
55[System.Int32]$Number = 1
56
57<# Important rule! The operand's type on the LEFT of the operator determines how the operation will be performed.
58It is the type that implements different kinds of operators.
59Mostly the operand on the RIGHT will be converted to the same type as the operand on the LEFT before the operation is performed.
60Beware this is the most common case however there are exceptions to the rule.
61In the task above, the operand on the LEFT was a variable with a type Int32.
62The assignment operator will cause PowerShell to attempt to convert the operand on the RIGHT to type Int32.
63Important! Conversion occurs by taking the propery values from the object and using it to create a new object of a different type.
64Generally these type conversions are implicitly performed by PowerShell where needed based on the rule above.
65Be aware, the object you see on the screen in the console may look like the object you expect it to be but it might actually be of an entirely different type.
66Use Get-Member and the method GetType() frequently when writing and testing scripts to ensure you are operating with the correct types.
67#>
68
69function Get-DayOfWeek
70{
71 param
72 (
73 [System.DateTime]$DateTime = (Get-Date)
74 )$DateTime.DayOfWeek
75}
76
77Get-DayOfWeek
78Get-Command Get-DayOfWeek -Syntax
79
80#Look at the command syntax of the newly defined function by calling Get-Command Get-DayOfWeek -Syntax. Fill in the table accordingly
81Get-DayOfWeek -DateTime (Get-Date) # Conversion Occurs? Answer False - Today's date - The Object passed in as a argument is of type DateTime
82
83Get-DayOfWeek # Conversion Occurs? False - Today's day - Using default value which is a DateTime object returned from call to Get-Date
84
85(Get-date '24 Dec 2020').dayofweek # Conversion Occurs? True - Thursday - The string is parsed and a new DateTime object is created. Note the string must be formatted properly
86
87Get-DayOfWeek '24 Dez 2020' # Conversion Occurs? False - Error - The PowerShell engine attempts to convert the argument of type string to a DateTime however fails because the string is not properly formatted for the current culture which is en-us
88
89<# PowerShell scripts or commands are simply text which is initially parsed and broken into words known as tokens.
90Each Token has a type and will result in a quasi first type conversion where the text turns into Token objects.
91Objects of type variable, Command, string, number, etc are hence being implicitly created through this parsing. #>
92
93
94#Look at the command Get-Member. How can we use this to get the static members of the type (Class) DateTime?
95
96# Notice using the Parenthesis around [DateTime] shows that the argument is a *type*
97Get-Member -InputObject ([DateTime]) -Static
98
99# Notice the difference in color syntax on how PowerShell parses the below argument for
100# the parameter InputObject. The default is to create a String object
101Get-Member -InputObject [DateTime] -Static
102
103# Alternatively passing the argument for -InputObject via the pipeline.
104# More on this in the Pipeline module.
105[DateTime] | Get-Member -Static
106
107#Using the DateTime type identify the member that needs to be used in order to mimic the result to the command Get-Date (without arguments).
108#Accessing static members is done using the following Syntax [< type >] :: \< member >.
109#If the Member is a method then you may be required to pass in arguments (positionally). If it is a property then it will simply return an object.
110
111# This will return a DateTime
112[DateTime]::Now
113
114# Compare to calling Get-Date by executing the right after each other
115# notice the similarity in results.
116Get-Date
117
118#Calling a static method : What argument type needs to be passed and in what order.
119#Using the new static method of the string type,create a string with length 16 containing only 'I's.
120
121#Hint: In order to see the different ways to call a method, as there could be several, simply attempt to invoke the method without parenthesis.
122#The result will show something called OverLoadDefinitions which is analogous to ParameterSets you saw in the Command module.
123# There are several possibilties. Below a few
124[System.String]::New('I',16)
125
126[System.String]::New('IIIIIIIIIIIIIIII')
127
128# Showing that the New-Object Command simply abstracts static method *New* for a type (class)
129New-Object -TypeName System.String -ArgumentList 'I',16
130
131# Here we can also allow the Parser to implicitly create the String Object
132# as when it see's quotation marks is does this
133'IIIIIIIIIIIIIIII'
134
135# The String type also supports a Times operator
136'IIII' * 4
137
138# Exploring the string's static Format method. This method has also been abstracted into the PowerShell operator -f.
139# How would you call the Format method in order to get the same result on console pane as the following PowerShell command line does?
140'New Years eve is on a {0:dddd} this year' -f (Get-Date -Month 12 -day 31)
141
142# All in one line
143[System.String]::Format('New Years eve is on a {0:dddd} this year',(Get-Date -Month 12 -day 31) )
144
145# Breaking it down using variables as arguments and using the String accelerator (Alias)
146$format = 'New Years eve is on a {0:dddd} this year'
147$arg0 = (Get-Date -Month 12 -day 31)
148[String]::Format($formatstring,$arg0)
149
150<# Enumerator types are types that are collections of strings with corresponding numeric values.
151These types are used all over as they make it possible to either pass a string as a argument or a numeric value.
152The numeric values are much harder to remember therefore these types are very useful also for legibility.
153Execute the following PowerShell code in order to define a helper command with which to further explore Enumerator types.#>
154
155function Show-Enum
156{
157 param
158 (
159 [System.Type]$Type
160 )if($Type.BaseType.Name -eq 'Enum')
161{
162 $FormatString = '{0,-32} {1,8} {2,32}'
163 "Enum Type: $($Type.Fullname)`n"
164 [System.String]::Format($FormatString ,'String','Decimal','Binary')
165 '-' * (32+1+8+1+32)
166 [System.Enum]::GetValues($Type) |
167 ForEach-Object {
168 [System.String]::Format($FormatString ,$_,$_.value__,([System.Convert]::ToString($_.value__,2)))
169 }
170}
171else
172{
173 Write-Warning "$($Enum.Fullname) is not a Enumerator type."
174}
175}
176
177Show-Enum -Type ([System.Management.Automation.ActionPreference])
178Show-Enum -Type ([System.IO.FileAttributes])
179Show-Enum -Type ([System.ConsoleColor])
180Show-Enum -Type ([System.IO.FileAccess])
181Show-Enum -Type ([System.IO.Directory])
182Show-Enum -Type ([System.DayOfWeek])
183
184#The numeric value associated with the string in an enumerator can be accessed via the property value__ (Two underscores)
185
186# Syntax
187# [<NameSpace>.<TypeName>]<Object>
188
189$FormatString = 'There are {0} {1} Apples on the {2}.'
190$Args = @([System.Management.AuthenticationLevel]::Call.value__,[ConsoleColor]12,'Table')
191[System.String]::Format($FormatString,$Args)
192
193Write-Host "Guess what color I will be" -ForegroundColor 14 -BackgroundColor ([ConsoleColor]::Red)
194
195# An Example casting a String to a CultureInfo Object
196[System.Globalization.CultureInfo]'De-De'
197
198
199# Create a string that represents a IPv4 address and cast it to a system.net.IPAddress object. What is the IPv6 representation.
200# Example using a variable to store new Object
201$IPAddress = [System.Net.IPAddress]'192.168.0.10'
202
203# Get-Member -InputObject $IPAddress will help find the method to convert
204$IPAddress.MapToIPv6().IPAddressToString
205
206#How would you use the -as operator to accomplish the same thing you did in the previous task?
207# Use the -As operator by having the Left operand use to create an object of Right operand's type
208('192.168.0.10' -as [System.Net.IPAddress]).MapToIPv6().IPAddressToString
209
210#You can check if an object is of a specific type using the -is operator.
211#Guess what type of object the variable ConfirmPreference is?
212
213#How can you check what value it is and what type the value is? Once you find out the type how can you check that it is that type using the -is operator.
214#Hint
215Get-Help about_Type_Operators
216
217# Look at the ConfirmPreference Object
218$ConfirmPreference
219
220# Get the type
221$ConfirmPreference.Gettype()
222
223# Confirm that is of that type
224$ConfirmPreference -is [System.Management.Automation.ConfirmImpact]
225
226# what do you think? Could it be an enumerator type - Check
227[System.Management.Automation.ConfirmImpact].IsEnum
228
229