I have a powershell script I am trying to execute and I have placed it inside a GPO under Computer ConfigurationPoliciesWindows SettingsScriptsStartup. I receive and Event 1130 Error in the System log on the target PC with the a listing of the network
share the script is contained, \domain.comSysVoldomain.comPolicies {GUID}Machine. I have made certain that the machine, authenticated users, domain computers all have at least read and execute permissions. Although, when I go to run the script directly
from the path above after logon, I get Access is denied.
Other settings I have tried to get this script to run:
Under System/Group Policy, «Configure Environment preference extension policy processing»= Enabled with «Allow processing across slow network connection» also enabled as well as «Process even if group policy objects have not changed»
is enabled.
«Configure Network Options preference extension policy processing» is «Enabled»
«Configure Logon Script Delay» = Enabled and set to 0
Under SystemLogon, «Always wait for the network at computer startup and logon» = Enabled
Under Windows Components/Windows Powershell, «Turn on Script Execution» with Execution Policy set to «Allow local scripts and remote signed scripts».
How do I correct the error so as to allow logon.
I have a powershell script I am trying to execute and I have placed it inside a GPO under Computer ConfigurationPoliciesWindows SettingsScriptsStartup. I receive and Event 1130 Error in the System log on the target PC with the a listing of the network
share the script is contained, \domain.comSysVoldomain.comPolicies {GUID}Machine. I have made certain that the machine, authenticated users, domain computers all have at least read and execute permissions. Although, when I go to run the script directly
from the path above after logon, I get Access is denied.
Other settings I have tried to get this script to run:
Under System/Group Policy, «Configure Environment preference extension policy processing»= Enabled with «Allow processing across slow network connection» also enabled as well as «Process even if group policy objects have not changed»
is enabled.
«Configure Network Options preference extension policy processing» is «Enabled»
«Configure Logon Script Delay» = Enabled and set to 0
Under SystemLogon, «Always wait for the network at computer startup and logon» = Enabled
Under Windows Components/Windows Powershell, «Turn on Script Execution» with Execution Policy set to «Allow local scripts and remote signed scripts».
How do I correct the error so as to allow logon.
- Remove From My Forums
-
Вопрос
-
Hello All,
I’m trying to apply the following computer startup script
I’ve set up the following powershell script to disable NetBIOS
$adapters=(gwmi win32_networkadapterconfiguration) Foreach ($adapter in $adapters){ Write-Host $adapter $adapter.settcpipnetbios(2) }
The script works fine locally. I added a schedule task under the SYSTEM account and it ran with no problems. It only fails in the computer startup via GPO
This is the error I’m receiving via event viewerEventData SupportInfo1 900986720 SupportInfo2 90 ErrorCode 267 ErrorDescription The directory name is invalid. ScriptType 0 GPODisplayName Computer Starup Script - Disable NetBIOS over TCP/IP GPOFileSystemPath \HERPSysVolDERPPolicies{GUID}Machine GPOScriptCommandString Disable_NetBIOS_over_TCPIP.ps1
Any help would be appreciated.
extra info. I’m testing this GPO on a windows 8.1 machine. This script works fine on a server 2008, server 2012, and server 2012 R2
Ответы
-
Hi Stephen,
Based on the description, where is the startup script stored? Please double make sure that the computer account in question has enough permissions to access the script.
Regarding Event ID 1130, the following article can be referred to for more information.
Event ID 1130 — Group Policy Scripts Processing
https://technet.microsoft.com/en-us/library/dd392581(v=ws.10).aspx
Best regards,
Frank Shen
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.
-
Помечено в качестве ответа
13 июля 2015 г. 2:20
-
Помечено в качестве ответа
Hello Spiceheads.
Our organization is currently working on rolling out Teams org-wide to replace Skype for Business, and part of that process involves me setting up a Group Policy to install Teams remotely to everyone’s computers. I was originally going to simply deploy the .msi file for the Teams machine-wide installer, but then after some research, I discovered that only installs Teams for users signing into a PC for the first time, which wouldn’t help me at all right now, since I need it installed for everyone on their existing machine. So, I did some more digging and found a handy PowerShell script that runs the regular .exe installer from a specified network share, after checking if Teams is already installed.
So, I placed the .exe installer in a network share that’s open to all authenticated users, added the powershell script as a Logon (user) script to a GPO linked to a test OU (with a test user and computer in it), and then ran logged off the computer and logged back in as the test user. It didn’t install Teams, so I checked Event Viewer and found an error. «Logon script failed», with an Event ID of 1130 and ErrorDescription of «Incorrect Function» I’ve been doing some Googling and found several other posts, including on Spiceworks, that reported similar issues, but none helped me fix my issue. I already double-checked the file permissions on the script and the .exe, so that’s not the problem. I was also able to run the PowerShell script manually and it worked just fine, it’s just won’t run automatically via GP. I did check the Execution Policy for PowerShell, and it says it’s Unrestricted, so that shouldn’t be the issue either.
The script is stored in the default \<domain>SysVol<domain>Policies<policy>UserScriptsLogon folder, and the .exe is stored in our company share directory. I specified «-SourcePath \<path>» for the script in GP; I tried with both the DNS name and the IP address, neither worked.
Script: https://gallery.technet.microsoft.com/scriptcenter/Install-Teams-Desktop-b1ffd424 Opens a new window
Script author’s blog post with instructions:
https://practical365.com/collaboration/teams/deploying-microsoft-teams-desktop-client/ Opens a new window
Script code:
Powershell
<# .SYNOPSIS Install-MicrosoftTeams.ps1 - Microsoft Teams Desktop Client Deployment Script .DESCRIPTION This PowerShell script will silently install the Microsoft Teams desktop client. The Teams client installer can be downloaded from Microsoft: https://teams.microsoft.com/downloads .PARAMETER SourcePath Specifies the source path for the Microsoft Teams installer. .EXAMPLE .Install-MicrosoftTeams.ps1 -Source \mgmtInstallsMicrosoftTeams Installs the Microsoft Teams client from the Installs share on the server MGMT. .NOTES Written by: Paul Cunningham Find me on: * My Blog: http://paulcunningham.me * Twitter: https://twitter.com/paulcunningham * LinkedIn: http://au.linkedin.com/in/cunninghamp * Github: https://github.com/cunninghamp For more Office 365 tips, tricks and news check out Practical 365. * Website: http://practical365.com * Twitter: http://twitter.com/practical365 Change Log V1.00, 15/03/2017 - Initial version #> #requires -version 4 [CmdletBinding()] param ( [Parameter(Mandatory=$true)] [string]$SourcePath ) function DoInstall { $Installer = "$($SourcePath)Teams_windows_x64.exe" If (!(Test-Path $Installer)) { throw "Unable to locate Microsoft Teams client installer at $($installer)" } Write-Host "Attempting to install Microsoft Teams client" try { $process = Start-Process -FilePath "$Installer" -ArgumentList "-s" -Wait -PassThru -ErrorAction STOP if ($process.ExitCode -eq 0) { Write-Host -ForegroundColor Green "Microsoft Teams setup started without error." } else { Write-Warning "Installer exit code $($process.ExitCode)." } } catch { Write-Warning $_.Exception.Message } } #Check if Office is already installed, as indicated by presence of registry key $installpath = "$($env:LOCALAPPDATA)MicrosoftTeams" if (-not(Test-Path "$($installpath)Update.exe")) { DoInstall } else { if (Test-Path "$($installpath).dead") { Write-Host "Teams was previously installed but has been uninstalled. Will reinstall." DoInstall } }
It also looks like the script author is a Spicehead, so I tagged him as well (maybe? I think it’s the same person).
прежде всего убедитесь, что политика применяется runnin rsop из командной строки на компьютере.
во-вторых, убедитесь, что скрипт доступен из общей папки, которую политика будет читать из нее.
Не говоря уже о некоторых политиках, требующих перезагрузки даже после gpupdate / force . Если он находится в разделе Конфигурация пользователя и применяется в подразделении компьютеров, убедитесь, что для режима обработки замыкания на себя установлено значение объединено.
Что Я подозреваю, что есть проблема с пакетный файл вызова файла vbs я бы рекомендовал следующее:
запустить командную строку и попробовать назвать файл вручную один раз из-за повышенного cmd и в другой раз от нормального ЦМД, и это действительно зависит от методов, которые вы пытаетесь вызвать VBS файл с Либо это cscript или WScript сейчас, не говоря уже о том, что некоторые из этих пакетных файлов лучше быть настроен в качестве входа скрипты в настройках пользователя, а не компьютер (который я предпочитать.)
теперь попробуйте отредактировать пакетный файл, вызывающий скрипт, следующим образом:
@echo off
%WINDIR%SysWOW64cmd.exe
cscript script.vbs or pathscript.vbs
Я думаю, что лучше хранить сценарий в общей папке Sysvol. Или можно просто добавить сценарий vbs в сценарий входа. Кроме того, если вставить содержимое пакетного файла было бы легче диагностировать, что происходит.
Обновлено 17.07.2019
Добрый день! Уважаемые читатели и гости одного из крупнейших IT порталов в России Pyatilistnik.org. В прошлый раз вы меня просили рассказать вам, о рабочих методах исправления черного экрана Windows 10 и я с вами ими поделился. Так как направленность моего ресурса больше рассчитана на системных администраторов и продвинутых пользователей, то я сегодня хочу вновь поговорить про групповые политики и автоматизацию получаемую благодаря им. В данной публикации речь пойдет, о запуске скрипта PowerShell средствами GPO (Групповой политики), мы рассмотрим все варианты доступные администраторам.
Постановка задачи
Когда начинающий системный администратор превращается в матерого админа, он хочет везде все автоматизировать и везде экономить свое время, и это логично люди существа любящие комфорт и лень. Рабочая среда Active Directory позволяет, как все знаете через групповые политики настройку почти всех компонентов в системе, а что не может замещается средствами PowerShell, вот такой симбиоз. В нашу задачу входит научиться запускать при загрузке компьютера или при входе пользователя на компьютер или сервер, наш скрипт PowerShell, который реализует ту или иную задачу, это не важно, пусть например монтирует базы 1С.
Методы запуска скрипта PowerShell через GPO
Существует несколько сценариев позволяющих вам применять к вашим объектам нужные скрипты:
- Скрипт применяется в автозагрузке системы, в момент загрузки операционной системы
- Скрипт отработает во время входа или выхода пользователя из системы
- Ну и запуск скрипта по расписанию, такое то же имеет место быть
Запуск PowerShell скрипта в автозагрузке сервера
Открываем оснастку «Управление групповой политикой» и создаем на нужном уровне вашей иерархии организационных подразделений, новую политику, в моем примере, это будет «Добавление баз 1С». Переходим к ее редактированию.
Для того, чтобы при загрузке вашего сервера или компьютера, к нему применялся нужный вам сценарий PowerShell вам необходимо перейти в раздел:
Конфигурация компьютера — Политики — Конфигурация Windows — Сценарий (запуск/завершение) (Computer Configuration — Policies — Windows Settings — Scripts (Startup/Shutdown)
Тут вы увидите два возможных варианта «Автозагрузка» и «Завершение работы»
Далее вы открываете пункт «Автозагрузка», переходите на вкладку «Сценарий PowerShell» и нажимаете кнопку «Добавить«. Через окно «добавление сценария» откройте папку «Startup» и скопируйте туда ваш скрипт. Теперь данный файл будет частью папки Sysvol и располагаться в конкретном GPO объекте.
Так же хочу отметить, что вы можете задать порядок выполнения PowerShell сценария в соответствующей области, выбрав будет ли он выполнятся после других сценариев или перед.
Еще есть ряд нюансов при использовании выполнения скриптов PowerShell средствами групповой политики:
- Во первых по умолчанию в Windows есть 5-ти минутная задержка выполнения скриптом, как ее отключать я рассказывал можете почитать вот тут.
- Если у вас в локальной сети присутствуют операционные системы по типу Windows Server 2008 или ниже, то там есть подводные камни в виде выполнения неподписанных скриптов и во вторых в старой версии PowerShell
Хочу отметить, что начиная с Windows Server 2012 R2, Windows 8.1 и выше, все запускаемые сценарии PowerShell через GPO работают в режиме Bypass, что подразумевает игнорирование политики Set-ExecutionPolicy. Но если у вас есть более старые клиенты, то вы можете пойти вот таким путем:
Вы можете явно указать исполняемый файл PowerShell, для этого в политике откройте вкладку «Сценарии», нажмите добавить. В имя сценария введите путь до файла powerShell, это:
%windir%System32WindowsPowerShellv1.0powershell.exe
В параметрах сценария введите вот такие ключи и сетевой путь до скрипта PowerShell.
-Noninteractive -ExecutionPolicy Bypass –Noprofile -file \root.pyatilistnik.orgSysVolroot.pyatilistnik.org Policies{2B79FA3E-CB2F-4D15-A446-3DBBF887CD40} MachineScriptsStartupAdd-Base-1C.ps1
Еще для подстраховки вы можете включить параметр GPO
Конфигурация компьютера — Административные шаблоны — Компоненты Windows — Windows Powershell
(Computer Configuration — Administrative Templates — Windows Components — Windows PowerShell)
Активируем настройку «Включить выполнение сценариев (Turn On Script Execution)», выставим значение «Разрешать все сценарии«.
Небольшой совет, я бы вам рекомендовал включать выполнение всех сценариев исключительно для старых ОС, для этого вы можете сделать отдельную политику и применить ее только к старым операционным системам, через WMI фильтр
Проверяем применение вашей GPO, если все настроили правильно она отработает если нет, то начинается траблшутинг, проверяете фильтры GPO и общий алгоритм поиска проблем.
Запуск PowerShell скрипта для пользователя
Чтобы применить к пользователю ваш скрипт, вам необходимо в объекте групповой политики открыть вот такую ветку:
Конфигурация пользователя — Политики — Конфигурация Windows — Сценарии (Вход/Выход из системы) (User Configuration — Policies — Windows Settings — Scripts
Тут будет два варианта «Вход в систему» и «Выход из системы».
Настраиваем аналогично, как я показывал выше для компьютера, все одинаково.
Выполнение сценариев PowerShell по расписанию
Тут все просто, если вы хотите средствами групповой политики запускать скрипты PowerShell по расписанию, то вам нужно создать задание в шедуллере. Для этого есть ветки GPO:
Конфигурация пользователя — Настройки — Параметры панели управления — Назначенные задания
Конфигурация компьютера — Настройки — Параметры панели управления — Назначенные задания
Указываем в задании нужное время, имя и сетевой путь до скрипта.
Как видите все просто. С вами был Иван Семин, автор и создатель IT портала Pyatilistnik.org.
Прежде всего убедитесь, что политика применяется runnin rsop из командной строки на компьютере.
Во-вторых, убедитесь, что скрипт доступен из общей папки, из которой будет считываться политика.
Не говоря уже о некоторых политиках, требуется перезагрузка даже после gpupdate /force. Если он размещен в пользовательской конфигурации и вы применяете его на OU компьютеров, убедитесь, что режим обработки обратной петли установлен на объединение.
Что я подозреваю, что есть проблема с командным файлом, вызывающим файл VBS, я бы порекомендовал следующее:
Запустите командную строку и попробуйте вызвать файл вручную один раз из повышенного cmd и в другой раз из обычного cmd, и это действительно зависит от методов, которые вы пытаетесь вызвать файл vbs с помощью cscript или wscript, не говоря уже о что некоторые из этих командных файлов лучше всего настраивать как сценарии входа в систему в настройках пользователя, а не на компьютере (что я предпочитаю).
Теперь попробуйте отредактировать командный файл, который вызывает скрипт следующим образом:
@echo off
%WINDIR%SysWOW64cmd.exe
cscript script.vbs or \pathscript.vbs
Я думаю, что лучше хранить сценарий в общей папке Sysvol. Или вы можете просто добавить скрипт vbs в скрипт входа в систему. Также, если вы вставите содержимое командного файла, будет проще диагностировать, что происходит.
- Remove From My Forums
-
Question
-
We have a GPO with a single startup script — an EXE that launches from a network share — applied to an OU for workstations. The GPO fails to execute the app at startup and an 1130 event is logged in the events of the workstations. This is the intended way
to deploy the software from the vendor of the app, who insists something is just wrong with our AD/workstations.So far I have:
- Verified the GPO is being applied correctly via GPResult (it is — otherwise this error wouldn’t even appear) and the permissions on the GPO are at their default.
- Verified Authenticated Users have access to the files needed, both in share and NTFS permissions. I even tried explicitly adding a test workstation by name to the permissions.
- Changed the «Specify startup policy processing wait time» to 60 and enabled the «Always Wait for the Network at Computer Startup and Logon» policy.
- Tried moving the path for the EXE and associated files to the NETLOGON folder.
- Verified a test batch file that writes the date/time to a dummy file is able to run during startup
from the same GPO. - Verified we can run the EXE from the share using psexec with the -s option to execute as the local system account.
Any idea what else we can do to troubleshoot this issue? Because of the nature of the software, it has to run at startup — we can’t simply deploy it with PDQ or another packager post-boot.
Paul Hite — MCSE, MCITP
Answers
-
We had already checked that out, but we did find the issue. Turned out to be antivirus, which was the very first thing I had checked. We have a ticket open with them now because nothing in the management console or even in the local AV agents logs with
verbose mode enabled indicated any sort of blocks occurring and all the apps involved are explicitly whitelisted.
Paul Hite — MCSE, MCITP
-
Marked as answer by
Tuesday, June 18, 2019 1:42 PM
-
Marked as answer by