Restarting PC's and writing to the event log with a custom message - powershell

I have written a script in PowerShell that will remotely restart a list of PC's using the 'Restart-Computer' command.
Is there a way of adding a custom message to the systems event log, to explain that the computer has been restart by my script.

Here is the PowerShell code that I used to solve this problem as suggested by the user C.B. above.
Shutdown /r /f /m ComputerName /d P:0:1 /c "Your comment"
This code will force (/f) a shut down and reboot (/r) of a given PC and write to the event log with a custom comment (/c). Note that to write a custom comment a reason code will need to be supplied using the (/d) parameter. Also note that the order of parameters matters.
For a list of reason codes and syntax follow the links below.
http://ss64.com/nt/shutdown.html
http://technet.microsoft.com/en-us/library/cc732503(v=ws.10).aspx

Related

Is there any way to have powershell automatically run a command anytime a command is run

I'm wanting to be able to have PowerShell automatically run a specified command anytime anything is run in PowerShell(hitting enter, any command at all). I've searched all over google with no luck finding anything except the way to have a command run on startup of powershell
If you need it a bit hidden you could do it with a ScheduledTask and Auditing Events.
Enable Auditing to get all changes logged as events
https://learn.microsoft.com/en-us/powershell/scripting/windows-powershell/wmf/whats-new/script-logging?view=powershell-7.2&viewFallbackFrom=powershell-6
Create a Scheduled Task that starts with a trigger from Events by ID. Take the IDs from the Microsoft article above. Add the command you would like to run as action. This means command is "PowerShell" and parameters are like -NonInteractive -Windowstyle minimized -c "command was executed | out-file c:\temp\activity.log"
Set it to be run as the user "system" if you want it at full permission without user interaction.
Don't forget this task to be allowed to run multiple times if you want it to.
Be aware that this might generate a lot of log entries and a lot of powershell processes depending on how log your task will run.
But in most cases the solution mentioned by Mathias R. Jessen above might be the easiest one, but is also easy to be changed by any user for the session even if you changed prompt in the settings mentioned here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_profiles?view=powershell-7.2

prompt a user for input during silent .msi install

We are trying to create a deployment of a software called lanschool to our organization, via SCCM 2012. It functions basically by having an admin account create a channel that client accounts connect to for monitoring. We're using our admins phone extensions as their channel numbers.
The issue here is that We'd like to create a silent deployment package for this software, but would need some way to create a prompt during the install so that the admin can input their extension. Is there a way to accomplish this?
Can you launch the MSI with a command line that includes the data? This is the standard method of passing in data during a silent install. The required input values are specified as properties that can be input by the user in UI mode or passed in during silent mode, something like:
msiexec /I [path to msi file] MYCHANNEL=12345
where MYCHANNEL is the name of the public property.
A silent install with user input? Ok then :)
My initial reaction would be to try to do it with a custom action (a simple VB script for example). However something at the back of my mind (I don't have access to InstallShield right now to test this) is warning me that any attempt at interaction would not show and could either timeout or throw an error. Don't take my word for that though.
What I ended up doing is writing a bat file that prompted the user for their extension, stored it in a variable, and then added that variable data to the specified registry key. Code below:
::create a prompt for extension input and store input in variable "channelNumber"
SET /P channelNumber=Please enter your phone extension, this will be used as your Lanschool channel:
::shut down lanschool
TASKKILL /f /im teacher.exe
::write variable to reg key
REG ADD HKLM\Software\Wow6432Node\Lanschool\ /t REG_DWORD /v channel /d "%channelNumber%" /f
::start lanschool
PUSHD C:\program files (x86)\Lanschool
START Teacher.exe
EXIT

Windows Scheduled task succeeds but returns result 0x1

I have a scheduled task on a Windows 2008 R2 server. The task includes a Start In directory entry. The task runs, and the batch file it runs does what it is supposed to do. When I run the batch file from a command prompt, I see no errors. The problem is that the "Last run result" is 0x1 (incorrect function call).
I did get this at one time with an incorrect DOS statement IF EXISTS file.txt DO (Copy file.txt file1.txt) that was corrected by dropping the DO statement. The current batch file does not show me any errors or warnings.
Why am I getting a 0x1 result?
Batch file that is run:
PUSHD \\JUKEBOX4\Archives\CallRecording
REM only move csv and wma together. wma should be created last.
IF NOT EXIST C:\CallRecording (MKDIR C:\CallRecording)
FOR /f %%f IN ('DIR /b *.wma') DO (
IF EXIST %%~nf.csv (MOVE /Y %%~nf.* C:\CallRecording\)
)
POPD
CD /D "C:\Program Files (x86)\Olim, LLC\Collybus DR Upload"
CollybusUpload.exe
POPD
Info on scheduled task setup:
Program to run: C:\Program Files (x86)\Olim, LLC\Collybus DR Upload\CallRecordingUploadFromH.cmd
Start in: C:\Program Files (x86)\Olim, LLC\Collybus DR Upload
Run whether user is logged on or not, highest privileges.
History screen, task completed entry
"Task Scheduler successfully completed task "\Call recording upload to portal from NH" , instance "{1449ad42-2210-427a-bd69-2c15e35340e6}" , action "C:\Windows\SYSTEM32\cmd.exe" with return code 1."
First screen of Task Scheduler shows "Run Result" of "Success"
It seems many users are having issues with this. Here are some fixes:
Right click on your task > "Properties" > "Actions" > "Edit" |
Put ONLY the file name under 'Program/Script', no quotes and ONLY the directory under 'Start in' as described, again no quotes.
Right click on your task > "Properties" > "General"
| Test with any/all of the following:
"Run with highest privileges" (test both options)
"Run wheter user is logged on or not" (test both options)
Check that "Configure for" is set to your machine's OS version
Make sure the user account running the program has the right permissions
I found that I have ticked "Run whether user is logged on or not" and it returns a silent failure.
When I changed tick "Run only when user is logged on" instead it works for me.
I've had the same problem. It is just a batch-file, working when manually started, but not working as a scheduled task.
there were drive-letters in the batch-file like this:
put z:\folder\file.ext
seems like you should not use drive-letters, they are bound to the user, who created them - for me this little change made it work again:
put \\server\folder\file.ext
For Powershell scripts
I have seen this problem multiple times while scheduling Powershell scripts with parameters on multiple Windows servers.
The solution has always been to use the -File parameter:
Under "Actions" --> "Program / Script" Type: "Powershell"
Under "Add arguments", instead of just typeing "C:/script/test.ps1" use -File "C:/script/test.ps1"
Happy scheduling!
Windows Task scheduler (Windows server 2008r2)
Same error for me (last run result: 0x1)
Tabs
Action: remove quotes/double-quotes in
program/script
and
start in
even if there is spaces in the path name...
General:
Run with highest privileges
and
configure for your OS...
Now it work!
last run result: The operation completed successfully
Probably not the cause of the OP's problem; for me the problem was caused by the fact that my program called a SQL function, and the service account the windows task was set up with did not have the required SQL permissions. That also gives a 0x1
This answer was originally edited into the question by the asker.
The problem was that the batch file WAS throwing a silent error. The final POPD was doing no work and was incorrectly called with no opening PUSHD.
Broken code:
CD /D "C:\Program Files (x86)\Olim, LLC\Collybus DR Upload" CALL CollybusUpload.exe POPD
Correct code:
PUSHD "C:\Program Files (x86)\Olim, LLC\Collybus DR Upload" CALL CollybusUpload.exe POPD
In my case it was an encoding issue. We wanted to start en existing batch file, and it resulted in "return code 1", and the desired action wasn't performed. I've accidentally found that the batch file was shown in Notepad as one with UTF-8 encoding (actually without any reason, as we have no special characters in the text). I saved it as ANSI, and it solved the problem for us. Might be, that it was a kind of encoding corruption in the file that prohibited Task Scheduler and cmd.exe to open the file, although it was displayed correctly in Notepad.
On our servers it was a problem with the system path. After upgrading PHP runtime (using installation directory whose name includes version number) and updating the path in system variable PATH we were getting status 0x1. System restart corrected the issue. Restarting Task Manager service might have done it, too.
I was running a PowerShell script into the task scheduller but i forgot to enable the execution-policy to unrestricted, in an elevated PowerShell console:
Set-ExecutionPolicy Unrestricted
After that, the error disappeared (0x1).
Just had the same problem here. In my case, the bat files had space " "
After getting rid of spaces from filename and change into underscore, bat file worked
sample before it wont start
"x:\Update & pull.bat"
after rename
"x:\Update_and_pull.bat"
For me the problem was the PowerShell script being ran had #Requires -RunAsAdministrator at the top, meaning it needs to run in an elevated command prompt as an Admin, but the user the Scheduled Task was set to run as wasn't an admin on the local computer. So even though Run with highest privileges was checked in the scheduled task, I still had to make the user an Administrator on the computer. Once I did that, the script ran as expected.
Since there is always more than one reason this could happen I thought I'd share some troubleshooting tips that helped me diagnose my issue.
Always adding a "start in" parameter first since thats an easy fix, even just adding the drive letter can help, e.g. C:\
If you're running "whether user is logged on or not" and it is failing it might be an issue with your user and/or user environment.
Switch the task to run only when user is logged in temporarily for
troubleshooting purposes.
Make sure you're actually logged in AS the user you're telling the task
to run as. (PATH and other environment variables are different by user
and if you see the task running on one user successfully that doesn't
necessarily mean it will run successfully for another user even if they're in the same security group.)
Add pauses or some other type of debugging to your script to give you
time to see any errors that may pop up.
Perform a manual run from the task scheduler window.
Fix any errors you see from your debugging statements. Rinse and repeat.
If it runs successfully switch back to run "whether user is logged on
or not" and try another manual run. If it works now you're all set.
If nothing has helped so far you might need to dig in deeper to your user and file privileges. My troubleshooting tips assume that you have been able to get a past task running using a specific user login already. They don't cover building a scheduled task from a fresh install necessarily. Luckily I haven't had to do that.
What solved it for me was that I was using a local administrator account instead of the domain account so I changed the "Run as" to the domain account.
It turns out that a FTP download call using winscp as last thing to do in the batch caused the problem. After inserting the echo command it works fine. Guess the problems source could be the winscp.exe which do not correctly report the end of the current task to the OS.
del "C:\_ftpcrawler\Account Export.csv" /S /Q
"C:\Program Files (x86)\WinSCP\WinSCP.exe" /console /script="C:\_isource\scripte\data.txt"
echo Download ausgeführt am %date%%time% >> C:\_isource\scripte\data.log

Powershell Script doesn't work when starting it by double-clicking

I got some strange behaviour when executing a powershell script.
When I run my script using the ISE it works just fine.
When I open Powershell.exe and run my script it works just fine.
When I open cmd, and start my script using powershell.exe -noexit
./myscript.ps1, myscript works just fine.
When I double-click myscript however, powershell opens for some milliseconds, I see that it shows some error (red font) and the powershell window closes. I'm unable to track down the error causing this problem since the powershell windows closes to fast.
I even tried one single big try-catch block around my hole script, catching any [Exception] and writing it down to a log file. However: the log file is not generated (catch is not called).
How can I track that issue? What could possibly be causing the trouble?
Please note that my execution-policy is set to unrestricted.
Before trying the suggestion invoke this to see your current settings (if you want restore them later):
cmd /c FType Microsoft.PowerShellScript.1
Then invoke this (note that you will change how your scripts are invoked "from explorer" by this):
cmd /c #"
FType Microsoft.PowerShellScript.1=$PSHOME\powershell.exe -NoExit . "'%1'" %*
"#
Then double-click the script, it should not exit, -NoExit does the trick. See your error messages and solve the problems.
But now all your scripts invoked "from explorer" keep their console opened. You may then
remove -NoExit from the above command and run it again or restore your
original settings.
Some details and one good way to invoke scripts in PS v2 is here.
Unfortunately it is broken in PS v3 - submitted issue.
by default, for security reason when you double clic on a .ps1 file the action is : Edit file, not Run file .
to execute your script : right-click on it and choose run with powershell
I also wasn’t able to run a script by double clicking it although running it manually worked without a problem. I have found out that the problem was in the path. When I ran a script from a path that contained spaces, such as:
C:\Users\john doe\Documents\Sample.ps1
The scipt failed to run. Moving the script to:
C:\Scripts\Sample.ps1
Which has no spaces, solved the problem.
This is most likely an issue with your local Execution Policy.
By default, Powershell is configured to NOT run scripts that are unsigned (even local ones). If you've not signed your scripts, then changing your default double-click 'action' in Windows will have no effect - Powershell will open, read the execution policy, check the script's signature, and finding none, will abort with an error.
In Powershell:
Help about_execution_policies
gives you all the gory details, as well as ways to allow unsigned scripts to run (within reason - you'd probably not want to run remote ones, only ones you've saved onto the system).
EDIT: I see at the tail end of your question that you've set Execution Policy to 'unrestricted' which SHOULD allow the script to run. However, this might be useful info for others running into execution policy issues.
If you would catch the error you will most likely see this
The file cannot be loaded. The file is not
digitally signed. The script will not execute on the system. Please
see "Get-Help about_signing" for more details.
Because you are able to run it from the shell you started yourself, and not with the right mouse button click "Run With PowerShell", I bet you have x64 system. Manually you are starting the one version of PowerShell where execution policy is configured, while with the right click the other version of the PowerShell is started.
Try to start both version x64 and x86 version and check for security policies in each
Get-ExecutionPolicy
I was in exactly the same situation as described in the question : my script worked everywhere except when double-clicking.* When I double-clicked a powershell windows would open but then it will close after a second or so. My execution-policy is also set to unrestricted.
I tried the selected answer concerning FType Microsoft.PowerShellScript.1 but it didn't change anything.
The only solution I found was a work around: create a bat file which start the powershell.
Create a file, copy this and modify the path : powershell.exe -File "C:\Users\user\script\myscript.ps1"
Save it as a .bat
Double-click the bat
I also used .ahk to start my powershell with a shorcut and it didn't work when pointing directly to the powershell. I had to point to the .bat

Starting XAMPP with batch only if it isn't already running

I am writing a batch for a new deployment of my company's software.. Here is what I have so far...
wscript.exe "invisible.vbs" "apache_start.bat" /wait
wscript.exe "invisible.vbs" "mysql_start.bat" /wait
"C:\Program Files\Internet Explorer\iexplore.exe" http://localhost
So as you can see, this script should start apache, then start mysql and then open the default page with IE.
The problem is if the user runs this script twice, it runs apache and mysql twice and loads two seperate instances. The solution I need is a way to check to see if the processes are already running and, if not, run the two wscript commands. I am absolutely horrible with shell, so please try to give specific responses! I am a software engineer, not a sysadmin. Thanks for the help!
As a software engineer I think you have a leg up on scripting over some sysadmins...
Using PowerShell would make this easy. Use the following template to execute the services - you'll need to use it twice, and follow up with launching IE as above.
If ((Get-Process mysqlprocessname.exe)) {Write-Host Skipping MySQL}
Else { Start-Process ...}
This is going to take a few minutes for you to research the best way of starting a process with PowerShell. Also, you might want to pipe Start-Process to Out-Null so the script waits to start IE and Apache.
Others may want to chime in with a simpler way from a batch file.
For XAMPP, there is a pv.exe file in the apache/bin folder that XAMPP uses to see if a service is running. Look at WorldDrknss' answer in this thread for some great info: http://www.apachefriends.org/f/viewtopic.php?p=80047
The code to solve your problem is to modify your mysql_start.bat file to this:
#echo off
apache\bin\pv mysqld.exe %1 >nul
if ERRORLEVEL 1 goto Process_NotFound
echo MySQL is running
goto END
:Process_NotFound
echo Process %1 is not running
mysql\bin\mysqld.exe --defaults-file=mysql\bin\my.ini --standalone --console
goto finish
:finish
That will check if mysqld.exe is running. If it is, it just echos that out. If not, it starts the service.