Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute powershell commands (not from ps1 file) from cmd.exe

Tags:

powershell

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.

like image 600
balajiboss Avatar asked May 11 '13 05:05

balajiboss


People also ask

Can I run PowerShell commands from CMD?

To start a Windows PowerShell session in a Command Prompt window, type PowerShell . A PS prefix is added to the command prompt to indicate that you are in a Windows PowerShell session.

How do I run a PowerShell script from the command exe?

To run scripts via the command prompt, you must first start up the PowerShell executable (powershell.exe), with the PowerShell location of C:\Program Files\WindowsPowerShell\powershell.exe and then pass the script path as a parameter to it.

How do I convert ps1 to exe?

Converting PS1 to EXE via the Command Line To convert a single PowerShell script to EXE via the command-line requires a single line providing the main PS2EXE command ( Invoke-PS2EXE ) followed by the script's path to convert and the path to the EXE you'd like to create.


2 Answers

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.

like image 72
utapyngo Avatar answered Nov 02 '22 23:11

utapyngo


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
like image 34
Frode F. Avatar answered Nov 03 '22 01:11

Frode F.