windowspowershellcommandexternalinternals

PowerShell: External Command Output to Internal Command


I want to run these two commands in PowerShell in conjunction, and use the output of dir as the path in Get-ChildItem

cmd /r dir /b/s/a/t screenshot_37.png; powershell -command "& {Get-ChildItem "dir output" -recurse -force}"

Can I receive some insight into how this is possible?

(Context: I'm conducting searches of specific files, and want to know their attributes if found)


Solution

    • If you're calling this from PowerShell, you don't need to call powershell.exe to run Get-ChildItem: just invoke the latter directly, which avoids the costly creation of a PowerShell child process.

      • If you were to solve this via cmd.exe's dir command (see next point for how to avoid that), you'd need:

        Get-ChildItem -Recurse -Force -LiteralPath (
          cmd /c dir /b /s /a screenshot_37.png
        ) | Select FullName, Attributes
        
      • Note that I'm using /c with cmd.exe (/r is a rarely seen alias that exists for backward compatibility) and that I've removed dir's /t option, which has no effect due to use of /b.

    • More fundamentally, a single Get-ChildItem call should suffice - no need for cmd.exe's internal dir command:

      Get-ChildItem -Recurse -Force -Filter screenshot_37.png |
        Select FullName, Attributes