Get File Information Remotely PowerShell

Get File Information Remotely PowerShell

Hello,

When you work locally, getting a file size isn’t an issue:

Get-Item C:WindowsSystem32cmd.exe

Get File Information Remotely PowerShell - CMD file

Get File Information Remotely PowerShell – CMD file

Or:

(Get-Item -Path C:WindowsSystem32cmd.exe | Select-Object -ExpandProperty Length) /1KB -as [int]
Get File Information Remotely PowerShell - File Size in KB

Get File Information Remotely PowerShell – File Size in KB

Get File Information Remotely PowerShell – Invoke-Command

But, if you want to to it on a remote server, you may want to use “Invoke-Command“:

Invoke-Command -ComputerName DC2-Core -ScriptBlock {(Get-Item -Path C:WindowsSystem32cmd.exe | Select-Object -ExpandProperty Length) /1KB -as [int]}
Get File Information Remotely PowerShell - Invoke-Command

Get File Information Remotely PowerShell – Invoke-Command

But this require that PowerShell remoting is enabled and working on the other side.

Get File Information Remotely – WMI

There is another way with WMI, we’ll need the “Cim_DataFile” class.

$PathToCmd = 'C:WindowsSystem32cmd.exe'
$PathToCmdForWMI = $PathToCmd -replace '\','\'
(Get-WmiObject -Class Cim_DataFile -Filter "Name='$PathToCmdForWMI'" -ComputerName DC2-CORE | Select-Object -ExpandProperty FileSize) / 1KB -as [int]
Get File Information Remotely PowerShell - WMI.PNG

Get File Information Remotely – WMI.PNG

Note: You need to double all the “” in the path to get it to work.

Note 2: This method also work on Windows Server 2003.

Get File Information Remotely – CIM

You can also do it with “Get-CimInstance“, over WinRM, but that’s killing the purpose of avoiding using it:

$PathToCmd = 'C:WindowsSystem32cmd.exe'
$PathToCmdForWMI = $PathToCmd -replace '\','\'
(Get-CimInstance -Class Cim_DataFile -Filter "Name='$PathToCmdForWMI'" -ComputerName DC2-CORE | Select-Object -ExpandProperty FileSize) / 1KB -as [int]
Get File Information Remotely PowerShell - CIM.PNG

Get File Information Remotely – CIM.PNG

User Get-CimInstance with older Operating System

If you want to target an older operating system such as Windows Server 2003, you may want to use the “Get-WmiObject” method, but, if your host running PowerShell is PowerShell 3.0°, you may have a way to use the more reliable and efficient “Get-CimInstance”, but you will need a CimSessionOption:

$SessionOption = New-CimSessionOption -Protocol DCOM
$CimSession    = New-CimSession -SessionOption $SessionOption -ComputerName $RemoteComputer

And then you will be able to use “Get-CimInstance” to target an older operating system with DCOM instead of WinRM.

Leave a Reply