Solved

Cannot run powershell script

Posted on 2013-06-07
30
1,643 Views
Last Modified: 2013-06-09
Hi,

The following code works fine if I paste it into a Powershell window. But whenever I try to run it from a saved ps1 script (like at logon) it errors and doesn't work. The errors flick past so quickly that I cannot reproduce them here and my scripting knowledge started when I found this code on the web :).

start C:\Windows\System32\taskmgr.exe
[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$shell = New-Object -ComObject “Shell.Application”
$shell.MinimizeAll()

Best Regards,

MusicBuddha
0
Comment
Question by:MusicBuddha
  • 16
  • 8
  • 5
30 Comments
 
LVL 11

Accepted Solution

by:
marek1712 earned 400 total points
Comment Utility
You don't have to load assembly for Shell.Application object. Such code is enough:
$shell = New-Object -ComObject Shell.Application
$shell.MinimizeAll()

Open in new window

The problem you're running into is probably the Execution Policy.
Run this in the PSh console and give us the result:
Get-ExecutionPolicy

Open in new window

If it's restricted - that's why your script is erroring out. You can issue this command:
Set-ExecutionPolicy Unrestricted

Open in new window

to make ALL the script execute.
The last thing: for running scripts from Task Scheduler you have to issue command like this:
powershell -File "Path to your .ps1 file"
0
 

Author Comment

by:MusicBuddha
Comment Utility
The problem you're running into is probably the Execution Policy.
Run this in the PSh console and give us the result:
It was set to restricted.

If it's restricted - that's why your script is erroring out. You can issue this command:

Set-ExecutionPolicy Unrestricted
                                           

When I ran this and tried to set to unrestricted I got the following error from the powershell terminal.

Set-ExecutionPolicy : Access to the registry key
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
At line:1 char:1
+ Set-ExecutionPolicy Unrestricted
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Set-ExecutionPolicy], UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyComma
   nd
0
 
LVL 11

Expert Comment

by:marek1712
Comment Utility
Did you click on the powershell icon and picked "Run As Administrator" (if UAC is running)?
0
 

Author Comment

by:MusicBuddha
Comment Utility
UAC is turned off, however running as administrator did allow me to change to unrestricted but I am still getting an error when I try to run my script.
0
 
LVL 11

Expert Comment

by:marek1712
Comment Utility
OK, try setting the $ErrorActionPreference to stop in the beginning of the script.
MORE INFORMATION
Like this:
$ErrorActionPreference = "Stop"

Open in new window

0
 

Author Comment

by:MusicBuddha
Comment Utility
$ErrorActionPreference = "Stop"
I am still just getting errors

Also since I ran Set-ExecutionPolicy Unrestricted the line $shell.MinimizeAll() line does not work when pasting the script into a PS window unless it is a Run As Administrator PS Window.
0
 
LVL 11

Expert Comment

by:marek1712
Comment Utility
With EAP set to STOP the error window should just sit in the background. You should be able to see the error then.
What kind of error is this?
If it's login script the error should be pointed somewhere in the Event Viewer. Can you check it?
Another thing to try - add another command to the pipeline.
$shell.MinimizeAll() | Out-File c:\test.txt

Open in new window

Check THIS thread for more information.
0
 

Author Comment

by:MusicBuddha
Comment Utility
I don't know what kind of error it is. All I see is some red text flash by and then the PS window closes.

$shell.MinimizeAll() | Out-File c:\test.txt
I added the line but it still doesn't work when I paste the comand into a normal PS window. When I use an Administrator window it works and creates an emtpy file called c:\test.txt
0
 

Author Comment

by:MusicBuddha
Comment Utility
Check THIS thread for more information.
I am sorry to say that I do not fully understand the contents of that thread. My knowledge of Powershell started yesterday when I found the script on the net and tried to run it at login.
0
 

Author Comment

by:MusicBuddha
Comment Utility
$shell.MinimizeAll()

I worked out why that command is not working, it is because taskmgr.exe has not fully opened yet. All of the other windows get minimized, so I guess we need a short delay command before that line?

If it's login script the error should be pointed somewhere in the Event Viewer. Can you check it?
I finally found the powershell errors in the event viewer the latest error gave the following detail.

Engine state is changed from Available to Stopped.

