Click here to Skip to main content
15,888,270 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Trying to get the results of this powershell script to return a table object so that i can read the object in C#

The powershell script recursively counts the number of files in a directory

What I have tried:

I have tried this:

cd D:\VMs
dir -recurse | ?{ $_.PSIsContainer } | %{ Write-Host $_.FullName $_.DirectoryName (dir $_.FullName | Measure-Object).Count} 


Which returns the right results but with no header like i expect it to.

Results from script

PS D:\VMs> C:\test\test.ps1
D:\VMs\Windows 10 Pro  52
D:\VMs\WindowsXP  29
D:\VMs\Windows 10 Pro\564d6a23-4315-5965-49a6-cef8c565a3ca.vmem.lck  1
D:\VMs\Windows 10 Pro\caches  1
D:\VMs\Windows 10 Pro\Personal Windows 10 Pro.vmdk.lck  1
D:\VMs\Windows 10 Pro\Personal Windows 10 Pro.vmx.lck  1
D:\VMs\Windows 10 Pro\caches\GuestAppsCache  2
D:\VMs\Windows 10 Pro\caches\GuestAppsCache\appData  442
D:\VMs\Windows 10 Pro\caches\GuestAppsCache\launchMenu  2
D:\VMs\WindowsXP\caches  1
D:\VMs\WindowsXP\caches\GuestAppsCache  2
D:\VMs\WindowsXP\caches\GuestAppsCache\appData  161
D:\VMs\WindowsXP\caches\GuestAppsCache\launchMenu  2


Would like the headers to be Directory and CountOfFilesInDirectory

    Directory: D:\vms


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2019-08-06  12:12 PM                Windows 10 Pro
d-----       2019-08-02   4:09 PM                WindowsXP



Like the headers showing above

C# code

string script = File.ReadAllText(@"c:\test\test.ps1");

using (PowerShell PowerShellInst = PowerShell.Create())
{
    //string criteria = "system*";
    //PowerShellInst.AddScript("Get-Service -DisplayName " + criteria);
    PowerShellInst.AddScript(script);
    Collection<PSObject> PSOutput = PowerShellInst.Invoke();
    foreach (PSObject obj in PSOutput)
    {
        if (obj != null)
        {
            obj.ToString();
            Console.Write(obj.Properties["Directory"].Value.ToString() + " - ");
            Console.WriteLine(obj.Properties["CountOfFilesInDirectory"].Value.ToString());
        }
    }
    Console.WriteLine("Done");
    Console.Read();
}
Posted
Updated 8-Aug-19 4:04am
v4

1 solution

Try using Select-Object instead of Write-Host:
PowerShell
dir -recurse | ?{ $_.PSIsContainer } | select-object -property FullName, Name, @{label="CountOfFilesInDirectory";expression={(dir $_.FullName | measure-object).Count}}
Select-Object[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900