将 WmiEvent Powershell 脚本注册为本地 GPO - 控制 USB
Register-WmiEvent Powershell script as a local GPO - Control USB
很多天来,我一直在与我想要 运行 的脚本作斗争,以便控制用户何时将 USB 记忆棒插入工作站。
这是脚本的简化版本。
Unregister-Event RemovableDiskDetection
$query = "SELECT * FROM __InstanceOperationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2"
Register-WmiEvent -Query $query -SourceIdentifier RemovableDiskDetection -Action {
$class = $eventArgs.NewEvent.__CLASS
$device = $eventArgs.NewEvent.TargetInstance.DeviceID
$wshell = New-Object -ComObject Wscript.Shell
switch($class)
{
__InstanceCreationEvent {
$path = $device + "\flag"
Write-Host "*** Checking the existence of the file $path"
if(Test-Path -Path $path)
{
$wshell.Popup("Inserted, device id: $device WITH flag",0,"Done",0x1)
}
else{
$wshell.Popup("Inserted, device id: $device WITHOUT flag",0,"Done",0x1)
}
}
__InstanceDeletionEvent {
$wshell.Popup("Removed, device id: $device ",0,"Done",0x1)
}
}
}
如果我 运行 来自 Windows Powershell ISE 的脚本,它会按预期工作。如果我打开 CMD window 和 运行 命令 "powershell -noexit -file basicUSBControl.ps1" ,它也会按预期工作。
我的问题是,当我尝试为整台计算机设置此脚本的执行时,会影响到可能登录计算机的任何用户。
我尝试通过本地组策略编辑器。我去了
计算机配置-->Windows设置-->脚本-->启动
然后我选择 Powershell 脚本选项卡并设置与之前相同的脚本。我还在下拉框中选择了选项“运行 Windows Powershell scripts first”。
然后我继续重新启动计算机并登录它,但无论何时插入任何 U 盘似乎都没有任何反应。
知道会发生什么吗?有人可以帮我吗?我快疯了,也许我无法做我需要做的事……
我还尝试了计划任务,结果任务状态一直显示 "Running" 但没有捕获事件,插拔 USB 棒时不显示弹出窗口...:/
非常感谢!
解决方案是在创建计划任务的地方创建一个 GPO。
在那里你可以指定将 运行 脚本的用户,在我的例子中,
%LogonDomain%\%LogonUser%
很多天来,我一直在与我想要 运行 的脚本作斗争,以便控制用户何时将 USB 记忆棒插入工作站。 这是脚本的简化版本。
Unregister-Event RemovableDiskDetection
$query = "SELECT * FROM __InstanceOperationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2"
Register-WmiEvent -Query $query -SourceIdentifier RemovableDiskDetection -Action {
$class = $eventArgs.NewEvent.__CLASS
$device = $eventArgs.NewEvent.TargetInstance.DeviceID
$wshell = New-Object -ComObject Wscript.Shell
switch($class)
{
__InstanceCreationEvent {
$path = $device + "\flag"
Write-Host "*** Checking the existence of the file $path"
if(Test-Path -Path $path)
{
$wshell.Popup("Inserted, device id: $device WITH flag",0,"Done",0x1)
}
else{
$wshell.Popup("Inserted, device id: $device WITHOUT flag",0,"Done",0x1)
}
}
__InstanceDeletionEvent {
$wshell.Popup("Removed, device id: $device ",0,"Done",0x1)
}
}
}
如果我 运行 来自 Windows Powershell ISE 的脚本,它会按预期工作。如果我打开 CMD window 和 运行 命令 "powershell -noexit -file basicUSBControl.ps1" ,它也会按预期工作。
我的问题是,当我尝试为整台计算机设置此脚本的执行时,会影响到可能登录计算机的任何用户。 我尝试通过本地组策略编辑器。我去了 计算机配置-->Windows设置-->脚本-->启动 然后我选择 Powershell 脚本选项卡并设置与之前相同的脚本。我还在下拉框中选择了选项“运行 Windows Powershell scripts first”。
然后我继续重新启动计算机并登录它,但无论何时插入任何 U 盘似乎都没有任何反应。
知道会发生什么吗?有人可以帮我吗?我快疯了,也许我无法做我需要做的事…… 我还尝试了计划任务,结果任务状态一直显示 "Running" 但没有捕获事件,插拔 USB 棒时不显示弹出窗口...:/
非常感谢!
解决方案是在创建计划任务的地方创建一个 GPO。 在那里你可以指定将 运行 脚本的用户,在我的例子中, %LogonDomain%\%LogonUser%