Details:
      NewEngineState=Stopped
      PreviousEngineState=Available

      SequenceNumber=15

      HostName=ConsoleHost
      HostVersion=3.0
      HostId=d0368bcb-08f8-4405-8b07-2ffb5c535b0b
      EngineVersion=3.0
      RunspaceId=975e64c6-1b46-4811-b6ee-eb85f02c1e2a
      PipelineId=
      CommandName=
      CommandType=
      ScriptName=
      CommandPath=
      CommandLine=
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
You can start Task Manager minimized:
start-process TaskMgr.exe -WindowStyle Minimized
(New-Object -ComObject Shell.Application).MinimizeAll()
read-host  "Press Enter to continue" | out-null

Open in new window

To be able to see the error message, if any, I've added a command to wait for you to press Enter.
0
 

Author Comment

by:MusicBuddha
Comment Utility
To be able to see the error message, if any, I've added a command to wait for you to press Enter.
This works if I copy and paste into a PowerShell window. But again when I try to run from the script I just see a flash of red and then the PS window closes.
0
 

Author Comment

by:MusicBuddha
Comment Utility
Did you see my comment where I found the error for the script in the event viewer?
0
 

Author Comment

by:MusicBuddha
Comment Utility
You can start Task Manager minimized:
Starting the task manager minized leaves a task manager button on the task bar. When it was done the other way with $shell.MinimizeAll() it not only minimized it but it also didn't leave the button on the taskbar. So I would prefer to put a small delay in there.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
That's not an error but info in the eventlog. It's telling only that PowerShell has been executed.

The error is either in starting TaskMgr, or in finding/executing the script. Let's try with
powershell -File "C:\Full Path to Script\Script.ps1" -noexit
0
 
LVL 68

Assisted Solution

by:Qlemo
Qlemo earned 100 total points
Comment Utility
Shell.Application.MinimizeAll() does not work different than to switch all window states to "minimized", so it is the same. Whether Task Manager shows something on the taskbar depends only on the option "Hide When Minimized" of Task Manager itself. That setting is stored in the user profile.
But if you insist, you can use  start-sleep 1 to wait one second, or something like start-sleep -Milliseconds 100 to wait less.
0
 

Author Comment

by:MusicBuddha
Comment Utility
The error is either in starting TaskMgr, or in finding/executing the script. Let's try with
powershell -File "C:\Full Path to Script\Script.ps1" -noexit
When I pasted this in to PS the task manager was not started and the PS window froze and would not accept any input, I had to kill it.

When I ran the script I got the same flash of red (looks like about 3 or 4 lines of errors) and then the PS window closes.
0
 

Author Comment

by:MusicBuddha
Comment Utility
The error is either in starting TaskMgr, or in finding/executing the script. Let's try with
powershell -File "C:\Full Path to Script\Script.ps1" -noexit
I am sorry to say that when I first tried this I was pointing back to the script that I started. When I fixed the error and had test1.ps1 calling test2.ps1 it works properly. Also both PS windows closed and the Task Manager was minized without leaving a button in the task bar.

Here is what I have in test2.ps1

$ErrorActionPreference = "Stop"
start C:\Windows\System32\taskmgr.exe
$shell = New-Object -ComObject “Shell.Application”
$shell.MinimizeAll()


Would you say that the best correct answer is
The error is either in starting TaskMgr, or in finding/executing the script. Let's try with powershell -File "C:\Full Path to Script\Script.ps1" -noexit
I must thank you for all your efforts, you have been most helpful.
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
I'm confused now. The -noexit should prevent the powershell window from closing after executing the script. And I didn't want to you use a script to start another script. And lastly, why does all that seem to help?
0
 
LVL 11

Expert Comment

by:marek1712
Comment Utility
Can you explain HOW do you launch this script? Via GPO?
It's not the best idea to launch one PS script from another (at least not in this case).
Just create batch file (with .cmd extension) and fill it with code either provided by me or Qlemo.
To create a delay you can use i.e.:
Start-Sleep -Seconds 5

Open in new window

0
 

Author Comment

by:MusicBuddha
Comment Utility
Can you explain HOW do you launch this script? Via GPO?
What is GPO?

For testing I am selecting the script in File Explorer and pressing the enter key, same way for the batch/cmd script. At runtime I am using the following registry key.

HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run

The batch/cmd script loads Task Manager and then exits without waiting the 5 seconds and without minimizing any windows. Below is the contents of the batch/cmd script that I was using.

$ErrorActionPreference = "Stop"
start C:\Windows\System32\taskmgr.exe
$shell = New-Object -ComObject “Shell.Application”
Start-Sleep -Seconds 5
$shell.MinimizeAll()


And lastly, why does all that seem to help?
I have no idea why it works when calling one script from another I am just reporting what I see.

Whether Task Manager shows something on the taskbar depends only on the option "Hide When Minimized"
I have the "Hide When Minimized" setting checked, but it was still leaving a button on the task bar.
0
 
LVL 11

Assisted Solution

by:marek1712
marek1712 earned 400 total points
Comment Utility
What is GPO?
OK - since you don't know what it is, you're not using it (suggested by the HKLM key). If you're really curious about it - check the Technet.

But... back to the original question.
There may be few misconceptions in your approach:
- HKLM - this key is used by a computer account, not user (not exactly, but I wanted to give you the picture) and it may not work as intended. Especially that you're using Wow6432Node key associated with 32-bit applications (taskmgr.exe in 64bit OS is a 64bit program). You may try to place your script here:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
But that makes it technically a STARTUP script, not a LOGON script.
For the latter - try placing it here:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
Let us know if it works.
0
 

Author Comment

by:MusicBuddha
Comment Utility
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
I cannot test it right now (I am running a system backup that will take another hour to complete)  but I am sure that one of them will work, and loading a script by using File Explorer should work properlyas well  yes?

Also what about the minimize line in the *.cmd file, and the fact that I am calling one script from another when using *.ps1?
0
 
LVL 11

Expert Comment

by:marek1712
Comment Utility
Running the script from the Explorer means you run it in the context of a user account. But we'll verify taht if you place it in the HKCU.
As for the .cmd file - you can't put PoSh code there. It's used to launch .ps1 files through powershell.exe, i.e.:
powershell.exe -File c:\test.ps1

Open in new window

0
 

Author Comment

by:MusicBuddha
Comment Utility
powershell.exe -File c:\test.ps1
This works fine from a *.cmd file, and the sleep function in the PS script works as well.

Why does it work in this way and not when launching from file explorer or calling the script directly. why do I need to call the *.ps1 script from a batch file?
0
 

Author Comment

by:MusicBuddha
Comment Utility
Hi marek1712,

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

This works fine. Just to clarify I am running this from a *.cmd file called from the above registry key

powershell.exe -File c:\powershellstartup\StartWindowsTaskManager.ps1

And I am using this as my *.ps1 script

$ErrorActionPreference = "Stop"
start C:\Windows\System32\taskmgr.exe
$shell = New-Object -ComObject “Shell.Application”
start-sleep -Milliseconds 100
$shell.MinimizeAll()


I am quite satisfied that my problem has been solved, I am just not sure which of your answers I should set as the solution. There has been so many examples/solutions given that anyone really needs to read the entire thread. I would also like to give Qlemo a little bit of the credit.  I could really use  your input here as because I think it is a really worthwhile thread for a beginner like me.

Lastly I would like to thank you for spending so much time on my problem and thank you again for the detailed answers you have given me.

Best Regards,

MusicBuddha
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
Assigning points is difficult, as we still do not know why it works now.
I recommend to close by accepting
   http:#a39231314   150  for Execution Policy & Calling PS
   http:#a39231722   100  for sleep
   http:#a39232138   100  for HKCU recommendation
and
   http:#a39232341
0
 

Author Closing Comment

by:MusicBuddha
Comment Utility
Thank you for spending so much time with my problem :)
0
 
LVL 11

Expert Comment

by:marek1712
Comment Utility
Glad I could help and sorry I couldn't answer earlier. I think Qlemo's suggestions are right - not that it matters now.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

This script checks a path to see if a folder exists. If the folder does exist you will get output "The folder has previously been created. No action taken" If not it will create the folder. Then adds one user modify permission to the folder. It …
How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
Windows 8 came with a dramatically different user interface known as Metro. Notably missing from that interface was a Start button and Start Menu. Microsoft responded to negative user feedback of the Metro interface, bringing back the Start button a…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now