PowerShell: External Command Output to Internal Command

72 Views Asked by At

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)

2

There are 2 best solutions below

0
mklement0 On BEST ANSWER
  • 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 
    
0
mandy8055 On

To achieve your purpose simply capture the output of the dir command and store it in a variable. Then, use that variable in Get-ChildItem. Something like:

$dirOutput = cmd /r dir /b/s/a/t screenshot_37.png
powershell -command "& {Get-ChildItem $dirOutput -RF}"

CAVEAT: If $dirOutput contains multiple paths, they would be passed as individual positional arguments, which would break the Get-ChildItem syntax.

Another Way:

You could also directly use Get-ChildItem to search for a specific file and get its attributes.

$file = "screenshot_37.png"
$items = Get-ChildItem -Filter $file -RF
$items | Format-List *