如何执行PowerShell命令从CMD.EXE
我想执行的PowerShell的if-else从CMD(而不是从PS1文件)。 例如要检查的文件数,有“临时”在其d名称:驱动器,我使用的,如何执行PowerShell命令从CMD.EXE
if(($i=ls D:\* | findstr /sinc:Temp).count -ne 0) {Write-Host $i}
这工作得很好,从PS窗户
但如果想要做同样的从cmd,我该怎么做? 我试过
powershell -noexit if(($i=ls D:\* | findstr /sinc:Temp).count -ne 0) {Write-Host $i}
不幸的是没有工作。
只要把命令在双引号:
powershell "if(($i=ls D:\* | findstr /sinc:Temp).count -ne 0) {Write-Host $i}"
我还以为你不要在这里需要-noexit开关。此开关可防止运行命令后PowerShell退出。如果您想返回到cmd
,请移除此开关。
powershell -noexit "& "C:\........\run_script.ps1"
看到这些 - http://poshoholic.com/2007/09/27/invoking-a-powershell-script-from-cmdexe-or-start-run/
http://www.leeholmes.com/blog/2006/05/05/running-powershell-scripts-from-cmd-exe/
或V2
Powershell.exe -File C:\.........\run_script.ps1
只为你问题的另一种解决方案,无需使用PowerShell:
dir /b D:\*Temp* | find /v /c "::"
这将打印的文件或文件夹d只是数量:那些在他们的名字“温度”。这里的双冒号只是不应该在dir /b
输出一个字符串,所以find /v /c "::"
计数dir /b
输出的所有行。
@ utapyngo的双引号解决方案工作。
而且另一种为@ utapyngo的另一种方式,使其在CMD:
dir /b D:\* | find /c "*Temp*"
而比尔:不应该有你的第一个代码&前打开双引号,我猜?
我知道这并没有回答如何运行命令(别人已经覆盖),但你为什么要合并CMD和PowerShell,当两个可以单独完成这项工作?
防爆的PowerShell:
#Get all files on D: drive with temp in FILEname(doesn't check if a foldername was temp)
Get-ChildItem D:\ -Recurse -Filter *temp* | where { !$_.PSIsContainer } | foreach { $_.fullname }
#Check if fullpath includes "temp" (if folder in path includes temp, all files beneath are shown)
Get-ChildItem D:\ -Recurse | where { !$_.PSIsContainer -and $_.FullName -like "*temp*" } | foreach { $_.fullname }
防爆CMD:
#Get all files with "temp" in filename
dir d:\*temp* /s /a:-d /b
这是正确答案的问题。应该标记为如此。 – villamejia 2015-04-17 20:09:51