@dshumov
Олдскул - Фигурнов форева

Почему скрипт Powershell выполняется не сразу весь а по частям?

Здравствуйте!
Есть скрипт Powershell назначенный на логон пользователю. В консоли, он выполняется весь и сразу. А если применить политику на пользователя, то чтобы он выполнился полностью, нужно перезагружаться. Т.е. одна часть выполнилась, перезагрузились, выполнилась вторая часть скрипта.
Что делает скрипт: 1) Назначает пользователю корпоративную подпись в Outlook 2) Устанавливает ее по умолчанию, и запрещает редактировать.
СКРИПТ
#Custom variables
$CompanyName = 'CraftGroup'
$SigSource = "\\group.com\SysVol\group.com\Scripts\Signatures\$CompanyName"
$ForceSignatureNew = '1' #When the signature are forced the signature are enforced as default signature for new messages the next time the script runs. 0 = no force, 1 = force
$ForceSignatureReplyForward = '1' #When the signature are forced the signature are enforced as default signature for reply/forward messages the next time the script runs. 0 = no force, 1 = force

#Environment variables
$AppData=(Get-Item env:appdata).value
$SigPath = '\Microsoft\Signatures'
$LocalSignaturePath = $AppData+$SigPath
$LocalSignatureFile = $LocalSignaturePath+'\'+$CompanyName+'.htm'
$RemoteSignaturePathFull = $SigSource+'\'+$CompanyName+'.htm'

#Get Active Directory information for current user
$UserName = $env:username
$Filter = "(&(objectCategory=User)(samAccountName=$UserName))"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter = $Filter
$ADUserPath = $Searcher.FindOne()
$ADUser = $ADUserPath.GetDirectoryEntry()
$ADDisplayName = $ADUser.DisplayName
#$ADEmailAddress = $ADUser.mail
$ADTitle = $ADUser.title
$ADTelePhoneNumber = $ADUser.mobile
#Setting registry information for the current user
$CompanyRegPath = "HKCU:\Software\"+$CompanyName

if (Test-Path $CompanyRegPath)
{}
else
{New-Item -path "HKCU:\Software" -name $CompanyName}

if (Test-Path $CompanyRegPath'\Outlook Signature Settings')
{}
else
{New-Item -path $CompanyRegPath -name "Outlook Signature Settings"}

$SigVersion = (gci $RemoteSignaturePathFull).LastWriteTime #When was the last time the signature was written
$ForcedSignatureNew = (Get-ItemProperty $CompanyRegPath'\Outlook Signature Settings').ForcedSignatureNew
$ForcedSignatureReplyForward = (Get-ItemProperty $CompanyRegPath'\Outlook Signature Settings').ForcedSignatureReplyForward
$SignatureVersion = (Get-ItemProperty $CompanyRegPath'\Outlook Signature Settings').SignatureVersion
Set-ItemProperty $CompanyRegPath'\Outlook Signature Settings' -name SignatureSourceFiles -Value $SigSource
#присваиваем переменные взяв значения из реестра
$TelephoneNumberREG = (Get-ItemProperty $CompanyRegPath'\Outlook Signature Settings').TelephoneNumber
$DisplayNameREG = (Get-ItemProperty $CompanyRegPath'\Outlook Signature Settings').DisplayName
#$EmailAddressREG = (Get-ItemProperty $CompanyRegPath'\Outlook Signature Settings').EmailAddress
$ADTitleREG = (Get-ItemProperty $CompanyRegPath'\Outlook Signature Settings').ADTitle

$SignatureSourceFiles = (Get-ItemProperty $CompanyRegPath'\Outlook Signature Settings').SignatureSourceFiles

$grog = Get-ChildItem $LocalSignaturePath
$FileExists =  Test-Path "$LocalSignatureFile"

#Write-Output $LocalSignaturePath
#Write-Output $LocalSignatureFile
#Write-Output $SignatureSourceFiles
#Write-Output $RemoteSignaturePathFull
#Write-Output $ADTelephoneNumber
#Write-Output $ADDisplayName
#Write-Output $ADTitle
#Write-Output $FileExists
#Write-Output $grog
#Write-Output "----------------------------------"
Get-ChildItem -Path $LocalSignaturePath -Recurse | Remove-Item -Force;
#Write-Output "----------------------------------"

if ($LocalSignatureFile -eq $FileExists) {

    #Write-Output "+++Файл существует!+++"

        if ($SignatureVersion -ne $SigVersion) {
            Get-ChildItem -Path $LocalSignaturePath -Recurse | Remove-Item -Force;
            Copy-Item "$RemoteSignaturePathFull" $LocalSignaturePath -Recurse -Force;
        }

    } else {

        #Write-Output "---Файла нет---"

        #Write-Output "Началось копирование в папку юзера"

        Copy-Item "$RemoteSignaturePathFull" $LocalSignaturePath -Recurse -Force;
}
	#Write-Output $FileExists

	#Write-Output "Пытаемся заменить параметры в файле"
	
    (Get-Content $LocalSignatureFile -Encoding UTF8) -replace "@TelephoneNumber",$ADTelephoneNumber -replace "@DisplayName", $ADDisplayName -replace "@Title", $ADTitle | Set-Content $LocalSignatureFile -Encoding UTF8

	#Stamp registry-values for Outlook Signature Settings if they doesn`t match the initial script variables. Note that these will apply after the second script run when changes are made in the "Custom variables"-section.
