简体   繁体   中英

How do I run a piped powershell command from command line?

I am trying to run the following powershell command from the windows 7 command line:

powershell ls 'C:/path to file/' | ForEach-Object {$_.LastWriteTime=Get-Date}

I have encountered several errors. When I run the above command, I get the error:

'ForEach-Object' is not recognized as an internal or external command, 
operable program or batch file.

I changed the command to:

powershell ls 'C:/My Programs/CPU Analysis/data/test/' | powershell ForEach-Object {$_.LastWriteTime=Get-Date}

Now I am getting the error:

Property 'LastWriteTime' cannot be found on this object; make sure it exists
and is settable.
At line:1 char:17
+ ForEach-Object {$_.LastWriteTime=Get-Date}
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound

How can I modify this command to work from the command line?

Update

Both solutions are basically saying the same thing, but @Trevor Sullivan has a clearer answer.

cmd.exe doesn't understand foreach object. Plus, you're trying to split execution across two separate PowerShell processes, which is not going to work in this scenario.

You'll need to run the whole command in PowerShell.

powershell "ls 'C:/My Programs/CPU Analysis/data/test/' | ForEach-Object {$_.LastWriteTime = Get-Date}"

I'm not sure what are you trying to achieve..but if you are after files and their last modified time then use this:

powershell "ls 'C:\path' | ft name,LastWriteTime"

All you have to do is enclose your command in double quotes " .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM