【问题标题】:powershell get info about computerpowershell 获取有关计算机的信息
【发布时间】:2019-01-31 19:46:32
【问题描述】:

我正在尝试创建一个 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

这就是我发现的:Script 我根据自己的需要对其进行了修改,但每当我尝试运行此脚本时,我都会以错误的方式得到它 - 它向我显示了整个脚本,最后才询问我计算机名称:

$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,我找到了,但它不起作用。我不能说我挖遍了整个互联网,但我希望你们(和女孩?)能帮我弄清楚。解决这三个问题应该不难,毕竟不是超级复杂的脚本吧?我当前的脚本只有 31 行,包括空格。

【问题讨论】:

  • 您的设置是否需要密码或用户名?在大多数网络上,您只需运行 CIM/WMI cmdlet,它将使用当前帐户信息访问系统。
  • 如果您不打算使用参数调用此脚本,请省略 start param 块。 $HostList 在哪里定义?如果您不想在每次执行中显示整个脚本,请至少保存一次。
  • 我尝试在没有密码的情况下运行,但它不起作用:+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

标签: powershell export-to-csv export-to-excel


【解决方案1】:

这是从一组系统中获取基本系统信息的一种方法的演示。它使用 CIM cmdlet,因为它们比 WMI cmdlet [大多数时间] 更快,将日期时间信息作为标准日期时间对象呈现,并且没有被弃用。

它还使用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

【讨论】:

  • 我想你误会了。我不想创建计算机列表并使用该列表来获取有关其中计算机的信息。我希望能够输入计算机名称并获取该特定计算机上的信息。然后,一旦我得到关于它的信息,我想得到一条消息,我是否想得到关于另一台计算机的信息,在“y”键上,等等,直到我点击代表“no”的“n”并且作为这样,取消。在我尝试获取有关它们的信息时,许多计算机可能不可用,如果计算机不可用,我想不是从文件中了解它,而是“实时”了解它。
  • @user10864312 - 在代码周围包裹一个while 循环,它只会在一个系统上为您提供相同的结果。我展示的是如何获取信息而不需要进行多次信息传输的演示......在远程机器上运行它,在那里收集信息,过滤掉你真正想要的东西,然后只发回数据你渴望。否则,您将通过网络发送信息,因为您很少需要来自任何给定 CIM/WMI 调用的多个道具。
  • 很抱歉看起来很愚蠢,但我对 powershell 没有太多经验。将“while”循环包裹在代码的哪一部分?我可能需要几个小时来测试,所以问起来更容易......而且......如果我包装它,我会收到关于计算机名称的请求以获取有关信息吗?
  • @user10864312 - 啊!我没有意识到你的新鲜感。 [grin] 我添加了一个 while 循环的演示,用于获取用户输入。如果这按需要工作,那么我会返回并删除偏离主题的数据收集代码,如果你想清除的话。
  • 抱歉回复晚了,但是……我刚刚有机会检查代码。这是我写到文件末尾的内容:$RespondingSystems | Export-Csv -Path C:\Users\user\Documents\results.csv 和生成的文档 - CSV 文件 - 是空的。完全是空的。甚至它的大小也是 0 字节。难道我做错了什么?就像我说的那样,我使用我发现的东西,根本没有使用 Powershell 编码的经验。 (我知道 '$' 创建了一个变量,但对于任何计算机编程语言我都可以说同样的话 - 我知道 'if' 和 'while' 以及其他一些东西,但仅此而已。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多