Hide or Minimize the powershell prompt after Winform Launch - powershell

I have written a simple powershell script to launch a winform(Winform code written within powershell script for example showContent.ps1 file) & showing some content.
I need to hide the powershell.exe command prompt after the launch of the Winform.
After searching some cases in web, I tried below Scenario:
1)I tried to execute "powershell.exe -Command -windowstyle Hidden" in the start of the script file "showContent.ps1"
2) Created a new script file exa:LaunchWinForm.ps1 and in that mentioned the command as:
PowerShell.exe -windowstyle Hidden showContent.ps1
It is not working.
I am using Powershell 3.0
Could anyone tell what is going wrong or suggest any way to do it.

In the new separate script file you created, try this:
powershell.exe -WindowStyle Hidden -File "c:\path\to the\GUI_Script.ps1"

This solution Minimizes Powershell window after it starts. Powershell window opens, then disapears, without using any outside code. I put at beginning of my scripts, but sounds like you want to put the code after you open your form.
$t = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);'
add-type -name win -member $t -namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0)

Related

Run Powershell Encoded Command, single .vbs file, no third-party tools [duplicate]

How is it possible to run a PowerShell script without displaying a window or any other sign to the user?
In other words, the script should run quietly in the background without any sign to the user.
Extra credit for an answer that does not use third party components :)
You can either run it like this (but this shows a window for a while):
PowerShell.exe -WindowStyle hidden { your script.. }
Or you use a helper file I created to avoid the window called PsRun.exe that does exactly that. You can download the source and exe file from Run scheduled tasks with WinForm GUI in PowerShell. I use it for scheduled tasks.
Edited: as Marco noted this -WindowStyle parameter is available only for V2 and above.
I was having this same issue. I found out if you go to the Task in Task Scheduler that is running the powershell.exe script, you can click "Run whether user is logged on or not" and that will never show the powershell window when the task runs.
You can use the PowerShell Community Extensions and do this:
start-process PowerShell.exe -arg $pwd\foo.ps1 -WindowStyle Hidden
You can also do this with VBScript: http://blog.sapien.com/index.php/2006/12/26/more-fun-with-scheduled-powershell/
Schedule Hidden PowerShell Tasks (Internet Archive)
More fun with scheduled PowerShell (Internet Archive)
(Via this forum thread.)
The answer with -WindowStyle Hidden is great but the windows will still flash.
I've never seen a window flash when calling it via cmd /c start /min "".
Your machine or setup may differ but it works well for me.
1. Call a file
cmd /c start /min "" powershell -WindowStyle Hidden -ExecutionPolicy Bypass -File "C:\Users\username\Desktop\test.ps1"
2. Call a file with arguments
cmd /c start /min "" powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command ". 'C:\Users\username\Desktop\test me.ps1' -Arg1 'Hello' -Arg2 'World'"ps1'; -Arg1 'Hello' -Arg2 ' World'"
Powershell content for 2. Call a file with arguments is:
Param
(
[Parameter(Mandatory = $true, HelpMessage = 'The 1st test string parameter.')]
[String]$Arg1,
[Parameter(Mandatory = $true, HelpMessage = 'The 2nd test string parameter.')]
[String]$Arg2
)
Write-Host $Arg1
Write-Host $Arg2
3. Call a file with a function and arguments
cmd /c start /min "" powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command ". 'C:\Users\username\Desktop\test me.ps1'; Get-Test -stringTest 'Hello World'"
Powershell content for 3. Call a file with a function and arguments is:
function Get-Test() {
[cmdletbinding()]
Param
(
[Parameter(Mandatory = $true, HelpMessage = 'The test string.')]
[String]$stringTest
)
Write-Host $stringTest
return
}
In case you need to run this in Task Scheduler then call %comspec% as the Program/Script and then code for calling the file above as the argument.
Note: All examples work when the PS1 file has spaces in its path.
Here's an approach that that doesn't require command line args or a separate launcher. It's not completely invisible because a window does show momentarily at startup. But it then quickly vanishes. Where that's OK, this is, I think, the easiest approach if you want to launch your script by double-clicking in explorer, or via a Start menu shortcut (including, of course the Startup submenu). And I like that it's part of the code of the script itself, not something external.
Put this at the front of your script:
$t = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);'
add-type -name win -member $t -namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0)
Here's a one-liner:
mshta vbscript:Execute("CreateObject(""Wscript.Shell"").Run ""powershell -NoLogo -Command """"& 'C:\Example Path That Has Spaces\My Script.ps1'"""""", 0 : window.close")
Although it's possible for this to flash a window very briefly, that should be a rare occurrence.
ps1 hidden from the Task Scheduler and shortcut too
mshta vbscript:Execute("CreateObject(""WScript.Shell"").Run ""powershell -ExecutionPolicy Bypass & 'C:\PATH\NAME.ps1'"", 0:close")
I think that the best way to hide the console screen of the PowerShell when your are running a background scripts is this code ("Bluecakes" answer).
I add this code in the beginning of all my PowerShell scripts that I need to run in background.
# .Net methods for hiding/showing the console in the background
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
function Hide-Console
{
$consolePtr = [Console.Window]::GetConsoleWindow()
#0 hide
[Console.Window]::ShowWindow($consolePtr, 0)
}
Hide-Console
If this answer was help you, please vote to "Bluecakes" in his answer in this post.
I was having this problem when running from c#, on Windows 7, the "Interactive Services Detection" service was popping up when running a hidden powershell window as the SYSTEM account.
Using the "CreateNoWindow" parameter prevented the ISD service popping up it's warning.
process.StartInfo = new ProcessStartInfo("powershell.exe",
String.Format(#" -NoProfile -ExecutionPolicy unrestricted -encodedCommand ""{0}""",encodedCommand))
{
WorkingDirectory = executablePath,
UseShellExecute = false,
CreateNoWindow = true
};
Here's a fun demo of controlling the various states of the console, including minimize and hidden.
Add-Type -Name ConsoleUtils -Namespace WPIA -MemberDefinition #'
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'#
$ConsoleMode = #{
HIDDEN = 0;
NORMAL = 1;
MINIMIZED = 2;
MAXIMIZED = 3;
SHOW = 5
RESTORE = 9
}
$hWnd = [WPIA.ConsoleUtils]::GetConsoleWindow()
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.MAXIMIZED)
"maximized $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.NORMAL)
"normal $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.MINIMIZED)
"minimized $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.RESTORE)
"restore $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.HIDDEN)
"hidden $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.SHOW)
"show $a"
When you scheduled task, just select "Run whether user is logged on or not" under the "General" tab.
Alternate way is to let the task run as another user.
Create a shortcut that calls the PowerShell script and set the Run option to Minimized. This will prevent a window from flashing although you will still get a momentary blip of the script running on the Task Bar.
For easy command line usage, there is a simple wrapper app:
https://github.com/stax76/run-hidden
Example command line:
run-hidden powershell -command calc.exe
I got really tired of going through answers only to find it did not work as expected.
Solution
Make a vbs script to run a hidden batch file which launches the powershell script. Seems silly to make 3 files for this task but atleast the total size is less than 2KB and it runs perfect from tasker or manually (you dont see anything).
scriptName.vbs
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:\Users\leathan\Documents\scriptName.bat" & Chr(34), 0
Set WinScriptHost = Nothing
scriptName.bat
powershell.exe -ExecutionPolicy Bypass C:\Users\leathan\Documents\scriptName.ps1
scriptName.ps1
Your magical code here.
I have created a small tool passing the call to any console tool you want to start windowless through to the original file:
https://github.com/Vittel/RunHiddenConsole
After compiling just rename the executable to "<targetExecutableName>w.exe" (append a "w"), and put it next to the original executable.
You can then call e.G. powershellw.exe with the usual parameters and it wont pop up a window.
If someone has an idea how to check whether the created process is waiting for input, ill be happy to include your solution :)
Wait until Powershell is executed and get the result in vbs
This is an improved version of the Omegastripes code Hide command prompt window when using Exec()
Splits the confused responses from cmd.exe into an array instead of putting everything into a hard-to-parse string.
In addition, if an error occurs during the execution of cmd.exe, a message about its occurrence will become known in vbs.
Option Explicit
Sub RunCScriptHidden()
strSignature = Left(CreateObject("Scriptlet.TypeLib").Guid, 38)
GetObject("new:{C08AFD90-F2A1-11D1-8455-00A0C91F3880}").putProperty strSignature, Me
objShell.Run ("""" & Replace(LCase(WScript.FullName), "wscript", "cscript") & """ //nologo """ & WScript.ScriptFullName & """ ""/signature:" & strSignature & """"), 0, True
End Sub
Sub WshShellExecCmd()
For Each objWnd In CreateObject("Shell.Application").Windows
If IsObject(objWnd.getProperty(WScript.Arguments.Named("signature"))) Then Exit For
Next
Set objParent = objWnd.getProperty(WScript.Arguments.Named("signature"))
objWnd.Quit
'objParent.strRes = CreateObject("WScript.Shell").Exec(objParent.strCmd).StdOut.ReadAll() 'simple solution
Set exec = CreateObject("WScript.Shell").Exec(objParent.strCmd)
While exec.Status = WshRunning
WScript.Sleep 20
Wend
Dim err
If exec.ExitCode = WshFailed Then
err = exec.StdErr.ReadAll
Else
output = Split(exec.StdOut.ReadAll,Chr(10))
End If
If err="" Then
objParent.strRes = output(UBound(output)-1) 'array of results, you can: output(0) Join(output) - Usually needed is the last
Else
objParent.wowError = err
End If
WScript.Quit
End Sub
Const WshRunning = 0,WshFailed = 1:Dim i,name,objShell
Dim strCmd, strRes, objWnd, objParent, strSignature, wowError, output, exec
Set objShell = WScript.CreateObject("WScript.Shell"):wowError=False
strCmd = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass Write-Host Hello-World."
If WScript.Arguments.Named.Exists("signature") Then WshShellExecCmd
RunCScriptHidden
If wowError=False Then
objShell.popup(strRes)
Else
objShell.popup("Error=" & wowError)
End If
powershell.exe -windowstyle hidden -noexit -ExecutionPolicy Bypass -File <path_to_file>
then set the run: Minimized
should work as expected without added code for hidden window flash
just slightly more delayed execution.
Here is a working solution in windows 10 that does not include any third-party components. It works by wrapping the PowerShell script into VBScript.
Step 1: we need to change some windows features to allow VBScript to run PowerShell and to open .ps1 files with PowerShell by default.
-go to run and type "regedit". Click on ok and then allow it to run.
-paste this path "HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell" and press enter.
-now open the entry on the right and change the value to 0.
-open PowerShell as an administrator and type "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned", press enter and confirm the change with "y" and then enter.
Step 2: Now we can start wrapping our script.
-save your Powershell script as a .ps1 file.
-create a new text document and paste this script.
Dim objShell,objFSO,objFile
Set objShell=CreateObject("WScript.Shell")
Set objFSO=CreateObject("Scripting.FileSystemObject")
'enter the path for your PowerShell Script
strPath="c:\your script path\script.ps1"
'verify file exists
If objFSO.FileExists(strPath) Then
'return short path name
set objFile=objFSO.GetFile(strPath)
strCMD="powershell -nologo -command " & Chr(34) & "&{" &_
objFile.ShortPath & "}" & Chr(34)
'Uncomment next line for debugging
'WScript.Echo strCMD
'use 0 to hide window
objShell.Run strCMD,0
Else
'Display error message
WScript.Echo "Failed to find " & strPath
WScript.Quit
End If
-now change the file path to the location of your .ps1 script and save the text document.
-Now right-click on the file and go to rename. Then change the filename extension to .vbs and press enter and then click ok.
DONE! If you now open the .vbs you should see no console window while your script is running in the background.
c="powershell.exe -ExecutionPolicy Bypass (New-Object -ComObject Wscript.Shell).popup('Hello World.',0,'ะžะš',64)"
s=Left(CreateObject("Scriptlet.TypeLib").Guid,38)
GetObject("new:{C08AFD90-F2A1-11D1-8455-00A0C91F3880}").putProperty s,Me
WScript.CreateObject("WScript.Shell").Run c,0,false
Out of all the solutions I've tried, this is by far the best and easiest to set up. Download hiddenw.exe from here - https://github.com/SeidChr/RunHiddenConsole/releases
Let's say you want to run Powershell v5 consoleless. Simply rename hiddenw.exe to powershellw.exe. If you want to do this for cmd, then rename to cmdw.exe. If you want to do it for Powershell v7 (pwsh), then rename to pwshw.exe. You can create multiple copies of hiddenw.exe and just rename to the actual process with the letter w at the end. Then, simply add the process to your system environmental PATH, so you can call it from anywhere. Or just copy to C:\Windows. Then, just call it, like this:
powershellw .\example.ps1
I found compiling to exe was the easiest way to achieve this. Theres a number of ways to compile a script, but you can try ISE Steroids
Open "Windows PowerShell ISE", install and run ISESteroids:
Install-Module -Name "ISESteroids" -Scope CurrentUser -Repository PSGallery -Force
Start-Steroids
Then go to Tools->Turn code into EXE, select 'Hide Console Window', and then create the application.
You can run this directly from task scheduler without the need for wrappers or 3rd party apps.
What I do is transform the .ps1 file into an invisible .exe file using an awesome app called Ps1 To Exe which you can download here : https://www.majorgeeks.com/files/details/ps1_to_exe.html
Maybe this helps (although I hope after 12 years you have found a suitable solution... ๐Ÿ™‚)
In other words, the script should run quietly in the background without any sign to the user.
Extra credit for an answer that does not use third party components :)
I found a way to do this by compiling a PowerShell script to a Windows executable. Third party modules are required to build the executable but not to run it. My end goal was to compile a one line PowerShell script that ejects a DVD on my system:
(New-Object -com "WMPlayer.OCX.7").cdromcollection.item(0).eject()
My target system is running Windows 7. The specific WMF update needed varies based on Windows version:
Download and install the WMF 5.1 package
The required PowerShell modules should be applicable to any Windows version. Here are the exact commands I used to install the necessary modules and compile the exe. You'll need to tweak the drive, directory and filename details for your system:
mkdir i:\tmp\wmf
cd i:\tmp\wmf
pkunzip ..\Win7AndW2K8R2-KB3191566-x64.zip
c:\windows\system32\windowspowershell\v1.0\powershell.exe
Set-ExecutionPolicy RemoteSigned
.\Install-WMF5.1.ps1
<click> "Restart Now"
c:\Windows\System32\WindowsPowerShell\v1.0\powershell -version 3.0
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-Module -Name ps2exe -RequiredVersion 1.0.5
ps2exe i:\utils\scripts\ejectDVD.ps1 -noConsole

Suppress command line but show credentials

I want to suppress the login of the command line. And just want to see the credential window.
So far the script is working with this command
Add-Type -Name win -MemberDefinition '[DllImport("user32.dll")] public
static extern bool ShowWindow(int handle, int state);' -Namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::
GetCurrentProcess() | Get-Process).MainWindowHandle,0)
I have compiled the script to an exe and it works so far except that the credential window is suppressed instead of the command line login.
I have tried various solutions to solve the problem, but nothing worked.
Start-Process "powershell.exe" -ArgumentList '-Command "
$Cred = Get-Credential
Add-Type -AssemblyName "System.Windows.Forms"
[System.Windows.Forms.MessageBox]::Show($Cred.Username)
"' -WindowStyle Hidden
you're hiding the process window handle low level - since the credential window is a child of it that will cause it to disappear as well, launching powershell with a hidden window will not suppress additional/child windows however.
The above code will output the username in a messagebox popup without displaying the PS window.
Never mind, thanks for the help! I found another way the solve the problem. When I compile the .ps1 to .exe I can set the parameter -console and this is working.

how do I make it easy for my parents to run this Powershell command?

I am not a programmer and my parents' Windows 10 PC tends to loose its start menu and cortana processes, resulting in start menu not showing up at all when the start icon is clicked.
I made a quick search and found + tested this Powershell command and it worked:
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
I wish to turn this command into a shortcut/batchfile that executes the command and restarts the PC whenever the desktop icon is double clicked, in order to avoid explaining to my parents what to do to fix the problem. Can any one help me out please?
Thank you in Advance.
you can encode the command and put the whole thing into a single batch file (no .ps1 necessary)
details here
https://blogs.msdn.microsoft.com/timid/2014/03/26/powershell-encodedcommand-and-round-trips/
or you can use this function
https://github.com/gangstanthony/PowerShell/blob/master/Encode-Text.ps1
first, either use Get-Content or Get-Clipboard (copy your whole script to the clipboard) to encode your desired script
PS> Encode-Text (Get-Clipboard | out-string)
RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
then you can use that in your batch file like so
powershell -encodedcommand RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
You could execute the PowerShell script via a batch file.
Batch file:
set powerscriptPath=C:\Example.ps1
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%powerscriptPath%""' -Verb RunAs}"
This will bypass the execution policies on the computer allowing the script to run in Administrator mode too. NOTE: You will need to edit the powerscriptPath to point to your PowerShell script location, I just used C:\Example.ps1 as an example.
You will want to add Restart-Computer -Force to the end of your PowerShell script to restart the computer
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
Restart-Computer -Force
Make a bat file which executes powershell with that file. Then add a shortcut to the bat file
I am really unsure why you would run a batch file just to call a powershell script! Talk about hokey approaches to a non-problem.
To call a powershell script is really no different than calling a batch script:
It's simply path to PowerShell, and the script path as a parameter:
"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" "C:\users\austinfrench\desktop\example.ps1"
You can also use the exact same format as the target for a desktop shortcut.

Powershell ISE - Choose script file when open a new window

I'm trying to open a new Powershell ISE window providing my own script .ps1 file.
How can I accomplish that? Seems that the only way to open a new Powershell ISE window is with a blank script file, and not one one's may choose(i.e. start powershell_ise.exe -file "myfile.ps1" - That's not working).
Here is a few solutions:
1) Use ISE twice, the only downside is that you'll see extra untitled doc
ise; ise ".\test.ps1"
2) You can start it in admin mode (from non-admin mode), it will force to create a new ISE:
Start-Process powershell_ise -ArgumentList ".\test.ps1" -Verb RunAs
3) Run as different user
Start-Process powershell_ise -ArgumentList "-noprofile .\test.ps1" -Credential $cred
Method 2/3 only open new ISE once though (until you close it)
From inside powershell I run:
ise myfile.ps1
and it will open it.
Simply put, I don't think it's possible. I've done a quick Google and found the answer that campbell.rw posted but the same thing occurred. Similarly, I've just tried to start a new PowerShell ISE process using the following command...
Start-Process -FilePath C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe -ArgumentList "-File .\testscript.ps1"
...but like you mentioned in the comments below the existing answer, instead of opening a new instance of PowerShell ISE it simply creates a new tab in the same instance with the script I specified in the 'ArgumentList' parameter.

