我想创建一个嵌套函数来执行一些处理,并且基于该处理,它可能需要用户输入才能继续。但是,当我尝试运行代码时,它会得到奇怪的输出。
Set-Variable -Name setme -Option AllScope
$setme = "not set"
$nestedfunction = {
Write-Output "inside the function `n"
$setme = Read-Host "Enter Something"
Write-Output "inside the function setme is: $setme `n"
}
Write-Output "Outisde call: $(&$nestedfunction)"
Write-Output "outside it is $setme"
然后,当我运行它时,我得到:
Enter Something: abc
Outisde call: inside the function
inside the function setme is: abc
outside it is not set
无论我如何嵌套函数,它最终都仍然像这样
Set-Variable -Name setme -Option AllScope
$setme = "not set"
$parentfunction = {
Write-Output "In parent `n"
$childfunction = {
Write-Output "inside the function `n"
$setme = Read-Host "Enter Something"
Write-Output "inside the function setme is: $setme `n"
}
Write-Output "Calling child function `n"
&$childfunction
}
Write-Output "Outisde call: $(&$parentfunction)"
Write-Output "outside it is $setme"
Enter Something: abc
Outisde call: In parent
Calling child function
inside the function
inside the function setme is: abc
outside it is not set
最终目标是能够调用子函数,让其处理一些数据,如果数据无效,请要求用户重新输入数据。在我想要设置此脚本的实际脚本中,它甚至不会确认Read-Host调用,但只会绕过它们执行其他所有操作。有人知道我在想什么吗?
非常感谢〜
感谢@Rohin Sidharth的工作:)
答案 0 :(得分:0)
首先,尽管它实际上就像一个函数一样工作,但是您创建的还是一个脚本块。根据您的要求,执行以下操作。
Function Get-UserInput ($message)
{
$Userinput = Read-Host $message
Return $Userinput
}
Function Run-ChildFunction ($input)
{
#Insert processing code here
if ("data is valid. Insert appropriate variables here")
{
Return $true
}
else
{
Return $false
}
}
Function Run-ParentFunction
{
$promptmessage = "Please enter Data"
Do
{
$input = Get-UserInput -message "$promptmessage"
$ChildReturnvalue = Run-ChildFunction -input $input
if (!$ChildReturnvalue)
{
$promptmessage = "Data is invalid. Please check and re-enter"
}
}
While (!$ChildReturnvalue)
}
Run-ParentFunction