簡體   English   中英

powershell獲取有關計算機的信息

[英]powershell get info about computer

我正在嘗試創建Powershell腳本(獲得更高級的功能……JK。Powershell提供的功能比批處理文件還多,我想使用其中的一些功能。)

所以,這是我的批處理腳本:

:Start 
@echo off 
set /p password="Password:" 
:Nextcomp 
set /p computer="Computer name:" 
wmic /user:username /password:%password% /node:"%computer%" memorychip get capacity 
set /P c=Do you want to get info about another computer (y/n)? 
if /I "%c%" EQU "y" goto :Nextcomp 
if /I "%c%" EQU "n" goto :End goto :choice 
pause 
:End

我發現的是: 腳本是根據我的需要進行修改的,但是每當我嘗試運行此腳本時,我都會以錯誤的方式得到它-它向我顯示整個腳本,最后它只是詢問我有關計算機的名稱:

$resultstxt = "C:\Users\user\Documents\results.csv"
Param(
     [Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
     [SecureString]$password
   )
$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
$Computer = Read-Host -Prompt 'Computer name'
$out = @()
If (!(Test-Connection -ComputerName $Computer -Count 1 -Quiet)) { 
    Write-Host "$Computer not on network."
    Continue 
}
foreach($object in $HostList) {
$RAM = get-wmiobject -user user -password $pw -computername $object.("Computer")-class win32_physicalmemory 
$DeviceInfo= @{}
$DeviceInfo.add("RAM", "$([math]::floor($RAM.Capacity/ (1024 * 1024 * 1024 )) )" + " GB" )
$DeviceInfo.add("Computer Name", $vol.SystemName)
$out += New-Object PSObject -Property $DeviceInfo | Select-Object "RAM"
Write-Verbose ($out | Out-String) -Verbose             
$out | Export-CSV -FilePath $resultstxt -NoTypeInformation

}

您可能已經猜到了,我有更多的字段,但是它們都是相似的,並且我從很多資源中借來,但主要來自“腳本”鏈接。

我想要的是:

  1. 隱藏密碼
  2. 將信息導出到CSV,並將每台新計算機(請參閱3.)添加到當前計算機之后(在下一行)
  3. 詢問我是否要獲取有關另一台計算機的信息,請使用“ y”鍵表示是,使用“ n”鍵表示否。
  4. 使腳本工作

我發現了問題1,但尚未測試,所以...行得通嗎? 接下來,我發現了問題2,但是它將以一種不易閱讀的格式顯示所有信息,而不是我需要的所有信息,並且全部顯示在一個單元格中。 最終,我發現大約3,但這是行不通的。 我不能說我挖了整個互聯網,但我希望你們(還有gal?)能幫我弄清楚。 解決這三個問題不應該那么困難,畢竟這不是一個超級復雜的腳本,對嗎? 我當前的腳本只有31行,包括空格。

這是從一組系統中獲取基本系統信息的一種方法的演示。 它使用CIM cmdlet,因為它們比WMI cmdlet更快(大多數時間),將datetime信息顯示為標准datetime對象,並且不建議過時。

它還使用Invoke-Command cmdlet進行遠程並行處理,並設置為忽略錯誤,以便無響應的系統不會浪費您的時間。

#requires -RunAsAdministrator

# fake reading in a list of computer names
#    in real life, use Get-Content or (Get-ADComputer).Name
$ComputerList = @'
Localhost
BetterNotBeThere
127.0.0.1
10.0.0.1
::1
'@ -split [environment]::NewLine

$IC_ScriptBlock = {
    $CIM_ComputerSystem = Get-CimInstance -ClassName CIM_ComputerSystem
    $CIM_BIOSElement = Get-CimInstance -ClassName CIM_BIOSElement
    $CIM_OperatingSystem = Get-CimInstance -ClassName CIM_OperatingSystem
    $CIM_Processor = Get-CimInstance -ClassName CIM_Processor
    $CIM_LogicalDisk = Get-CimInstance -ClassName CIM_LogicalDisk |
        Where-Object {$_.Name -eq $CIM_OperatingSystem.SystemDrive}

    [PSCustomObject]@{
        LocalComputerName = $env:COMPUTERNAME
        Manufacturer = $CIM_ComputerSystem.Manufacturer
        Model = $CIM_ComputerSystem.Model
        SerialNumber = $CIM_BIOSElement.SerialNumber
        CPU = $CIM_Processor.Name
        SysDrive_Capacity_GB = '{0:N2}' -f ($CIM_LogicalDisk.Size / 1GB)
        SysDrive_FreeSpace_GB ='{0:N2}' -f ($CIM_LogicalDisk.FreeSpace / 1GB)
        SysDrive_FreeSpace_Pct = '{0:N0}' -f ($CIM_LogicalDisk.FreeSpace / $CIM_LogicalDisk.Size * 100)
        RAM_GB = '{0:N2}' -f ($CIM_ComputerSystem.TotalPhysicalMemory / 1GB)
        OperatingSystem_Name = $CIM_OperatingSystem.Caption
        OperatingSystem_Version = $CIM_OperatingSystem.Version
        OperatingSystem_BuildNumber = $CIM_OperatingSystem.BuildNumber
        OperatingSystem_ServicePack = $CIM_OperatingSystem.ServicePackMajorVersion
        CurrentUser = $CIM_ComputerSystem.UserName
        LastBootUpTime = $CIM_OperatingSystem.LastBootUpTime
        }
    }

$IC_Params = @{
    ComputerName = $ComputerList
    ScriptBlock = $IC_ScriptBlock
    ErrorAction = 'SilentlyContinue'
    }
$RespondingSystems = Invoke-Command @IC_Params
$NOT_RespondingSystems = $ComputerList.Where({
    # these two variants are needed to deal with an ipv6 localhost address
    "[$_]" -notin $RespondingSystems.PSComputerName -and
    $_ -notin $RespondingSystems.PSComputerName
    })

# if you want to remove the PSShowComputerName, PSComputerName & RunspaceID props, use ... 
#    Select-Object -Property * -ExcludeProperty PSShowComputerName, PSComputerName, RunspaceId


'=' * 40
$RespondingSystems
'=' * 40
$NOT_RespondingSystems

截斷的輸出...

LocalComputerName           : [MySysName]
Manufacturer                : System manufacturer
Model                       : System Product Name
SerialNumber                : System Serial Number
CPU                         : AMD Phenom(tm) II X4 945 Processor
SysDrive_Capacity_GB        : 931.41
SysDrive_FreeSpace_GB       : 745.69
SysDrive_FreeSpace_Pct      : 80
RAM_GB                      : 8.00
OperatingSystem_Name        : Microsoft Windows 7 Professional 
OperatingSystem_Version     : 6.1.7601
OperatingSystem_BuildNumber : 7601
OperatingSystem_ServicePack : 1
CurrentUser                 : [MySysName]\[MyUserName]
LastBootUpTime              : 2019-01-24 1:49:31 PM
PSComputerName              : [::1]
RunspaceId                  : c1b949ef-93af-478a-b2cf-e44d874c5724

========================================
BetterNotBeThere
10.0.0.1

要獲得結構良好的CSV文件,請通過Export-CSV$RespondingSystems集合發送到該文件。


對於環繞任何給定代碼塊的循環演示,請看一下...

$Choice = ''

while ([string]::IsNullOrEmpty($Choice))
    {
    $Choice = Read-Host 'Please enter a valid computer name or [x] to exit '
    # replace below with real code to check if $ComputerName is valid
    if ($Choice -eq $env:COMPUTERNAME)
        {
        $ValidCN = $True
        }
        else
        {
        $ValidCN = $False
        }
    if (-not $ValidCN -and $Choice -ne 'x')
        {
        # insert desired error notice
        [console]::Beep(1000, 300)
        Write-Warning ''
        Write-Warning ('Your choice [ {0} ] is not a valid computer name.' -f $Choice)
        Write-Warning '    Please try again ...'
        pause
        $Choice = ''
        }
        elseif ($Choice -ne 'x')
        {
        # insert code to do the "ThingToBeDone"
        Write-Host ''
        Write-Host ('Doing the _!_ThingToBeDone_!_ to system [ {0} ] ...' -f $Choice)
        pause
        $Choice = ''
        }
    }

屏幕輸出...

Please enter a valid computer name or [x] to exit : e
WARNING: 
WARNING: Your choice [ e ] is not a valid computer name.
WARNING:     Please try again ...
Press Enter to continue...: 
Please enter a valid computer name or [x] to exit : [MySysName]

Doing the _!_ThingToBeDone_!_ to system [ [MySysName] ] ...
Press Enter to continue...: 
Please enter a valid computer name or [x] to exit : x

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM