这是我遇到问题的代码部分:
function getGroup {
$Script:confirmdggroup = "N"
$Script:dggroup = "none"
$dggroup = Read-Host -Prompt 'Enter the name of the group to add a member'
write-host "You entered $dggroup"
$confirmdggroup = Read-Host -Prompt 'If the group name is correct enter Y'
write-host "You entered $confirmdggroup when asked to confirm group name"
}
If ($confirmdggroup -ne "Y") {getGroup}
write-host "Group name to be modified is $dggroup"
write-host "the confirmdggroup variable is: $confirmdggroup"
下面是我运行该程序时的输入和输出图像。您可以看到函数内部的变量已正确分配,但外部没有。我做错了什么?
好的,我正在尝试重写而不使用“Script:”,但我无法让函数返回任何内容。这是新函数:
function getGroup {
while($confirmDGGroup -ne "Y")
{
$DGGroup = Read-Host -Prompt 'Enter the name of the Exchange group to modify'
""
write-host "You entered $DGGroup"
""
$confirmDGGroup = Read-Host -Prompt 'If the group name is correct enter Y'
}
}
cls
write-host "This script will add or remove email addresses from an Exchange Distibution Group"
""
$GroupName = getGroup
write-host "The get group function returned $GroupName"
pause
下面是我现在得到的输出:
此脚本将从 Exchange 分发组中添加或删除电子邮件地址 输入要修改的Exchange组的名称:office 你进入办公室 如果组名正确,请输入 Y: Y 获取组函数返回 按 Enter 继续...:
答案1
这是一个获取用户输入、询问是否正确、如果不正确则重复,最后将文本发送给调用者的函数。
function Get-ExchangeGroupName
{
$Prompt = 'Please enter the Group name '
$Choice = ''
while ($Choice -eq '')
{
$Choice = Read-Host $Prompt
Write-Host ('You entered [ {0} ].' -f $Choice)
$YesNo = Read-Host ' Is that correct? [n/y]'
if ($YesNo -eq 'y')
{
# send the result out to the caller
$Choice
}
else
{
$Choice = ''
}
}
} # function Get-ExchangeGroupName
$ChosenGroupName = Get-ExchangeGroupName
''
$ChosenGroupName
输出带有n
& 的y
对“那正确吗?”的响应...
Please enter the Group name : qwerty
You entered [ qwerty ].
Is that correct? [n/y]: n
Please enter the Group name : AlfaBravo
You entered [ AlfaBravo ].
Is that correct? [n/y]: y
AlfaBravo
答案2
搞清楚了。我忘了在函数要求输入的行前面添加 $Script:。以下是更正后的代码:
function getGroup {
$Script:dggroup = Read-Host -Prompt 'Enter the name of the group to add a member'
write-host "You entered $dggroup"
$Script:confirmdggroup = Read-Host -Prompt 'If the group name is correct enter Y'
write-host "You entered $confirmdggroup when asked to confirm group name"
}
If ($confirmdggroup -ne "Y") {getGroup}
write-host "Group name to be modified is $dggroup"
write-host "the confirmdggroup variable is: $confirmdggroup"