5

I am trying to execute powershell if-else from cmd. For example to check the number of files, that has "temp" in its name in D: drive,I used,

if(($i=ls D:\* | findstr /sinc:Temp).count -ne 0 ) {Write-Host $i}

This works fine from PS windows

But if want to do the same from cmd, How do i do it? I tried

powershell -noexit if(($i=ls D:\* | findstr /sinc:Temp).count -ne 0 ) {Write-Host $i}

which did not work unfortunately.

0

5 Answers 5

16

Just put the command in double quotes:

powershell "if(($i=ls D:\* | findstr /sinc:Temp).count -ne 0 ) {Write-Host $i}"

I also think you don't need the -NoExit switch here. This switch prevents powershell from exiting after running the command. If you want to return back to cmd, remove this switch.

Sign up to request clarification or add additional context in comments.

2 Comments

This is the correct answer to the question. Should be marked as so.
@utapyngo what if we need to run this as admin? is there any parameter too?
1

I know this doesn't answer how to run the command(others have covered it already), but why would you want to combine cmd and powershell, when both can do the job alone?

Ex 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 }

Ex cmd:

#Get all files with "temp" in filename
dir d:\*temp* /s /a:-d /b

Comments

1

Just another solution for you problem without using powershell:

dir /b D:\*Temp* | find /v /c "::"

This will print just the number of files or folders on D: that have "Temp" in their names. The double-colon here is just a string that should not be in the output of dir /b, so find /v /c "::" counts all lines of the output of dir /b.

Comments

0

@utapyngo's double quote solution works.

Also another way for @utapyngo's another way to make it in cmd:

dir /b D:\* | find /c "*Temp*"

And to Bill: there should not be a opening double quote before & in your first code, I guess?

Comments

-1

powershell -noexit "& "C:\........\run_script.ps1"

see these -- 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/

or for V2

Powershell.exe -File C:\.........\run_script.ps1

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.