Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass DateTime as a parameter in PowerShell?

I have a script that's calling another script and passing in parameters along with it. Whenever I try to pass in a datetime, parts of the datetime are used as arguments for the other parameters.

script1.ps1

$dateEnd = Get-Date "12/31/14"
$siteUrl = "http://foo.com"
$outputPath = "c:\myFolder"

$argumentList = "-file .\script2.ps1", "test1", $dateEnd, $siteUrl, $outputPath
Start-Process powershell.exe -ArgumentList $argumentList

script2.ps1

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

$test1
$dateEnd
$siteUrl
$outputFile

Read-Host -Prompt "Press Enter to exit"

This would result in:

test1
Wednesday, December 31, 2014 12:00:00 AM
00:00:00
http://foo.com

EDIT - string as date, typo on my part:

If I pass the string 12/31/14 it works fine, but I'd like to be able to pass a date.

like image 854
MickB Avatar asked Dec 12 '22 02:12

MickB


1 Answers

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.

like image 87
Ryan Bemrose Avatar answered Dec 24 '22 06:12

Ryan Bemrose