如何在PowerShell中将DateTime作为参数传递?

Mic*_*ckB 3 parameters powershell datetime

我有一个脚本,它调用另一个脚本并传入参数.每当我尝试传入日期时间时,日期时间的一部分将用作其他参数的参数.

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
Run Code Online (Sandbox Code Playgroud)

script2.ps1

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

$test1
$dateEnd
$siteUrl
$outputFile

Read-Host -Prompt "Press Enter to exit"
Run Code Online (Sandbox Code Playgroud)

这将导致:

test1
Wednesday, December 31, 2014 12:00:00 AM
00:00:00
http://foo.com
Run Code Online (Sandbox Code Playgroud)

编辑 - 字符串作为日期,我的错字:

如果我通过字符串12/31/14它工作正常,但我希望能够通过日期.

Coo*_*ter 6

这是由于位置参数使用和引用的组合.这是一个应该使其工作的单个更改(引用日期输入):

$argumentList = "-file D:\script2.ps1", "test1", "`"$dateEnd`"", $siteUrl, $outputPath
Run Code Online (Sandbox Code Playgroud)

您是否有任何理由将其称为单独的PowerShell流程?你可以这样称呼它:

#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
Run Code Online (Sandbox Code Playgroud)


Rya*_*ose 6

在分配 $argumentList 的行中,将 $dateEnd 参数更改为$dateEnd.toString('s')

Windows 进程的参数是字符串,而不是对象,因此Start-Process必须将 ArgumentList 转换为字符串。Powershell.exe 然后通过在空格上拆分来解析该字符串(就像任何 Windows 进程一样),并将其转换回您的参数。

通常,这应该工作得很好,但在这种情况下,请注意运行(get-date).tostring(). DateTime 对象的默认输出包含一个空格,这会干扰解析。

然后,解决方案是将参数列表中的日期参数格式化为没有空格,但仍采用 DateTime::Parse() 可以理解的格式(因此 PowerShell 可以在另一端重新加载变量)。传递's'给 DateTime::toString() 为您提供了这样的格式。