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())
{
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();
}