2

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)

1
  • As an aside: There's no reason to use "& { ... }" in order to invoke code passed to PowerShell's CLI via the -Command (-c) parameter - just use "..." directly. Older versions of the CLI documentation erroneously suggested that & { ... } is required, but this has since been corrected. Commented Oct 25, 2023 at 17:01

2 Answers 2

2
  • 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 
    
Sign up to request clarification or add additional context in comments.

Comments

1

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 *

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.