如果没有输入输入则提示

时间:2013-12-20 15:34:17

标签: variables powershell input

如果我只是按Enter而不输入任何变量..它会吐出错误。我可以添加什么才能让它再次重新编译?

 mode con: cols=35 lines=5
while (1) {
    $tag1 = Read-Host 'Enter tag # or Q to quit'
    if ($tag1 -eq "Q") {
        break;
    }

    mode con: cols=80 lines=46

    cls

    sc.exe \\$tag1 start RemoteRegistry;

    cls

    start-sleep -seconds 2

    cls

    $OSInfo = get-wmiobject -class win32_operatingsystem -computername $tag1;
    $OSInfo | Format-Table -Property @{Name="OS Name";Expression={$_.Caption}} -AutoSize;
    $OSInfo | Format-Table -Property @{Name="System Boot Time";Expression={$_.ConvertToDateTime($_.LastBootUpTime)}} -AutoSize;
    $OSInfo | Format-Table -Property @{Name="OS Install Date";Expression={$_.ConvertToDateTime($_.InstallDate)}} -AutoSize;

    "`n"

    "Current Date & Time: $(Get-Date -Format G)";

    "`n"

    Get-WmiObject win32_computersystem -Computer $tag1 | Format-Table -Property @{Name="Username";Expression={$_.username}} -Autosize;

    Get-EventLog system -computername $tag1 -InstanceId 2147489657 -Newest 10 | format-table EventID,TimeWritten,MachineName -AutoSize;
}

2 个答案:

答案 0 :(得分:1)

只需清除变量然后循环直到设置完毕。

$tag1 = ""
while (-not ($tag1)) {
  $tag1 = Read-Host 'Enter tag # or Q to quit'
}

答案 1 :(得分:1)

几种不同的方式:

$tag1 = $null
while (-not $tag1 ) {
    $tag1 = Read-Host 'Enter tag # or Q to quit'
    if ($tag1 -eq "Q") {
        return;
    }
}

mode con: cols=80 lines=46

cls

sc.exe \\$tag1 start RemoteRegistry;

cls

start-sleep -seconds 2

cls

$OSInfo = get-wmiobject -class win32_operatingsystem -computername $tag1;
$OSInfo | Format-Table -Property @{Name="OS Name";Expression={$_.Caption}} -AutoSize;
$OSInfo | Format-Table -Property @{Name="System Boot Time";Expression={$_.ConvertToDateTime($_.LastBootUpTime)}} -AutoSize;
$OSInfo | Format-Table -Property @{Name="OS Install Date";Expression={$_.ConvertToDateTime($_.InstallDate)}} -AutoSize;

"`n"

"Current Date & Time: $(Get-Date -Format G)";

"`n"

Get-WmiObject win32_computersystem -Computer $tag1 | Format-Table -Property @{Name="Username";Expression={$_.username}} -Autosize;

Get-EventLog system -computername $tag1 -InstanceId 2147489657 -Newest 10 | format-table EventID,TimeWritten,MachineName -AutoSize;

或者:

$GetTag = {
 Switch (Read-Host 'Enter tag # or Q to quit')
  {
    'Q' {Return}
    ''  {.$GetTag}
    default {$_}
  }
}

 $tag = &$GetTag