Converting VBScript's Weekday Function
Definition: Returns a whole number representing the day of the week.
You know, you’re right: if you want to return an integer value representing a day of the week (say, getting back a 6 as opposed to getting back Friday), well, that’s really none of our business, is it? To tell you the truth, we don’t know of any way built into Windows PowerShell to do this; however, you can do this by using the .NET Framework’s Microsoft.VisualBasic.DateAndTime class and the DatePart function. The following three commands assign the current date and time to the variable $a, load the Microsoft.VisualBasic assembly, then use the DatePart function to return an integer representing the day of the week. Note that DatePart requires two parameters:
w, which tells the function we want the day of the week.
$a, the date we want to check.
Here are the commands:
$a = get-date [reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic") [Microsoft.VisualBasic.DateAndTime]::DatePart("w",$a)
Or, if you’re really gung-ho on this, here’s another approach:
The Get-Date Cmdlet returns a System.DateTime object that has a DayOfWeek property. This property is an enumeration (a sequence of numbers that each represent something) with 0 representing Sunday, 1 representing Monday, and so on. If you type (Get-Date).DayOfWeek, you will see the text representation of the day. To get at the underlying numeric value you need to type this:
Note: The value is followed by 2 underscores.
Of Course, because the DayOfWeek enumeration starts by numbering Sunday at 0 rather than 1, you need to add 1 at the end of this last command to get the same result as the VBScript function.
(Get-Date).DayOfWeek.Value__ + 1
Assuming you run these commands on a Friday you should get back the following: