How to execute a Powershell (.ps1) file in Autohotkey? - autohotkey

Run, powershell.exe C:\Users\user1\PoweShell\Duplicate Selected Files.ps1
Running the above example just opens the blue powershell CMD window and it quickly flashes, the script does not run.
Running the below example opens the blue powershell CMD window and keeps it open, the script does not run.
Run, powershell.exe /k C:\Users\user1\AppLib\Executables\PoweShell\Duplicate Selected Files.ps1
I should mention in file explorer, double clicking a .ps1 file opens it in notepad, I should like to keep this behaviour. I can achieve the same in Autohotkey with:
Run, C:\Users\user1\AppLib\Executables\PoweShell\Duplicate Selected Files.ps1
I can execute .ps1 script files in file explorer by rich clicking and choosing Run with Powershell. How can I achieve this same result in Autohotkey?
PS: I know I can run Poweshell directly in Autohotkey with RunWait, powershell.exe -NoExit -Command "Something here..." I really need to how to execute .ps1 files saved to folders.
Any help would be greatly appreciated!
I have taken the liberty to crosspost this question on other forums as well.

First Way
Create a variable to store the path to ps1 script.
strPsScriptFile := "F:\psScript\test.ps1"
Run the powershell script as below, use Runwait to keep the shell open
Run, PowerShell.exe -NoExi -ExecutionPolicy Bypass -Command %strPsScriptFile%
Incase you want to pass parameters to ps1 script. Ex: pass a Name as first and age as second
Run, PowerShell.exe -NoExi -ExecutionPolicy Bypass -Command %strPsScriptFile% " Chanu 10"
Second Way
; hide the terminal
DetectHiddenWindows, On
;path to ps1
Path_To_File := "test.ps1"
Target := "PowerShell.exe -ExecutionPolicy Bypass -File " PathToFile
; terminal location
vComSpec := A_ComSpec ? A_ComSpec : ComSpec
;run the terminal
Run, % vComSpec,, Hide, vPID
WinWait, % "ahk_pid " vPID
DllCall("kernel32\AttachConsole", "UInt",vPID)
oShell := ComObjCreate("WScript.Shell")
oExec := oShell.Exec(Target)
vStdOut := ""
while !oExec.StdOut.AtEndOfStream{
; you can read the the output till the execution ends
}
DllCall("kernel32\FreeConsole")
Process, Close, % vPID
Reference :
https://www.autohotkey.com/docs/
https://www.reddit.com/r/AutoHotkey/comments/ey3pmb/get_hidden_cmdpowershell_output/

Related

How to run powershell script from .ps1 file?

I'm trying to automate the execution of a simple PS script (to delete a certain .txt file). Obviously, I'm new to powershell :)
When I run the code in shell, it works flawless. But when i save the code as a .ps1 and double-click it (or execute it remotely), it just pops up a window and does nothing.
I've tried to save the code as a .bat file and execute it on Windows command line, but it behaves the same: Works by coding directly on prompt, but doesn't Works by executing the .bat file.
$Excel = New-Object -ComObject Excel.Application
$Workbook = $Excel.Workbooks.Open('H:\codes\test1.xlsm')
$workSheet = $Workbook.Sheets.Item(2)
$str_name = $WorkSheet.Cells.Item(2,1).Text
Remove-Item -Path "H:\text files\$str_name.txt" -Force
I expected it to work by double-clicking it, just as it does by running in shell, or in the command line, but i can't figure out why it doesn't.
Create a batch file which points at your .ps1 file. You may be required to run the batch file with elevated permissions, depending on your access levels (the logged in account will be used for execution).
E.g.:
Powershell.exe -executionpolicy remotesigned -File "C:\Path\script.ps1"
If this still isn't working, please execute your batch file via CMD (copying the path, wrapped in quotation marks, into CMD) and let me know the response.
There are several ways to run a .ps1 file. The simplest way is to right-click the file and choose 'Run with PowerShell'.
As others have suggested, you can also run your .ps1 file using powershell.exe either in command prompt or from a BATCH or CMD file. As follows:
powershell.exe -File C:\Script.ps1
If you are still having problems it could be the execution policy. For this, simply add -ExecutionPolicy Bypass to your command as follows:
powershell.exe -File C:\Script.ps1 -ExecutionPolicy Bypass
To change your execution policy you can use:
Set-ExecutionPolicy

PowerShell in Task Manager Shows Window

I am trying to make Task Schedule Task so it is completely invisible that a PowerShell script is running so I created a Task on my Win10 machine configured as follows:
Program/Script:
powershell.exe
Add arguments (optional):
-WindowStyle Hidden -command "& {Out-File 'C:\temp\somefile.txt'}" -NonInteractive -NoLogo -NoProfile
When I run this task the powershell command windows pops up for a split second which I don't want.
You can get around this with an 'Application Host' type wrapper. This is a known issue with powershell as a console-based host.
The most convenient way to do this I've found, is to use WScript.exe and run a VBS script that will invoke the process "invisibly", with no console or task bar flicker.
VBS Code:
On Error Resume Next
ReDim args(WScript.Arguments.Count-1)
For i = 0 To WScript.Arguments.Count-1
If InStr(WScript.Arguments(i), " ") > 0 Then
args(i) = Chr(34) & WScript.Arguments(i) & Chr(34)
Else
args(i) = WScript.Arguments(i)
End If
Next
CreateObject("WScript.Shell").Run Join(args, " "), 0, False
Save the above code in a file with extension '.vbs', and place it somewhere it can be run by the client running the task. This may be in a protected fileshare on the network (if you expect the script it invokes to only run while connected to the network), or locally on the client.
Now when you invoke your console-based script (PowerShell, BAT, CScript, etc.), you invoke this VBS script with WScript explicitly WScript.exe. It also pays to throw on the 'Batch Mode' parameter //B which will suppress script errors & prompts - such as if the wrapper file itself can't be found.
At this point, all you need to do is pass powershell & the command you want powershell to run to this launch sequence:
WScript.exe //B "\\Path\To\Launcher.VBS" powershell.exe -ExecutionPolicy ByPass -file "\\Powershell\Script\To\Run"
I had the same problem, it was resolved at the simple way.
When you create a Task on Windows, just set this configuration:
Open Properties dialog;
Then you check Run whether user is logged on or not;
You can check Do not store password to avoid asking for PC password on Task execution;
In Add arguments (optional): just:
-File 'C:\temp\somefile.txt
This spcript will run without popup the prompt.
Solved in this link below:
https://stackoverflow.com/a/50630717/19926325

