选择使用Powershell启用/禁用网络适配器



我正在尝试使用Powershell来选择启用/禁用网络适配器"以太网"我编码了这个

$caption = "Choose Action";
$message = "What do you want to do?";
$enab = start-process powershell -verb runas -argument D:ena.ps1
$disa = start-process powershell -verb runas -argument D:dis.ps1
$choices = [System.Management.Automation.Host.ChoiceDescription[]]($enab,$disa);
$answer = $host.ui.PromptForChoice($caption,$message,$choices,0)
switch ($answer){
0 {"You entered Enable"; break}
1 {"You entered Disable"; break}
}

错误:

对象不能存储在此类型的数组中。在D:\Unttled4.ps1:5字符:1+$choices=System.Management.Automation.Host.ChoiceDescription[];+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+类别信息:OperationStopped:(:)[],InvalidCastException+FullyQualifiedErrorId:System.InvalidCastException

使用"4"个参数调用"PromptForChoice"时发生异常:"Value不能为null。参数名称:choices"At D:\Unttled4.ps1:6 char:1+$answer=$host.ui.PromptForChoice($caption,$message,$choices,0)+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+CategoryInfo:未指定:(:)[],MethodInvocationException+FullyQualifiedErrorId:ArgumentNullException

在此之前,我曾使用powershell执行On/Off脚本失败(如果网络适配器启用,则禁用它,反之亦然。有什么方法可以做到这一点吗?

使用此选项:https://technet.microsoft.com/en-us/library/ff730939.aspx我认为你想做的是:

$caption = "Choose action:"
$message = "What state do you want for the network adapter?"
$enable = New-Object System.Management.Automation.Host.ChoiceDescription "&Enable", `
    "Enables the Network Adapter"
$disable = New-Object System.Management.Automation.Host.ChoiceDescription "&Disable", `
    "Disables the Network Adapter"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($enable, $disable)
$result = $host.ui.PromptForChoice($caption, $message, $options, 0) 
switch ($result)
{
    0 { 
        "You selected Enable." 
        start-process powershell -verb runas -argument D:ena.ps1
    }
    1 {
        "You selected Disable."
        start-process powershell -verb runas -argument D:dis.ps1
    }
}

您所采用的方法不起作用,因为您试图将process分配给ChoiceDescription数组。在上面的示例中,在将两个ChoiceDescription对象分配给数组

之前,必须首先创建它们

最新更新