I am trying to run this script in PowerShell. I have saved the below script as ps.ps1
on my desktop.
$query = "SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"
Register-WMIEvent -Query $query -Action { invoke-item "C:\Program Files\abc.exe"}
I have made a batch script to run this PowerShell script
@echo off
Powershell.exe set-executionpolicy remotesigned -File C:\Users\SE\Desktop\ps.ps1
pause
But I am getting this error:
If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:
It is better to use
Bypass
...I explain both why you would want to call a PowerShell script from a batch file and how to do it in my blog post here.
This is basically what you are looking for:
And if you need to run your PowerShell script as an admin, use this:
Rather than hard-coding the entire path to the PowerShell script though, I recommend placing the batch file and PowerShell script file in the same directory, as my blog post describes.
If your PowerShell login script is running after 5 minutes (as mine was) on a 2012 server, there is a GPO setting on a server - 'Configure Login script Delay' the default setting 'not configured' this will leave a 5-minute delay before running the login script.
If you want to run from the current directory without a fully qualified path, you can use:
You need the
-ExecutionPolicy
parameter:Otherwise PowerShell considers the arguments a line to execute and while
Set-ExecutionPolicy
is a cmdlet, it has no-File
parameter.If you want to run a few scripts, you can use
Set-executionpolicy -ExecutionPolicy Unrestricted
and then reset withSet-executionpolicy -ExecutionPolicy Default
.Note that execution policy is only checked when you start its execution (or so it seems) and so you can run jobs in the background and reset the execution policy immediately.