Running PowerShell Scripts in Komodo Edit - powershell

I have a hard time trying to run PowerShell Scripts from the "Run Command" within Komodo Edit on Windows 7.
The command that I am using is:
powershell -File "%F"
When I run it, it does not return anything to the console, it just keeps running till I terminate it.
I have tested it, with the following simple script:
Write-Host "Hello World"

This is a known issue where powershell.exe waits for a STDIN prompt to return in certain cases, causing it to hang when no input is provided.
Solutions
Use -InputFormat None to indicate STDIN will not be used:
powershell.exe -InputFormat None -File "%F"
Forward null input from the outer command scope so that STDIN returns:
powershell.exe -File "%F" < NUL
Similar Questions
2010-11-09 Silently executing a PowerShell script from WiX Hangs PowerShell
2010-11-21 Running PowerShell from MSdeploy runcommand does not exit
2011-07-26 Exiting VMware vSphere PowerCLI command prompt?

Related

how to exec ps1 file from cmd?

I have a ps1 file, Test.ps1, which I need to exec from cmd. For test purposes this file only has 1 line:
write "ps1 test successful"
I was trying to exec this ps1 file from cmd. I googled and it seemed that including the following line might help:
Set-ExecutionPolicy RemoteSigned
write "ps1 test successful"
However I still can't exec this test. I've tried:
powershell Test
powershell Test.ps1
Test
Test.ps1
The cmd path context is set to the dir in which the ps1 script resides. Any idea what I might be doing wrong here?
Does this work?
Powershell -ExecutionPolicy Bypass -File .\Test.ps1
I've done this before with a .bat file, and this was the syntax used. In this instance, you're running from within the same directory as the powershell script (otherwise adjust the filename argument as necessary). And you may need to be running the CMD prompt as admin, if you aren't already.
Use
powershell.exe -ExecutionPolicy Bypass -File "C:\dir name\test.ps1"
Of course, replace C:\dir name\test.ps1 with the path and filename of the script you want to run, enclosed in " (double quotes).
Alternatively, start PowerShell in its own window, then run the script.
On macOS:
Use Homebrew to install Powershell:
brew install --cask powershell
Switch to Powershell:
pwsh
Execute the script:
./Test.ps1
My PowerShell script (Test.ps1):
echo "trying to test something"
I can execute it in cmd with this command:
.\Test.ps1
My output:
trying to test something

Powershell equivalent of the "tail" command ALMOST works remotely

I am looking for a Windows 7 equivalent of the "tail" command and thought I had found it with this Powershell equivalent -
C:\>powershell -command "& {Get-Content file.txt | Select-Object -last 100}"
If I use this in the CMD prompt on my own Windows 7 PC, returns the info just fine. I can even input/append it into another file.
However, when I log on remotely to another PC (via openSSH), the command works, but it never drops me back to a command prompt - just hangs after showing me the last 100 lines of the file. Which means this won't work for a batch file I'm trying to edit for about 300 remote Windows 7 PCs.
Any ideas?
After trying MANY different suggestions found all over online, FINALLY found one that worked!
And the answer is within the Batch file itself. My batch file to call this Powershell line was just this:
Powershell.exe -noprofile -executionpolicy Bypass C:\log\Tail.ps1
:end
Again, works great if you're using it on the very PC from which you want it to run/get the information. But not remotely. Finally found you just need to add "< nul" to the end of your call to Powershell in your batch file, just like this
Powershell.exe -noprofile -executionpolicy Bypass C:\log\Tail.ps1 <nul
:end
What the other person wrote is what finally made sense: "My research has shown that PowerShell runs the commands in the script indicated through the -File switch and then waits for additional PowerShell commands from the standard input (my brief experimentation with the -Command switch demonstrated similar behavior). By redirecting the standard input to nul, once PowerShell finishes executing the script and 'reads end-of-file' from the standard input, PowerShell exits."
Found here at this page - Powershell script gets stuck, doesn't exit when called from batch file
so credit actually goes to #Gordon Smith
Since your running the command with -command "...", according to the docs, you need to specify the -noexit flag to stop powershell from exiting after the command is run.
powershell -command "& {Get-Content file.txt | Select-Object -last 100}" -noexit
When you add this to a batch file you'll probably need -noprofile and -noninteractive as well - though for remote commands you might want to spawn a process for better control and error handling. Also, if this doesn't work the problem would probably be with how OpenSSH is handling something (this worked for me on a test-server with remote connect)

