Home > Blockchain >  Powershell check storage on remote pc
Powershell check storage on remote pc

Time:03-16

Hello I am building a menu to run scripts per option selected and an option I want is to check storage of a remote pc but from researching I have broken the script and hopefully can get assistance from someone that has more than my month experience using 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

CodePudding user response:

You need to move the $Computer = Read-Host ... statement out of the Invoke-Command statement:

# 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

CodePudding user response:

You don't need to use Invoke-Command seeing as the WMI cmdlets accept a -ComputerName value:

$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]
        }
    }

Alternatively, you can have the Computer Name input be prompted first using the grouping operator (as Santiago points out in the comments):

Get-WmiObject -Class Win32_logicalDisk -Filter "DeviceID='C:'" -ComputerName (Read-Host -Prompt "Please Enter Host name")
  • Same goes for the subexpression operator which just tells PowerShell to ask for it first - without going into more detail.

Side Note:

The WMI Cmdlets such as Get-WMIObject are deprecated and have been replaced by the newer CIM Cmdlets.

  • Introduced in v3, it uses a separate remoting protocol other than DCOM.
    • This can be explicitly made to use DCOM as well, but not by default.
  • Emphasis on replaced as they are no longer part of PowerShell's deployment as of PowerShell Core.
  • Most cmdlets translate fairly easy if I may add:
    • Get-WmiObject -Class Win32_logicalDisk -Filter "DeviceID='C:'"
    • Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceID='C:'"
  • Related