How do I run a PowerShell script when the computer starts?

I have a PowerShell script that monitors an image folder. I need to find a way to automatically run this script after the computer starts.
I already tried the following methods, but I couldn't get it working.
Use msconfig and add the PowerShell script to startup, but I cannot find the PowerShell script on that list.
Create a shortcut and drop it to startup folder. No luck.
%SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -File "C:\Doc\Files\FileMonitor.ps1"
or
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -File "C:\Doc\Files\FileMonitor.ps1"
Here's my PowerShell script:
$folder = "C:\\Doc\\Files"
$dest = "C:\\Doc\\Files\\images"
$filter = "*.jpg"
$fsw = new-object System.IO.FileSystemWatcher $folder, $filter -Property #{
IncludeSubDirectories=$false
NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite'
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
Start-Sleep -s 10
Move-Item -Path C:\Doc\Files\*.jpg C:\Doc\Files\images
}
I also tried to add a basic task using taskschd.msc. It is still not working.
Here's what I found, and maybe that will help to debug it.
If I open up a PowerShell window and run the script there, it works. But if I run it in a command prompt,
powershell.exe -File "C:\Doc\Files\FileMonitor.ps1"
It will not work. I am not sure it's a permission problem or something else.
BTW, I have PowerShell 3.0 installed, and if I type $host.version, it will show 3 there. But my powershell.exe seems like it is still v1.0.
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
I finally got my PowerShell script to run automatically on every startup. You will need to create two files: the first is the Powershell script (e.g. script.ps1) and the second is a .cmd file that will contain commands that will run on the command prompt (e.g. startup.cmd).
The second file is what needs to be executed when the computer starts up, and simply copy-pasting the .ps1 to the startup folder won't work, because that doesn't actually execute the script - it only opens the file with Notepad. You need to execute the .cmd which itself will execute the .ps1 using PowerShell. Ok, enough babbling and on to the steps:
Create your .ps1 script and place it in a folder. I put it on my desktop for simplicity. The path would look something like this:
%USERPROFILE%\Desktop\script.ps1
Create a .cmd file and place it in
%AppData%\Microsoft\Windows\Start Menu\Programs\Startup\startup.cmd
Doing this will execute the cmd file every time on startup. Here is a link of how to create a .cmd file if you need help.
Open the .cmd file with a text editor and enter the following lines:
PowerShell -Command "Set-ExecutionPolicy Unrestricted" >> "%TEMP%\StartupLog.txt" 2>&1
PowerShell %USERPROFILE%\Desktop\script.ps1 >> "%TEMP%\StartupLog.txt" 2>&1
This will do two things:
Set the Execution Policy of your PowerShell to Unrestricted. This is needed to run scripts or else PowerShell will not do it.
Use PowerShell to execute the .ps1 script found in the path specified.
This code is specifically for PowerShell v1.0. If you're running PowerShell v2.0 it might be a little different. In any case, check this source for the .cmd code.
Save the .cmd file
Now that you have your .ps1 and .cmd files in their respective paths and with the script for each, you are all set.
You could set it up as a Scheduled Task, and set the Task Trigger for "At Startup"
What I do is create a shortcut that I place in shell:startup.
The shortcut has the following:
Target: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "C:\scripts\script.ps1"
(replacing scripts\scripts.ps1 with what you need)
Start In: C:\scripts
(replacing scripts with folder which has your script)
You could create a Scheduler Task that runs automatically on the start, even when the user is not logged in:
schtasks /create /tn "FileMonitor" /sc onstart /delay 0000:30 /rl highest /ru system /tr "powershell.exe -file C:\Doc\Files\FileMonitor.ps1"
Run this command once from a PowerShell as Admin and it will create a schedule task for you. You can list the task like this:
schtasks /Query /TN "FileMonitor" /V /FO List
or delete it
schtasks /Delete /TN "FileMonitor"
This is really just an expansion on #mjolinor simple answer [Use Task Scheduler].
I knew "Task Scheduler" was the correct way, but it took a bit of effort to get it running the way I wanted and thought I'd post my finding for others.
Issues including:
Redirecting output to logs
Hiding the PowerShell window
Note: You must have permission to run script see ExecutionPolicy
Then in Task Scheduler, the most important/tricky part is the Action
It should be Start a Program
Program/Script:
powershell
Add arguments (optional) :
-windowstyle hidden -command full\path\script.ps1 >> "%TEMP%\StartupLog.txt" 2>&1
Note:
If you see -File on the internet, it will work, but understand nothing can be after -File except the File Path, IE: The redirect is taken to be part of the file path and it fails, you must use -command in conjunction with redirect, but you can prepend additional commands/arguments such as -windowstyle hidden to not show PowerShell window.
I had to adjust all Write-Host to Write-Output in my script as well.
Try this: create a shortcut in startup folder and input
PowerShell "& 'PathToFile\script.ps1'"
This is the easiest way.
Prerequisite:
1. Start powershell with the "Run as Administrator" option
2. Enable running unsigned scripts with:
set-executionpolicy remotesigned
3. prepare your powershell script and know its path:
$path = "C:\Users\myname\myscript.ps1"
Steps:
1. setup a trigger, see also New-JobTrigger (PSScheduledJob) - PowerShell | Microsoft Docs
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30
2. register a scheduled job, see also Register-ScheduledJob (PSScheduledJob) - PowerShell | Microsoft Docs
Register-ScheduledJob -Trigger $trigger -FilePath $path -Name MyScheduledJob
you can check it with Get-ScheduledJob -Name MyScheduledJob
3. Reboot Windows (restart /r) and check the result with:
Get-Job -name MyScheduledJob
see also Get-Job (Microsoft.PowerShell.Core) - PowerShell | Microsoft Docs
References:
How to enable execution of PowerShell scripts? - Super User
Use PowerShell to Create Job that Runs at Startup | Scripting Blog
Copy ps1 into this folder, and create it if necessary. It will run at every start-up (before user logon occurs).
C:\Windows\System32\GroupPolicy\Machine\Scripts\Startup
Also it can be done through GPEDIT.msc if available on your OS build (lower level OS maybe not).
Be sure, whenever you want PowerShell to run automatically / in the background / non-interactive, itโ€™s a good idea to specify the parameters
-ExecutionPolicy Bypass to PowerShell.exe
PowerShell.exe -ExecutionPolicy Bypass
I have a script that starts a file system watcher as well, but once the script window is closed the watcher dies. It will run all day if I start it from a powershell window and leave it open, but the minute I close it the script stops doing what it is supposed to.
You need to start the script and have it keep powershell open.
I tried numerous ways to do this, but the one that actually worked was from http://www.methos-it.com/blogs/keep-your-powershell-script-open-when-executed
param ( $Show )
if ( !$Show )
{
PowerShell -NoExit -File $MyInvocation.MyCommand.Path 1
return
}
Pasting that to the top of the script is what made it work.
I start the script from command line with
powershell.exe -noexit -command "& \path\to\script.ps1"
A relatively short path to specifying a Powershell script to execute at startup in Windows could be:
Click the Windows-button (Windows-button + r)
Enter this:
shell:startup
Create a new shortcut by rightclick and in context menu choose menu item: New=>Shortcut
Create a shortcut to your script, e.g:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "C:\Users\someuser\Documents\WindowsPowerShell\Scripts\somesscript.ps1"
Note the use of -NoProfile
In case you put a lot of initializing in your $profile file, it is inefficient to load this up to just run a Powershell script. The -NoProfile will skip loading your profile file and is smart to specify, if it is not necessary to run it before the Powershell script is to be executed.
Here you see such a shortcut created (.lnk file with a Powershell icon with shortcut glyph):
This worked for me. Created a Scheduled task with below details:
Trigger : At startup
Actions:
Program/script : powershell.exe
Arguments : -file
You can see scripts and more scheduled for startup inside Task Manager in the Startup tab. Here is how to add a new item to the scheduled startup items.
First, open up explorer to shell:startup location via start-button => run:
explorer shell:startup
Right click in that folder and in the context menu select a new shortcut. Enter the following:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile
-Command "C:\myfolder\somescript.ps1"
This will startup a Powershell script without starting up your $profile scripts for faster execution. This will make sure that the powershell script is started up.
The shell:startup folder is in:
$env:APPDATA\Microsoft\Windows
And then into the folder:
Start Menu\Programs\Startup
As usual, Microsoft makes things a bit cumbersome for us when a path contains spaces, so you have to put quotes around the full path or just hit tab inside Powershell to autocomplete in this case.
If you do not want to worry about execution policy, you can use the following and put into a batch script. I use this a lot when having techs at sites run my scripts since half the time they say script didnt work but really it's cause execution policy was undefined our restricted. This will run script even if execution policy would normally block a script to run.
If you want it to run at startup. Then you can place in either shell:startup for a single user or shell:common startup for all users who log into the PC.
cmd.exe /c Powershell.exe -ExecutionPolicy ByPass -File "c:\path\to\script.ps1"
Obviously, making a GPO is your best method if you have a domain and place in Scripts (Startup/Shutdown); under either Computer or User Configurations\Windows Settings\Scripts (Startup/Shutdown).
If you go that way make a directory called Startup or something under **
\\yourdomain.com\netlogon\
and put it there to reference in the GPO. This way you know the DC has rights to execute it. When you browse for the script on the DC you will find it under
C:\Windows\SYSVOL\domain\scripts\Startup\
since this is the local path of netlogon.
Execute PowerShell command below to run the PowerShell script .ps1 through the task scheduler at user login.
Register-ScheduledTask -TaskName "SOME TASKNAME" -Trigger (New-ScheduledTaskTrigger -AtLogon) -Action (New-ScheduledTaskAction -Execute "${Env:WinDir}\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-WindowStyle Hidden -Command `"& 'C:\PATH\TO\FILE.ps1'`"") -RunLevel Highest -Force;
-AtLogOn - indicates that a trigger starts a task when a user logs on.
-AtStartup - indicates that a trigger starts a task when the system is started.
-WindowStyle Hidden - don't show PowerShell window at startup. Remove if not required.
-RunLevel Highest - run PowerShell as administrator. Remove if not required.
P.S.
If necessary execute PowerShell command below to enable PowerShell scripts execution.
Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy Unrestricted -Force;
Bypass - nothing is blocked and there are no warnings or prompts.
Unrestricted - loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the internet, you're prompted for permission before it runs.
I 'm aware that people around here don't need a tool like this. But I think it will be useful especially for novice users. Auto start tool It is a Portable freeware which designed to simplify the process to automatically launch an App or script when you login to Windows. It offers 3 different options for autostart
Task Scheduler
Startup folder
Registry run key
The best part of the tool is supports powershell scripts (.Ps1) . this means that you can run a Powershell script automatically at system startup with all 3 methods.
Download
https://disk.yandex.com.tr/d/dFzyB2Fu4lC-Ww
Source:
https://www.portablefreeware.com/forums/viewtopic.php?f=4&t=25761
One thing I found. if you are using Write-Host within your PowerShell scripts, and are also using Task Scheduler (as shown in the posts above), you don't get all the output from the command line.
powershell.exe -command C:\scripts\script.ps1 >> "C:\scripts\logfile.log"
In my case, I was only seeing output from commands that ran successfully from the PowerShell script.
My conclusion so far is PowerShell uses Out-File to output to another command or in this case a log file.
So if you use *> instead of >> you get all the output from the CLI for your PowerShell script, and you can keep using Write-Host within your script.
powershell.exe -command C:\scripts\script.ps1 *> "C:\scripts\logfile.log"
https://lazyadmin.nl/powershell/output-to-file/
You can also run the script in the background, regardless of user login.
Within your task in Task Scheduler set "Run whether user is logged on or not", and then in the password prompt type your hostname\username then your password (In my case an account with Admin permissions).
I used Set-ExecutionPolicy RemoteSigned -Scope CurrentUser to get around the script execution problem. I still would have preferred to run it on a per-process basis though. A problem for another time.