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
Related
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:"=%
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.
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.
I've been stuck at this same issue from past 5 days. The script has no issues and is sending email without any issues when executed from ISE directly.
#ECHO OFF C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -executionpolicy RemoteSigned -file D:\powershell\Fedex_Meter_Check1.ps1 PAUSE
Also tried
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -executionpolicy RemoteSigned -file D:\powershell\Fedex_Meter_Check1.ps1
There are no errors when executed from powershell.exe or cmd but no email. Please assist me on this.
Send-MailMessage -from 'Trax_FedEx ittraxsupport#xpo.com' -to 'Rahul `Rahul.Lalwani#xpo.com'<#'TRAX ittraxsupport#xpo.com' #> -subject 'Daily Rates `Check for FedEx Meters.' -body 'Perfect! All FedEx Meters Have Good Rates!'` `-Encoding Unicode -port 25 -smtpserver mailhost.cnf.com
I have had numerous issues running Powershell from BAT files in the past. One thing that I remember is that there are weird issues dealing with starting directory. From the command line, try changing the directory to the same directory as the powershell script, and then run it from there. I have this in a BAT file that works as long as the .bat and .ps1 share the same name.
#ECHO OFF
SET ThisScriptsDirectory=%~dpn0
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%~dpn0'"
PAUSE
Another solution I found in another old script is to run powershell.exe from the .bat or command line and give the .ps1 as a command to powershell instead of as a file.
powershell.exe -command "& {C:\filepath.ps1}"
I found a solution. Just adding Start-Sleep -Seconds 1 as the last line and it worked for me.
I have a PowerShell script that needs to run as administrator when i click the .bat file to launch it, however, i also need the PowerShell window hidden. I have a script that currently launches it as admin, but i need it to hide the window as well. I have tried to put in -windowstyle hidden, but it does not work. Here is my launch script:
#ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%PMCS_Full_InProgress.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";
Can anyone help me hide the window? Thanks for your time.
Solved. I was not putting -windowstyle hiddeninsideofthe "& {Start-Process PowerShell -Arguments . . .} so it wasn't recognizing it at all. I was trying to put it on the outside. Thanks for your help!