Using PowerShell types with commands and variables
Table of contents for Intro to PowerShell
- Getting PowerShell
- Basic PowerShell Concepts
- Commonly Used Cmdlets
- PowerShell Scripts and Profiles
- Using PowerShell types with commands and variables
- Error handling in PowerShell scripts
- Calling static methods
- $NestedPromptLevel
- Prompts in PowerShell
When executing a command in PowerShell that expects a non-string argument, sometimes you need to specify more than just the string representation of the parameter. Here is an example using dates.
PS> 2007-03
2004
PS> [DateTime]"2007-03"
Monday, March 01, 2007 12:00:00 AM
PS> [DateTime]::Parse("2007-03")
Monday, March 01, 2007 12:00:00 AM
You can also set the type of a variable as you assign a value to it:
PS> $x = 2007-03
PS> $x
2004
PS> [DateTime]$x = "2007-03"
PS> $x
Monday, March 01, 2007 12:00:00 AM
Note that when you use the type in front of the value or the variable that you must also specify the value in quotes. That syntax is, in fact, a shortcut for calling the Parse static method on the type to convert a string to that type.
When specifying a date for a cmdlet parameter whose type is DateTime, no such extra work is necessary as PowerShell will automatically call the DateTime.Parse() method on the value.



Loading... 
Leave a Reply