Get bat file to contiune when lauching PowerShell

I have a bat file that is launching a powerShell script. I would like for the bat file to keep moving after it launches the script and not wait for the powerShell script to complete. Every time right now when i launch the powerShell script the bat files waits till the powerShell script finishes before it moves on. Here is how I'm calling my powerShell script:
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "&'C:\Users\sharph\Desktop\test.ps1'"
SS64 'start' help page
You'll want to start it with the start command, like this;
start "" "PowerShell"
This will start a program without waiting for it to close, although that behavior can be re-added with the /w or /wait option. The blank "" is in place of the title, not always needed but generally a safe thing to add.
Perhaps this will work?
start "" "PowerShell" -NoProfile -ExecutionPolicy Bypass -Command "^& 'C:\Users\sharph\Desktop\test.ps1'"
of course, the & had to be delimited to ^&.

Running script on selected folder/drive using right click on windows explorer

Environment: Windows 7
With the help of straight forward article from Scott, I am able to have "PowerShell Here" as the right click item of windows explorer.
Right clicking "PowerShell Here" opens a powershell command prompt with selected folder as the current working directory.
But I want little bit different which I am not able to do - inplace of opening the powershell prompt, I want to run a powershell script taking argument as the selected drive/folder/filename!
So, I updated the following line of "powershellhere.inf" file,
;existing one
;HKCR,Drive\Shell\PowerShellHere\command,,,"""C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe"" -NoExit ""cd '%1'"""
;updated one, added -Command <ScriptFile>
HKCR,Drive\Shell\PowerShellHere\command,,,"""C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe"" -Command d:\temp.ps1 -NoExit ""cd '%1'"""
But when I right click and select the "PowerShell Here", it's not running the script in the selected drive/folder/file, it's running in C:\Windows\System32 folder.
The string I believe you are looking for:
"""C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe"" -NoExit -File ""C:\temp\test.ps1"" ""'%1'"""
-NoExit had to be before the -File else it was being picked up as an argument to the ps1 file. Also you need to put a full file path. I'm sure you could use environment variables. In my script i just had Write-Host $args[0] which output the path.
I was having an issue with the path being passed at first. I think the single quotes were not the ones I expected them to be inside the script. My script now changes directory successfully. Contents of test.ps1
$location = $args[0].Trim("'")
Write-Host "Path is valid = $(Test-Path $location)"
Set-Location $location
Use -File instead of -Command and get rid of the cd stuff:
HKCR,Drive\Shell\PowerShellHere\command,,,"""C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe"" -File d:\temp.ps1 -NoExit
-Command is for literal commands on the command line. You may also want to set the -ExecutionPolicy if you have an issue with that.
If you don't want the prompt to stick around after executing the script, get rid of -NoExit.

How to execute a PowerShell script from Notepad++

I am using Notepad++ to edit a PowerShell file and want to be able to execute that file from inside Notepad++.
How can I set that up?
It took me a little fiddling, but I finally got this working. (I am using version 1.0 but this should work in other versions as well.)
Notepad++ can be set up to run commands, and assign shortcuts to those commands, as follows:
From the menu, click Run → Run
Add the command
C:\NotepadRun.bat "$(FULL_CURRENT_PATH)"
Save the command, giving it a name and a key shortcut.
Below are the contents of the batch file. I named mine NotepadRun.bat, but you can name it whatever.
#echo off
GOTO %~sx1
:.ps1
cd "%~d1%~p1"
powershell.exe .\%~n1%~sx1
GOTO end
:.rb
ruby "%~f1"
GOTO end
:.php
php "%~f1"
GOTO end
:end
pause
As a note upgrading to Windows7 and Powershell 2 I found some Issues with this and have updated to passing in an ExecutionPolicy to ensure I can run the script I am editing.
:.ps1
cd "%~d1%~p1"
powershell -ExecutionPolicy Unrestricted -File "%~n1%~sx1"
GOTO end
See Using Notepad++ to Compile and Run Java Programs and replace "javac" with "C:Windows\system32\WindowsPowerShell\v1.0\powershell.exe" (or your path to PowerShell). (Caveat: I'm not a Notepad++ user and haven't tried this.)
That said, I'd just use PowerShell ISE (installs with PowerShell) or one of the other dedicated PowerShell IDEs instead.
I would recommend using PowerShell ISE which comes as part of PowerShell and designed specifically for Powershell.
You can run a saved script from "Run" -> "Run" menu in Notepad++ with the following command:
powershell.exe -noexit -command . \"$(FULL_CURRENT_PATH)\"
Based on the answers before:
powershell.exe -ExecutionPolicy Unrestricted -NoLogo -File "$(FULL_CURRENT_PATH)"
You can also add the -NoExit parameter to keep PowerShell from closing automatically:
powershell.exe -ExecutionPolicy Unrestricted -NoExit -NoLogo -File "$(FULL_CURRENT_PATH)"
Note: File has to be saved.