How do I pass DateTime as a parameter in PowerShell? How do I pass DateTime as a parameter in PowerShell? powershell powershell

How do I pass DateTime as a parameter in PowerShell?


In the line which assigns $argumentList, change the $dateEnd parameter to be $dateEnd.toString('s').

Arguments to Windows processes are strings, and not objects, so Start-Process must convert the ArgumentList into a string. Powershell.exe then parses that string by splitting on spaces (like any Windows process), and it turns it back into your parameters.

Normally, this should work perfectly well, but in this case notice what happens when you run (get-date).tostring(). The default output for a DateTime object contains a space, which is interfering with the parsing.

The solution, then, is to format the date parameter in your argument list to have no spaces and yet still be in a format that DateTime::Parse() can understand (so PowerShell can reload the variable on the other end). Passing 's' to DateTime::toString() gives you such a format.


This is due to a combination of positional parameter usage and quoting. Here's a single change that should make it work (quoted the date input):

$argumentList = "-file D:\script2.ps1", "test1", "`"$dateEnd`"", $siteUrl, $outputPath

Is there any reason you call a separate PowerShell process? You could call this like so:

#This will run in separate scope     & ".\script2.ps1" test1 $dateEnd $siteUrl $outputPath#This will run in the local (current) scope:    . ".\script2.ps1" test1 $dateEnd $siteUrl $outputPath


I think this is an issue of you not using DateTime objects correctly. If you want to specify a date, then do so. What you suggest as your string is a Time, not a date. If you want to specify both then provide both to Get-Date.

$endDate = "12/31/14 08:00:00"

That's 8:00 AM on December 31st.

Then in your script call whatever it is that you want specifically.

param(     [string]$test1,     [DateTime]$dateEnd,     [string]$siteUrl,     [string]$outputFile)      $test1$dateEnd.ToLongDateString()$dateEnd.ToLongTimeString()$siteUrl$outputFile

When a DateTime object is passed to that (shown here with your other test data) you should get:

test1Wednesday, December 31, 20148:00:00 AMhttp://foo.comC:\myfolder