if ($ForcedSignatureNew -eq $ForceSignatureNew){}
else
{Set-ItemProperty $CompanyRegPath'\Outlook Signature Settings' -name ForcedSignatureNew -Value $ForceSignatureNew}

if ($ForcedSignatureReplyForward -eq $ForceSignatureReplyForward){}
else
{Set-ItemProperty $CompanyRegPath'\Outlook Signature Settings' -name ForcedSignatureReplyForward -Value $ForceSignatureReplyForward}

if ($SignatureVersion -eq $SigVersion){}
else
{Set-ItemProperty $CompanyRegPath'\Outlook Signature Settings' -name SignatureVersion -Value $SigVersion}

#проверить актуальность тел. номера
if ($TelephoneNumberREG -eq $ADTelePhoneNumber){}
else
{Set-ItemProperty $CompanyRegPath'\Outlook Signature Settings' -name TelephoneNumber -Value $ADTelePhoneNumber}

#проверить актуальность ФИО
if ($DisplayNameREG -eq $ADDisplayName){}
else
{Set-ItemProperty $CompanyRegPath'\Outlook Signature Settings' -name DisplayName -Value $ADDisplayName}

#проверить актуальность должности
if ($ADTitleREG -eq $ADTitle){}
else
{Set-ItemProperty $CompanyRegPath'\Outlook Signature Settings' -name ADTitle -Value $ADTitle}


#Вот до этого места скрипт выполняется в первый раз. Чтобы применилась последующая нужно #перезагрузиться (она как раз отвечает за назначение подписи по умолчанию и запрет редактирования)

#Office 2016
If ((Test-Path HKCU:'\Software\Microsoft\Office\16.0') -and ($ForcedSignatureNew -eq '1')) { 
        New-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'NewSignature' -Value $CompanyName -PropertyType 'ExpandString' -Force  
        New-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'ReplySignature' -Value $CompanyName -PropertyType 'ExpandString' -Force 
		
		#Remove-ItemProperty -Path HKCU:\Software\Microsoft\Office\16.0\Common\MailSettings -Name ReplySignature -Force -ErrorAction SilentlyContinue 
        #Remove-ItemProperty -Path HKCU:\Software\Microsoft\Office\16.0\Common\MailSettings -Name NewSignature -Force -ErrorAction SilentlyContinue 
		
		If (Get-ItemProperty -Name 'NewSignature' -Path HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings') {Remove-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'NewSignature' -Value $CompanyName -PropertyType 'ExpandString' -Force }  
			Else {  
				New-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'NewSignature' -Value $CompanyName -PropertyType 'ExpandString' -Force  
				#Remove-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'NewSignature' -Value $CompanyName -PropertyType 'ExpandString' -Force  
			}  
		If (Get-ItemProperty -Name 'ReplySignature' -Path HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings') { Remove-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'ReplySignature' -Value $CompanyName -PropertyType 'ExpandString' -Force  }  
			Else {  
				
				New-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'ReplySignature' -Value $CompanyName -PropertyType 'ExpandString' -Force 
				#Remove-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'ReplySignature' -Value $CompanyName -PropertyType 'ExpandString' -Force 
			}   
} 
If ((Test-Path HKCU:'\Software\Microsoft\Office\15.0') -and ($ForcedSignatureNew -eq '1')) { 
        New-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'NewSignature' -Value $CompanyName -PropertyType 'ExpandString' -Force  
        New-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'ReplySignature' -Value $CompanyName -PropertyType 'ExpandString' -Force 
		
		#Remove-ItemProperty -Path HKCU:\Software\Microsoft\Office\15.0\Common\MailSettings -Name ReplySignature -Force -ErrorAction SilentlyContinue 
        #Remove-ItemProperty -Path HKCU:\Software\Microsoft\Office\15.0\Common\MailSettings -Name NewSignature -Force -ErrorAction SilentlyContinue 
		
		If (Get-ItemProperty -Name 'NewSignature' -Path HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings') {Remove-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'NewSignature' -Value $CompanyName -PropertyType 'ExpandString' -Force }  
			Else {  
				New-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'NewSignature' -Value $CompanyName -PropertyType 'ExpandString' -Force  
				#Remove-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'NewSignature' -Value $CompanyName -PropertyType 'ExpandString' -Force  
			}  
		If (Get-ItemProperty -Name 'ReplySignature' -Path HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings') { Remove-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'ReplySignature' -Value $CompanyName -PropertyType 'ExpandString' -Force}  
			Else {  
				New-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'ReplySignature' -Value $CompanyName -PropertyType 'ExpandString' -Force 
				#Remove-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'ReplySignature' -Value $CompanyName -PropertyType 'ExpandString' -Force 
			}  
}

  • Вопрос задан
  • 120 просмотров
Пригласить эксперта
Ответы на вопрос 1
@azarij
В меру опытный никто
возможно, скрипт выполняется полностью, но изменения которые он в реестр пишет применяются только при следующем логине юзверя? если так, то как это обойти трудно сказать. хотя... можно попробовать устанавливать подпись через Exchange EWS, но я не знаю можно ли там запретить ее изменение...
вставьте во вторую часть скрипта что-то, что создаст пустой файл гденить и посмотрите создастся ли файл при первом прогоне через гпо.
set-content c:\test\test.file -force
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы