Powershell 检查远程电脑上的存储

Powershell check storage on remote pc

你好,我正在为每个选择的选项构建一个 运行 脚本的菜单,我想要的一个选项是检查远程 pc 的存储,但是通过研究我已经破坏了脚本,希望能得到某人的帮助使用 PS.

的经验超过我一个月
Invoke-Command $Computer = Read-Host Please Enter Host name  -ScriptBlock{Get-WmiObject -Class Win32_logicalDisk -Filter "DeviceID='C:'" | Select SystemName, DeviceID, @{n='Size(GB)';e={$_.size / 1gb -as [int]}},@{n='Free(GB)';e={$_.Freespace / 1gb -as [int]}}} > C:\DiskInfo_output.txt

您需要将 $Computer = Read-Host ... 语句移出 Invoke-Command 语句:

# Ask for computer name
$Computer = Read-Host "Please Enter Host name"

# Invoke command on remote computer
Invoke-Command -ComputerName $Computer -ScriptBlock {
    Get-WmiObject -Class Win32_logicalDisk -Filter "DeviceID='C:'" | Select SystemName, DeviceID, @{n='Size(GB)';e={$_.size / 1gb -as [int]}},@{n='Free(GB)';e={$_.Freespace / 1gb -as [int]}}
} > C:\DiskInfo_output.txt

您不需要使用 Invoke-Command,因为 WMI cmdlet 接受 -ComputerName 值:

$ComputerName = Read-Host -Prompt "Please Enter Host name"
Get-WmiObject -Class Win32_logicalDisk -Filter "DeviceID='C:'" -ComputerName $ComputerName | 
    Select-Object -Property SystemName, DeviceID, @{
        Name ='Size(GB)';
        Expression = {
            $_.size / 1gb -as [int]
        }
    }, @{
        Name ='Free(GB)';
        Expression = {
            $_.Freespace / 1gb -as [int]
        }
    }

或者,您可以首先使用分组运算符提示输入计算机名(正如 Santiago 在评论 中指出的那样):

Get-WmiObject -Class Win32_logicalDisk -Filter "DeviceID='C:'" -ComputerName (Read-Host -Prompt "Please Enter Host name")
  • 子表达式运算符也是如此,它只是告诉 PowerShell 首先请求它 - 无需详细说明

旁注:

Get-WMIObject 等 WMI Cmdlet 已弃用,已被较新的 CIM Cmdlets 取代。

  • 在 v3 中引入,它使用不同于 DCOM 的单独远程处理协议。
    • 这也可以明确地使用 DCOM,但不是默认情况下。
  • 强调已替换,因为从 PowerShell Core 开始,它们不再是 PowerShell 部署的一部分。
  • 如果我可以添加,大多数 cmdlet 翻译起来相当容易:
    • Get-WmiObject -Class Win32_logicalDisk -Filter "DeviceID='C:'"
    • Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceID='C:'"