Running CMD command in PowerShell

I am having a bunch of issues with getting a PowerShell command to run. All it is doing is running a command that would be run in a CMD prompt window.
Here is the command:
"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME
I have tried the following with no success (I have tried many iterations of this to try and get one that works. Syntax is probably all screwed up):
$TEXT = $textbox.Text #$textbox is where the user enters the PC name.
$CMDCOMMAND = "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe"
Start-Process '"$CMDCOMMAND" $TEXT'
#iex -Command ('"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe"' $TEXT)
The command will just open SCCM remote connection window to the computer the user specifies in the text box.
Try this:
& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME
To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.
To run or convert batch files externally from PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, e.g. deletefolders.ps1.
Input the following into the script:
cmd.exe /c "rd /s /q C:\#TEMP\test1"
cmd.exe /c "rd /s /q C:\#TEMP\test2"
cmd.exe /c "rd /s /q C:\#TEMP\test3"
*Each command needs to be put on a new line calling cmd.exe again.
This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd directly.
It is a much safer way than running batch files!
One solution would be to pipe your command from PowerShell to CMD. Running the following command will pipe the notepad.exe command over to CMD, which will then open the Notepad application.
PS C:\> "notepad.exe" | cmd
Once the command has run in CMD, you will be returned to a PowerShell prompt, and can continue running your PowerShell script.
Edits
CMD's Startup Message is Shown
As mklement0 points out, this method shows CMD's startup message. If you were to copy the output using the method above into another terminal, the startup message will be copied along with it.
For those who may need this info:
I figured out that you can pretty much run a command that's in your PATH from a PS script, and it should work.
Sometimes you may have to pre-launch this command with cmd.exe /c
Examples
Calling git from a PS script
I had to repackage a git client wrapped in Chocolatey (for those who may not know, it's a package manager for Windows) which massively uses PS scripts.
I found out that, once git is in the PATH, commands like
$ca_bundle = git config --get http.sslCAInfo
will store the location of git crt file in $ca_bundle variable.
Looking for an App
Another example that is a combination of the present SO post and this SO post is the use of where command
$java_exe = cmd.exe /c where java
will store the location of java.exe file in $java_exe variable.
You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.
If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock option.

TeamCity Powershell Runner - Unable to run Source Code

Im trying to run some PS scripts using the Powershell Runner in TC and defining my own script as "Source Code" instead of a script file.
My script is as simple as:
"Hello World!"
Im running on Windows Server 2008 R2 and ive tried with to:
Run it as x86 + x64
Using "Execute .ps1 with '-File' argument" + "Put script into powershell stdin with "-Command -" arguments.
Ive set the security policy to Unrestricted in an attempt to get it to work, but no luck.
If I instead use a Command Line runner and for example writes:
powershell -Command Get-ExecutionPolicy
It works fine.
The errors im getting (depending on which of the 2 execution modes im using) are:
Starting: C:\...\cmd.exe /c C:\...\powershell.exe -NonInteractive -Command
- "<C:\...\powershell3889347351955805274.ps1" && exit /b %ERRORLEVEL%
in directory: C:\...\e18dda4054c166c7
'-' was specified with the -Command parameter; no other arguments to -Command are permitted.
OR
Starting: C:\...\cmd.exe /c C:\...\powershell.exe -NonInteractive -File
"C:\...\powershell8264270201473986040.ps1" && exit /b %ERRORLEVEL%
in directory: C:\...\e18dda4054c166c7
The term 'f' is not recognized as the name of a cmdlet, function, script file,
It looks to me like TC puts something in the actual script itself, but im not sure. Im stuck and I cant figure out what point im missing here :S.
Can anyone help?
I wasn't able to reproduce this, but I noticed something pretty weird with the command that TeamCity was trying to run:
-NonInteractive -Command - "<C:\...\powershell3889347351955805274.ps1"
I did not see it adding the quotes for me, so I thought maybe TeamCity is trying to quote a path with space(s) in it ( would have helped if you hadn't redacted your path)
So I switched my agent to a path with a space in it and I got the same command, and yes, the same error. So TeamCity is quoting the path wrongly. It is including the < in the quotes while it should have been <"c:\path with\space"
I will see if I can file a bug for this ( if there isn't one)
Try moving your agent to a non-space path as a workaround.

How to return an exit code from a Powershell script only when run non-interactively

I have a lot of scripts that are running as scheduled tasks. So they do a $host.setshouldexit(1) on any failure, which shows up in the task scheduler as the return code.
I also want to be able to run these scripts interactively while debugging and testing. So the $host.setshouldexit() kills my powershell or ISE session.
My question is: how can I detect if a script is running non-interactively? If it is, then I'll use setshouldexit, otherwise it will print the error code or something nondestructive. (Note that I don't want to use [environment]::userinteractive because these scripts are not always running in what the OS thinks is a non-interactive session.)
There is a -noninteractive switch that I'm using for the scheduled tasks. Is there some way I can query that from powershell?
The $Host.SetShouldExit method should not be necessary, and is actually inconsistent, depending on how you are calling your scripts. Using the keyword exit should get you your exit status.
Using powershell -F script.ps1:
exit - works
SetShouldExit - ignored
Using powershell -c '.\script.ps1':
exit - status reduced to 0 or 1, for success or failure of the script, respectively.
SetShouldExit - exits with correct status, but remaining lines in script are still run.
Using powershell -c '.\script.ps1; exit $LASTEXITCODE' [1]:
exit - works
SetShouldExit - exits with status == 0, and remaining lines in script are still run.
Calling directly from powershell (> .\script.ps1):
exit - works
SetShouldExit - terminates calling powershell host with given exit status
Why not just have it take a parameter "testing" which sets the right behavior during your tests? You have a history buffer so it will be hardly any more typing to run.
I had the same issue. The following works for me:
# Exit with Return Code when NOT using PowerShell ISE
if ($psise -eq $Null)
{
$host.SetShouldExit(1)
}
Upon finding your question I have taken the issue a bit further and found $MyInvocation.MyCommand.Name. This is False in both the command interpreter and the ISE command interpreter. And when a script (mine is jest.ps1) containing just the line: Write-Host $MyInvocation.MyCommand.Name is run from cmd.exe call to powershell.exe as:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -NoExit -NonInteractive -NoProfile -File "M:\WindowsPowerShell\Jest.ps1"
Output is simply:
Jest.ps1
Check $Host.Name. If your script is running outside of an IDE, it will return a value of ConsoleHost. Otherwise it will return a reference to the IDE such as Windows PowerShell ISE Host or PowerGUIScriptEditorHost.
I have to use SetShouldExit because the scheduler that runs my scripts usually ignores other methods of indicating a failure. I add a function to allow SetShouldExit when $Host.Name is ConsoleHost. It saves a lot of IDE crashes during testing.
This directly answers the question poster had about whether or not you can query if the powershell console was launched with -NonInteractive switch.
Function Test-IsPowerShellConsoleNonInteractive { [Boolean]([Environment]::GetCommandLineArgs() -Match '-NonInteractive') }
$IsPSConsoleNonInteractive = Test-IsPowerShellConsoleNonInteractive
If ($IsPSConsoleNonInteractive) { $Host.SetShouldExit(2) }