Trouble linking commands together

Viewed 29

So i'm pretty new to powershell and I'm trying to list all contents of a directory(on my vm) while stating if each is a reg file or directory along with it's path/size. the code I have is:

#!/bin/bash
cd c:\
foreach ($item in get-childitem -Path c:\) {
Write-Host $item
}
########
if(Test-Path $item){
Write-Host "Regular File" $item
}
else {
Write-Host "Directory" $item

...I can get all of the contents to print but when i try to state whether file/directory, only one .txt file says "Regular File" next to it. I've been at it for hours on end and get figure it out. Also, my output doesn't state "directory" next to directories...

1 Answers

Here is an example of how you can enumerate the files and folders on your C Drive one level deep with their current size (if it's a folder, look for the files inside and get a sum of it's Length). Regarding trying to "state whether file / directory", you don't need to apply any logic to it, FileInfo and DirectoryInfo have an Attributes property which gives you this information already.

Get-ChildItem -Path C:\ | & {
    process {
        $object = [ordered]@{
            Attributes = $_.Attributes
            Path       = $_.Name # change to $_.FullName for the Path
            Length     = $_.Length / 1mb
        }

        if($_ -is [IO.DirectoryInfo]) {
            foreach($file in $_.EnumerateFiles()) {
                $object['Length'] += $file.Length / 1mb
            }
        }
        $object['Length'] = [math]::Round($object['Length'], 2).ToString() + ' Mb'
        [pscustomobject] $object
    }
}

If you want something more complex, i.e. seeing the hierarchy of a directory, like tree does, with the corresponding sizes you can check out this module.

Related