在PowerShell中将变量传递到语句块括号中

时间:2015-04-28 20:00:32

标签: powershell powershell-v3.0 powershell-v4.0

我有一个数组,我想传递给一个变量,然后传递给$project_id

如下所示:

$task_token

我在上面注意到{}$action变量在我将脚本块分配给void save() { BinaryFormatter bf = new BinaryFormatter (); FileStream file = File.Open(Application.persistentDataPath + "/MyData.dat",FileMode.Append); MyData data = new MyData (); data.s = input.text; input.text=""; bf.Serialize (file, data); file.Close (); } 时置于public void load() { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath+"/MyData.dat",FileMode.Open); MyData data = (MyData)bf.Deserialize(file); file.Close(); name = data.s; //returns only one string } [Serializable] class MyData { public string s; } 之间时会丢失。

如何在此处保留变量?

1 个答案:

答案 0 :(得分:1)

由于至少有两个原因,您的代码不应该以您编写代码的方式工作。

首先:我不确定这个,但是当你写的时候:

$body = @{
    project_id = $project_id
    task_token = $task_token
}

$body是一个哈希表,所以你确定它会为-body参数构成一个好的值吗?

第二:动作脚本块将在另一个作业中执行,因此$body变量将不会在{{3}中写入的动作块范围内可用} documentation:" Action参数的值可以包括$ Event,$ EventSubscriber,$ Sender,$ EventArgs和$ Args自动变量,它们向Action脚本块提供有关事件的信息。有关详细信息,请参阅about_Automatic_Variables。"。

因此,在您的情况下,如果您想要指定与此活动订阅相关联的其他数据,您可以通过这种方式使用-MessageData参数(此处我不会照顾第一个< / strong>评论):

$action = {Invoke-RestMethod -Uri http://localhost/temp.php -Method Post -Body $($event.MessageData)"}
Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier MyTimer -Action $action -MessageData $body