Running powershell command from cmd - windows

I'm new in windows environment. How can I execute the following powershell command from cmd "hello gourav how are you1" | Out-File filename -append

Open cmd from Run and execute powershell /? to know all the options you have.
PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
[-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
[-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
[-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
[-ConfigurationName <string>]
[-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
PowerShell[.exe] -Help | -? | /?
-PSConsoleFile
Loads the specified Windows PowerShell console file. To create a console
file, use Export-Console in Windows PowerShell.
-Version
Starts the specified version of Windows PowerShell.
Enter a version number with the parameter, such as "-version 2.0".
-NoLogo
Hides the copyright banner at startup.
-NoExit
Does not exit after running startup commands.
-Sta
Starts the shell using a single-threaded apartment.
Single-threaded apartment (STA) is the default.
-Mta
Start the shell using a multithreaded apartment.
-NoProfile
Does not load the Windows PowerShell profile.
-NonInteractive
Does not present an interactive prompt to the user.
-InputFormat
Describes the format of data sent to Windows PowerShell. Valid values are
"Text" (text strings) or "XML" (serialized CLIXML format).
-OutputFormat
Determines how output from Windows PowerShell is formatted. Valid values
are "Text" (text strings) or "XML" (serialized CLIXML format).
-WindowStyle
Sets the window style to Normal, Minimized, Maximized or Hidden.
-EncodedCommand
Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.
-ConfigurationName
Specifies a configuration endpoint in which Windows PowerShell is run.
This can be any endpoint registered on the local machine including the
default Windows PowerShell remoting endpoints or a custom endpoint having
specific user role capabilities.
-File
Runs the specified script in the local scope ("dot-sourced"), so that the
functions and variables that the script creates are available in the
current session. Enter the script file path and any parameters.
File must be the last parameter in the command, because all characters
typed after the File parameter name are interpreted
as the script file path followed by the script parameters.
-ExecutionPolicy
Sets the default execution policy for the current session and saves it
in the $env:PSExecutionPolicyPreference environment variable.
This parameter does not change the Windows PowerShell execution policy
that is set in the registry.
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
in Windows PowerShell. The results of the script block are returned to the
parent shell as deserialized XML objects, not live objects.
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
To write a string that runs a Windows PowerShell command, use the format:
"& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.
-Help, -?, /?
Shows this message. If you are typing a PowerShell.exe command in Windows
PowerShell, prepend the command parameters with a hyphen (-), not a forward
slash (/). You can use either a hyphen or forward slash in Cmd.exe.
EXAMPLES
PowerShell -PSConsoleFile SqlSnapIn.Psc1
PowerShell -version 2.0 -NoLogo -InputFormat text -OutputFormat XML
PowerShell -ConfigurationName AdminRoles
PowerShell -Command {Get-EventLog -LogName security}
PowerShell -Command "& {Get-EventLog -LogName security}"
# To use the -EncodedCommand parameter:
$command = 'dir "c:\program files" '
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand

Maybe a bit off-topic but this does the same trick without powershell (i.e. directly from cmd prompt):
echo Your text >>filename

simple
#ECHO off
SET LONG_COMMAND=^
if ($true)^
{^
$Resolution=Get-DisplayResolution;^
Write-Host $Resolution;^
}
START Powershell -noexit -command %LONG_COMMAND%
with return
#echo off
set "psCommand="[Environment]::GetFolderPath('DesktopDirectory')""
for /f "usebackq delims=" %%I in (`powershell %psCommand%`) do set "folder=%%I"
echo DesktopDirectory = %folder%

you can use powershell.exe in cmd to execute powershell command.
powershell.exe "your command"
like
powershell.exe "\"hello gourav how are you1\" | Out-File filename -append"
And you can enter interact interface in powershell using powershell directly

Related

Unable to capture output from CMD

Trying to open CMD in elevated mode and running powershell script.
powershell -Command "Start-Process cmd \"/k "PowerShell -NoProfile -ExecutionPolicy Bypass -file ""C:\WIM_Creation.ps1 ""hello"" V7.0E V9.0A""\" -Verb RunAs"
Note: Problem is in order to open CMD in elevated mode from current CMD window it redirect to new window in elevated mode and run the command. due to which output is not getting captured in primary CMD window. HENCE NOT GETTING OUTPUT CAPTURED IN JENKINS.
Need to open elevated CMD in current CMD.
An elevated process launched from a non-elevated one invariably runs in a new window.
A non-elevated process that launches an elevated one cannot capture its output.
The workaround is to make the elevated process itself capture its output, by redirecting it to a file.
Unless the program running in the elevated process itself happens to support that, you must call it via a shell, i.e. launch the shell elevated, and pass it a command line that invokes the target executable with a shell redirection (>)
To make your code work:
You need to add -Wait to your Start-Process -Verb RunAs call to ensure that it waits for the elevated process to terminate.
This precludes using cmd /k in automated execution, as it would create a cmd.exe session that stays open until closed by the user.
While you could use cmd /c, there's no reason to create another cmd.exe process - just call the nested powershell instance directly.
*>$env:TEMP\out.txt is used to capture the elevated powershell instance's output in a temporary file, whose content is then output by the outer (non-elevated) instance.
Note:
The file's content is only output after the elevated process has exited, so you won't get realtime feedback; while implementing the latter is possible, it would significantly complicate the solution.
Using fixed file name out.txt creates the potential for name collisions; ruling those out would require more work.
powershell -Command "Start-Process -Verb RunAs -Wait powershell '-NoProfile -ExecutionPolicy Bypass -file C:\WIM_Creation.ps1 \"hello\" V7.0E V9.0A *>$env:TEMP\out.txt'; Get-Content $env:TEMP\out.txt; Remove-Item $env:TEMP\out.txt"
Note that I've made some corrections to the use of " quotes in your original command, based on what I think you're trying to do.

what is `powershell -c` or any execution parameters(e.g. powershell -nop -NonI)?

Apologize for the noob question but I did hours of research but still so confused...
The problem:
In powershell we can write this:
$i = 'hello'
echo $i # hello
easy. But:
powershell -c "$j = 'hello'; echo $j"
won't work and it throws error at our face.
The question: what is the error, and what is the correct grammar to use powershell -NoP -NonI -c "//..."? I see quite a few scripts written in this format. I even wonder if it is a linux thing...? but we are talking about powershell right?...
Any help would be appreciated.
It depends on where are you executing the command.
Inside cmd.exe this will work, because the commands don't render special meaning to cmd. But in powershell it will fail because of the special characters, use powershell -c '$j = ''hello''; echo $j' instead.
Also -c,-NoP etc. are parameters of powershell.exe:
PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
[-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
[-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
[-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
[-ConfigurationName <string>]
[-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
PowerShell[.exe] -Help | -? | /?
-PSConsoleFile
Loads the specified Windows PowerShell console file. To create a console
file, use Export-Console in Windows PowerShell.
-Version
Starts the specified version of Windows PowerShell.
Enter a version number with the parameter, such as "-version 2.0".
-NoLogo
Hides the copyright banner at startup.
-NoExit
Does not exit after running startup commands.
-Sta
Starts the shell using a single-threaded apartment.
Single-threaded apartment (STA) is the default.
-Mta
Start the shell using a multithreaded apartment.
-NoProfile
Does not load the Windows PowerShell profile.
-NonInteractive
Does not present an interactive prompt to the user.
-InputFormat
Describes the format of data sent to Windows PowerShell. Valid values are
"Text" (text strings) or "XML" (serialized CLIXML format).
-OutputFormat
Determines how output from Windows PowerShell is formatted. Valid values
are "Text" (text strings) or "XML" (serialized CLIXML format).
-WindowStyle
Sets the window style to Normal, Minimized, Maximized or Hidden.
-EncodedCommand
Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.
-ConfigurationName
Specifies a configuration endpoint in which Windows PowerShell is run.
This can be any endpoint registered on the local machine including the
default Windows PowerShell remoting endpoints or a custom endpoint having
specific user role capabilities.
-File
Runs the specified script in the local scope ("dot-sourced"), so that the
functions and variables that the script creates are available in the
current session. Enter the script file path and any parameters.
File must be the last parameter in the command, because all characters
typed after the File parameter name are interpreted
as the script file path followed by the script parameters.
-ExecutionPolicy
Sets the default execution policy for the current session and saves it
in the $env:PSExecutionPolicyPreference environment variable.
This parameter does not change the Windows PowerShell execution policy
that is set in the registry.
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
in Windows PowerShell. The results of the script block are returned to the
parent shell as deserialized XML objects, not live objects.
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
To write a string that runs a Windows PowerShell command, use the format:
"& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.
-Help, -?, /?
Shows this message. If you are typing a PowerShell.exe command in Windows
PowerShell, prepend the command parameters with a hyphen (-), not a forward
slash (/). You can use either a hyphen or forward slash in Cmd.exe.
EXAMPLES
PowerShell -PSConsoleFile SqlSnapIn.Psc1
PowerShell -version 2.0 -NoLogo -InputFormat text -OutputFormat XML
PowerShell -ConfigurationName AdminRoles
PowerShell -Command {Get-EventLog -LogName security}
PowerShell -Command "& {Get-EventLog -LogName security}"
# To use the -EncodedCommand parameter:
$command = 'dir "c:\program files" '
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand
-NoP is no profile means not load powershell profile.
-NonI is to run non-interactive session.
-c execute command/scriptblock and exit.

Dynamically rename a command prompt window title via Powershell

I have a powershell script which launches a ffmpeg command
$process = Start-Process -FilePath "cmd" -ArgumentList "/c c:\bin\ffmpeg\bin\ffmpeg.exe -rtsp_transport tcp -i........
This spawns a command prompt window.
I would like to rename the title of the command prompt window and be able to do that for every iteration I run of the ffmpeg command.
I have seen how to rename the title of the window directly via the command prompt and how to rename the powershell window title.
I cannot find any information pertaining to powershell being able to dynamically assign a new title to the command prompt window when created.
Any assistance/pointers would be greatly appreciated.
Once you pass your code off to the cmd instance you started it would be up to the running process to update it's title window (without getting into pinvoke/Windows API calls.) If ffmpeg.exe provides you with the current file as it's running then simply use that to set the title. If not, then it's most likely you'd need to adjust your commands to first get the list of files then iterate over those files setting the title and running the ffmpeg command. Here's a small example of letting the commands set the title.
Start-Process -FilePath "cmd" -ArgumentList "/c for /l %a in (1,1,10) do (title %a & cls & timeout 3)"
If you are instead referring to each time you do Start-Process then simply set the title before the other commands.
Start-Process -FilePath "cmd" -ArgumentList "/c title ffmpeg command running & c:\bin\ffmpeg\bin\ffmpeg.exe -rtsp_transport tcp -i........"
The & character instructs CMD to run the first command AND the next command. && says run the first command and only run the second if the first succeeds. || says run first command and if it fails run second.
By the way, unless you use the -Passthru on Start-Process then it is not collecting anything. With the passthru parameter it would collect a System.Diagnostics.Process object. That could be used for tracking, closing, etc.
$host.ui.RawUI.WindowTitle = "Changed Title"
Something like this?

Executing an EXE file using a PowerShell script with arguments for GCDS

I am new to windows and PowerShell on the admin level. I have experience in Linux and prefer using Python but I have a difficult time understanding windows environments. In bash and Linux I am used to running shell scripting with cronjobs but in Windows, I'm having an issue running this command in the Task Scheduler. I need to be able to run Google Cloud Directory Sync so that our AD is in sync with Gsuite. I wrote a batch file that works but I feel its a bit dated to use a bat file
cd C:\Program Files\Google Apps Directory Sync\
sync-cmd.exe -a -o -c config.xml
my best guess is this needs to run as a PowerShell script through task scheduler, but I don't know where to start. I found this so far but I get an error that I don't know how to interpret.
Start-Process sync-cmd.exe -ArguementList "-a -o -c C:\Somepath\config.xml"
sorry for being a noob thanks in advance!
Also for an additional resource here's the GCDS command page.
https://support.google.com/a/answer/6152425?hl=en
Your error indicates that Start-Process does not have a parameter called ArguementList. You can use Get-Help to get a list of available parameters.
Get-Help Start-Process -Parameter * | Select-Object Name
Indeed ArguementList is not available, but ArgumentList is available. There simply is a typo in your command.
The following should work just fine:
Start-Process sync-cmd.exe -ArgumentList "-a -o -c C:\Somepath\config.xml"
Option 1 - Schedule your EXE directly through Task Scheduler
No need for powershell. You can just provide the full path to the EXE and the arguments using the Windows Task Scheduler User Interface. You can specify a working folder using the Start in option.
Option 2 - Schedule a PowerShell script using Task Scheduler
I find using the -File option of PowerShell.exe very useful when scheduling a PowerShell script using Task Scheduler. In this case, I would use the cmdlet Start-Process and I would encapsulate the arguments inside the PowerShell script.
Example
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -File "c:\MyScript.ps1"
MSDN
https://learn.microsoft.com/en-us/powershell/scripting/components/console/powershell.exe-command-line-help?view=powershell-6
Syntax
PowerShell[.exe]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
[-EncodedCommand <Base64EncodedCommand>]
[-ExecutionPolicy <ExecutionPolicy>]
[-File <FilePath> [<Args>]]
[-InputFormat {Text | XML}]
[-Mta]
[-NoExit]
[-NoLogo]
[-NonInteractive]
[-NoProfile]
[-OutputFormat {Text | XML}]
[-PSConsoleFile <FilePath> | -Version <PowerShell version>]
[-Sta]
[-WindowStyle <style>]
PowerShell[.exe] -Help | -? | /?
Example from my laptop
Passing arguments through Start-Process
If you are using Start-Process then you can pass an array of arguments through a comma delimited string.
PS C:\> Start-Process -FilePath "$env:comspec" -ArgumentList "/c dir `"%systemdrive%\program files`""
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-6
I discovered that PowerShell is pretty similar to python and bash with variables. This runs as a script that I then attach to Task Scheduler.
$msbuild = "C:\Program Files\Google Apps Directory Sync\sync-cmd.exe"
$arguments = "-a -o -c config.xml"
start-Process -FilePath $msbuild $arguments

How to execute Windows command (Get-Content) from PowerShell in Windows Server

My server is Windows Server. I would like to replicate the Unix tail command in Windows Server.
Unix Server: tail -f test.txt
PowerShell: Get-Content test.txt
How to execute in Windows Server?
Below command is not working:
powershell -File "Get-Content test.txt"
Error message:
Unable to execute program 'powershell -File "\"Get-Content...
Any idea?
Get-Content is not a file; it is a cmdlet. The -file parameter to Powershell.exe instructs Powershell to read the file supplied and execute the commands in it, as a script.
You can pass commands directly to Powershell by using the -command parameter; the parameter can be a quoted string, which is interpreted as a Powershell command. You would therefore want to use
powershell -command "Get-Content test.txt"
in the simplest case.
Note that Powershell.exe must be in your system path; if it is not, you would need to supply the full path to powershell, e.g.,
C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -command "Get-Content text.txt"
This question is very similar - perhaps essentially identical - to Unix tail equivalent command in Windows Powershell; I would recommend reading that question and its answers as well.
Additionally, exploring the help for Get-Content will provide useful information.
Working fine after setting full path of powershell.exe and without any quotes
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command Get-Content test.txt
Within a powershell window :
Get-Content test.txt
command returns :
hello world.
i'm inside test.txt.
bye.

Resources