Writing a powershell script to re-start itself - windows

I'm trying to make a powershell script restart itself in the event of failure. Following on from a couple of references I've found here and here I've added this line...
Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file "$PSCommandPath"'
($PSCommandPath is the path and filename of the script)
What happens when my script gets to this point is that a window flashes up for a fraction of a second and then closes.
I think (but can't be sure) that the window that appears is a powershell console - it disappears too quickly to read.
The first questions is why isn't the -noexit parameter working - it should make the window of the new process remain open even if there's an error.
The 2nd question is how to get it to work, I've tried various combinations of the command including....
Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file c:\my_dir\my_script.ps1 '
Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file $PSCommandPath'
Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file "$PSCommandPath"'
The only version that does work (almost) is....
Invoke-Expression -Command ($PSCommandPath)
which does restart the script, but it doesn't do it in a new window it re-starts in the existing window (not what I'm looking for). The script has read and execute permissions (all users). This is a particularly frustrating problem in that I'm pretty sure this was working in the past, so it may be system problem rather than a script problem.
Update - I used Invoke-Expressions because that's what the examples I found used (and at the time I'm sure I got it to work!)
This solutions does work....
Start-Process -FilePath "$PSHOME\powershell.exe" -ArgumentList '-NoExit', '-File', """$PSCommandPath"""
Thanks

No need to search so far...
. $PSCommandPath
Note the space between the dot and $PSCommandPath.

Related

Batch script to run Powershell script: Flashing window

System: Windows 10
Powershell Version: 5.1
Purpose: Run a powershell script from a batch file
Parameters: Directory, Filename, Server, Username, Password all being passed in as string encompassed in "" when called from command to handle the situation when there is a space (such as the Directory which currently has a space in)
The Powershell script works perfectly, it creates the credential and starts the RDP connection without issues. When calling from a batch file however the Powershell window flashes and closes immediately. Command Prompt window is run as Administrator.
I've tried using:
- pause
- -noexit
- code from https://blog.danskingdom.com/allow-others-to-run-your-powershell-scripts-from-a-batch-file-they-will-love-you-for-it/
if ($Host.Name -eq "ConsoleHost")
{
Write-Host "Press any key to continue..."
$Host.UI.RawUI.FlushInputBuffer() # Make sure buffered input doesn't "press a key" and skip the ReadKey().
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}
Clicking on the appearing Powershell window (To try get the select function to pause the window).
None of which have worked.
The code in question is:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Outside of this code no changes have been made to the system, the four speech marks were marked as required to pass through parameters and can be found under the blog post link above at the bottom just before the comments.
There is a high chance i'm using this incorrectly, I am a novice to batch and even newer to powershell. The batch scripts are being made as internal as possible, they need to be able to be used by a base install of Windows. They will eventually be migrated onto versions of Windows Server 2008 and up.
Is there anything that needs to be done with command prompt to allow it to run Powershell code?
Is the powershell code correct for the purpose i'm intending to use it for?
Is there any way, besides the ones listed, to view error, log information or pause the powershell window when run from a batch script?
Any input would be really appreciated!
Edit:
-NoExit variations:
Parent Call
PowerShell **-NoExit** -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Nested call
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '**-NoExit** -NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Parent and Nested
PowerShell **-NoExit** -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '**-NoExit** -NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Variables set inside batch script as:
SET server=%~1
To remove the quotation marks I have also tried using:
SET server=%1
SET server=%server:"=%

How to QUIETLY start Powershell.exe using different credentials (without getting prompted for username/password)?

I've spent more time on this that I'd like to admit. I'm looking for powershell code that will quietly start a new PowerShell instance (in the existing PowerShell Window) using different credentials.
The best I can come up with is extremely clunky... popping up two different Powershell Windows on my screen before finally giving me a prompt. Apparently, the -NoNewWindow argument doesn't prevent the opening of any new PowerShell windows.
My VERY clunky code:
Start-Process powershell.exe -Credential $DomainAdmin -WorkingDirectory $env:windir -NoNewWindow -ArgumentList "Start-Process powershell.exe -Verb runAs"
If there is a way to "Runas" Powershell.exe from a desktop shortcut (and saving the username/password). I'd also be happy with that. Below, is the code I attempted to make. However, there seems to be a bug that keeps giving me the error, "267: The directory name is invalid"
Batch file that doesn't work:
runas.exe /savecred /env /noprofile /user:MKA "powershell.exe -noprofile -command \"start-process -WorkingDirectory c:\temp powershell -verb RunAs\""
A solution would be greatly appreciated.
To run as user MKA, create a shortcut with this in Target window:
C:\Windows\System32\runas.exe /User:MKA /savecred C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
To hide a PowerShell console window, you can put this code at the top of the script being executed. which is my favoured solution in this StackOverflow post.
add-type -name win -member '[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)
The post discusses other ways that may be more suitable for you.

