Powershell,获取用户输入的计算机名称并显示计算机的BIOS信息,操作系统信息和磁盘信息

时间:2015-10-17 21:28:39

标签: powershell

我正在尝试为我可以运行此脚本的目标计算机获取用户输入。如果没有指定计算机名称,我想显示错误消息。恩。我选择dc1和所有BIOS信息,Os信息和硬盘显示dc1而不是我的本地计算机。关于如何实现这一目标的任何想法?

#Clears the screen
cls

#Sets status to 0 just incase its not already zero, option 4 sets status to 4 and exit the loop
$status = 0

#Gets the BIOS information
$biosInfo = get-CIMInstance -Class CIM_BIOSElement |select-Object SMBIOSBIOSVersion, Manufacturer, SerialNumber, Version | Format-Table

#Gets the Operating System information
$osInfo = get-CIMInstance -Class CIM_OperatingSystem | Select-Object Caption, Version |Format-List

#Gets the Disk information
$discInfo= get-CIMInstance -Class CIM_LogicalDisk |Select-Object DeviceID, FreeSpace, Size |Format-List @{Name=‘DeviceID‘;Expression={$_.DeviceID}}, @{Name=‘FreeSpace(InPercent)’;Expression={[math]::Round($_.FreeSpace / $_.Size,2)*100}}, @{Name=‘Size(GB)’;Expression={[int]($_.Size / 1GB)}}                                             

#Function to select computer name
function name { 

$a = get-cimInstance -Class CIM_ComputerSystem.computername

}


#Menu selection zone!
Write-Host "Query Computer System Main Menu"
Write-Host ""
Write-Host "1 Display Current BIOS information"
Write-Host "2 Display Operating System Information"
Write-host "3 Display Hard Disk Information"
Write-Host "4 Exit"
Write-Host ""

do 
{

$status = read-host "Please enter and Option"
$computer = Read-Host "Enter target computer name"  

if ($computer -ne $computer){Write-host "ERROR! Please enter a target computer name" }
if ($status -ne 4){
}

#Where the menu magic happens
switch ($status){
    1{ $biosInfo ; pause}
    2{ $osInfo ; pause}
    3{ $discInfo ; pause}
    4{ $status_text = '4 Exit' ;$status = 4}
   default {"Please select a number in the list!"}
}
}
#Exits the do loop when status is equal to 4
while ($status -ne 4)

1 个答案:

答案 0 :(得分:0)

您需要在函数或参数化的scriptblock中抽象出Get-CimInstance个调用。

而不是立即针对本地计算机执行此操作:

$OSInfo = Get-CimInstance -Class CIM_OperatingSystem

你想要这样的东西:

$OSInfoGetter = {
    param([string]$ComputerName)

    Get-CimInstance -Class CIM_OperatingSystem -ComputerName $ComputerName
}

现在您可以使用调用运算符(&)重新调用您的scriptblock并提供任何计算机名作为参数:

$OSInfo = &$OSInfoGetter $env:ComputerName

为了检查用户输入的计算机名称,我将在第一个中放入另一个do{}while()循环:

do 
{
    $status = Read-Host "Please enter and Option"

    do{
        $Computer = Read-Host "Enter target computer name"
        if (($InvalidName = [string]::IsNullOrWhiteSpace($Computer))){
            Write-Warning "ERROR! Please enter a target computer name"
        }
    } until (-not $InvalidName)

    # switch goes here

} while ($status -ne 4)

您可以替换您想要的任何逻辑,例如检查Active Directory中是否存在计算机

相关问题