如何从命令行运行管道PowerShell命令?

时间:2014-07-09 15:20:07

标签: file datetime powershell command-line

我正在尝试从Windows 7命令行运行以下powershell命令:

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

我遇到了几个错误。当我运行上面的命令时,我收到错误:

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

我将命令更改为:

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

现在我收到了错误:

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

如何从命令行修改此命令?

更新

两种解决方案基本上都是同一回事,但@Trevor Sullivan有更明确的答案。

2 个答案:

答案 0 :(得分:2)

cmd.exe无法理解foreach对象。此外,您正试图跨两个单独的PowerShell流程拆分执行,这在这种情况下无效。

您需要在PowerShell中运行整个命令。

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

答案 1 :(得分:1)

我不确定你想要实现什么......但如果你是在文件和他们的最后修改时间之后,那么使用它:

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

您所要做的就是将命令括在双引号"中。