How to start PowerShell script from BAT file with proper Working Directory?

I'm trying to create bat script that can start PowerShell script named the same as bat file in proper working directotry.
This is what I got:
#ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -WorkingDirectory '%~dp0' -Verb RunAs}"
PAUSE
Passing working directory this way does not work.
How to make script that will pass proper working directroy and also command line arguments?
The -WorkingDirectory parameter doesn't work when using -Verb RunAs. Instead, you have to set the working directory by calling cd within a -Command string.
This is what I use: (cmd/batch-file command)
powershell -command " Start-Process PowerShell -Verb RunAs \""-Command `\""cd '%cd%'; & 'PathToPS1File';`\""\"" "
If you want to make a "Run script as admin" right-click command in Windows Explorer, create a new registry key at HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command, and set its value to the command above -- except replacing %cd% with %W, and PathToPS1File with %1 (if you want it to execute the right-clicked file).
Result: (Windows Explorer context-menu shell command)
powershell -command " Start-Process PowerShell -Verb RunAs \""-Command `\""cd '%W'; & '%1';`\""\"" "
EDIT: There's an alternative way to have the script be run as admin from Explorer, by using the "runas" sub-key: https://winaero.com/blog/run-as-administrator-context-menu-for-power-shell-ps1-files
If you want to run your script as admin from an existing powershell, remove the outer powershell call, replace %W with $pwd, replace %1 with the ps1 file-path, and replace each \"" with just ".
Note: The \""'s are just escaped quotes, for when calling from the Windows shell/command-line (it's quote-handling is terrible). In this particular case, just \" should also work, but I use the more robust \"" for easier extension.
See here for more info: https://stackoverflow.com/a/31413730/2441655
Result: (PowerShell command)
Start-Process PowerShell -Verb RunAs "-Command `"cd '$pwd'; & 'PathToPS1File';`""
Important note: The commands above are assuming that your computer has already been configured to allow script execution. If that's not the case, you may need to add -ExecutionPolicy Bypass to your powershell flags. (you may also want -NoProfile to avoid running profile scripts)
A workaround is to let the PowerShell script change the directory to it's own origin with:
Set-Location (Split-Path $MyInvocation.MyCommand.Path)
as the first command.
As per mklement0s hint: In PSv3+ use the simpler:
Set-Location -LiteralPath $PSScriptRoot
Or use this directory to open adjacent files.
$MyDir = Split-Path $MyInvocation.MyCommand.Path
$Content = Get-Content (Join-Path $MyDir OtherFile.txt)

Setting wallpaper: PowerShell works but only temporarily

I have some trouble with a PowerShell and Batch file. When I run a batch file in which a Powershell script is called, it runs normally. After a logoff and logon it´s as if nothing happened.
This is the batch file (SetWallpaper.bat):
#ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
PAUSE
And here is my Powershell code (SetWallpaper.ps1):
Set-ItemProperty -path 'HKCU:\Control Panel\Desktop\' -name wallpaper -value "<root>\Users\temp\Tree_Updown.jpg"
rundll32.exe user32.dll, UpdatePerUserSystemParameters
As I said, it works, but after a logoff and on, the wallpaper is the default Windows picture.
The curiosity is, that when I launch just the Powershell code alone, without a batch, it works perfect.
I searched the web for some other alternatives, like launching the file via VBS, and it didn´t work.
VBS-code(LaunchSetWallpaper.vbs):
command = "powershell.exe -nologo -command <root>\Users\temp\SetWallpaper.ps1"
set shell = CreateObject("WScript.Shell")
shell.Run command,0
for some reason unknown, it doesn't do anything.
At this point, I don´t know what else to do. Hope someone can give me some advice.
Thanks.
Martin Leiva

The syntax of the command is incorrect running .ps1 from .bat

So I am trying to run a powershell script on windows server from a .bat file and I keep getting this error.
This is the only line I have in my script:
start /d "C:\Windows\SysWOW64\WindowsPowerShell\v1.0\" Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\path\to\scripts\awesomescript.ps1'"
I have successfully run that command by itself in the cmd window by copying/pasting that whole line into the cmd prompt. The script has been tested as well.
However the same command will not work in the batch file and gives me the error "The syntax of the command is incorrect".
Does anyone happen to know why?
Update:
Thank you to the poster. I merely exited my old command prompt and started a new one. That old command and the previous posters worked. I hate those little things with windows.
Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\path\to\script\script.ps1'"
I will be keeping the posters answer as the accepted.
Thank you!
Why are you putting path before powershell.exe? Seems to be working without this full path:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Users\SE\Desktop\ps.ps1'"
Look there.

Resources