W
W
Warikos2021-11-19 13:05:15
PowerShell
Warikos, 2021-11-19 13:05:15

Error in powershell script syntax, can't find it?

There is a powershell script that works with a .docx document
. After it has worked, the document is saved, but the viewing style changes to a web document.
I want to add at the end of the document so that in the active document the view mode changes to "page markup"
Since in the syntax of powershell and in general in the syntax of any language I am a little less than 0, but I can figure out how to do it.
Here is a piece of code that doesn't work.

#Set variables for New-Object -com word.application
$ReplaceAll = 2
$FindContinue = 1
$MatchCase = $True
$MatchWholeWord = $True
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False

#Start generating
$MSWord = New-Object -com word.application
$MSWord.Documents.Open($fullPath)

$FindText = "DisplayName"
$ReplaceText = $ADDisplayName.ToString()
$ MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll )

$FindText = "Title"
$ReplaceText = $ADTitle.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format , $ReplaceText, $ReplaceAll )

$FindText = "Telephone"
$ReplaceText = $ADTelePhoneNumber.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $ Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll )

$FindText = "Department"
$ReplaceText = $ADDepartment.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll )

$MSWord.Selection.Find.Execute("Email")
$MSWord.ActiveDocument.Hyperlinks.Add($MSWord.Selection.Range, "mailto:"+$ADEmailAddress.ToString(), $missing, $missing, $ADEmailAddress. ToString()) #Save

modified document
$MSWord.ActiveDocument.Save()
#Generate HTM
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatHTML");
[ref]$BrowserLevel = "microsoft.office.interop.word.WdBrowserLevel" -as [type]
$MSWord.ActiveDocument.WebOptions.OrganizeInFolder = $true
$MSWord.ActiveDocument.WebOptions.UseLongFileNames = $true
$MSWord.ActiveDocument.WebOptions .BrowserLevel = $BrowserLevel::wdBrowserLevelMicrosoftInternetExplorer6
$path = $LocalSignaturePath+"\"
$MSWord.ActiveDocument.saveas([ref]$path, [ref]$saveFormat)

#Generate RTF
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatRTF");
$path = $LocalSignaturePath+"\"+$CompanyName+".rtf"
$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$saveFormat)

#Generate TXT
$saveFormat = [Enum]::Parse([Microsoft. Office.Interop.Word.WdSaveFormat], "wdFormatText");

#Not needed
#$path = $LocalSignaturePath+"\"+$CompanyName+".rtf"
#$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$saveFormat)

$path = $LocalSignaturePath+"\"+$CompanyName+ ".txt"
$MSWord.ActiveDocument.SaveAs([ref] $path,

$MSWord.Application.Visible = $true
$MSWord.ActiveWindow.View = [Microsoft.Office.Interop.Word.WdViewType]"wdNormalView"
$MSWord.ActiveDocument.Close()
$MSWord.Quit()

}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
MaxKozlov, 2021-11-19
@MaxKozlov

If you change something in the active document, and then immediately close it without saving, then what do you expect to see in the saved document?
Or in the unsaved, but somewhere else? but in general you have } at the end for some reason
. If you are interested in what the WebView is called, then here is a list for you

[enum]::GetValues([Microsoft.Office.Interop.Word.WdViewType])

Name           Value
----           -----
wdNormalView       1
wdOutlineView      2
wdPrintView        3
wdPrintPreview     4
wdMasterView       5
wdWebView          6
wdReadingView      7
wdConflictView     8

# и если обойтись без кавычек, PSReadline ещё и подсказки даст по ctrl+space после ::
[Microsoft.Office.Interop.Word.WdViewType]::wdWebView

R
Roman Bezrukov, 2021-11-19
@NortheR73

Trying to attach signatures for mail? (judging by the set of processed files) ...
I created template files (html, rtf, txt) of the form

Best regards,
@NAME
@DESCRIPTION
@COMPANY
@POSTALCODE, @CITY, @STREETADDRESS
Phone: @OFFICEPHONE
E-mail: @EMAIL
WWW: @WEBSITE

further in the code I substituted the values:
Foreach ($Ext in $FileExt)
{
    $UserSign = Get-Content "$PathSignatureUser\$FileName.$Ext"
    $UserSign = $UserSign -replace "@NAME", $AD_user.DisplayName
    $UserSign = $UserSign -replace "@DESCRIPTION", $AD_user.Title
    $UserSign = $UserSign -replace "@COMPANY", $AD_user.Company
    $UserSign = $UserSign -replace "@STREETADDRESS", $AD_user.StreetAddress
    $UserSign = $UserSign -replace "@POSTALCODE", $AD_user.PostalCode
    $UserSign = $UserSign -replace "@CITY", $AD_user.L
    $UserSign = $UserSign -replace "@OFFICEPHONE", $AD_user.Mobile
    $UserSign = $UserSign -replace "@EMAIL", $AD_user.Mail
    $UserSign = $UserSign -replace "@WEBSITE", $AD_user.wwwHomepage
    $UserSign | Set-Content "$PathSignatureUser\$FileName.$Ext" -Encoding UTF8
}

W
Warikos, 2021-11-20
@Warikos

Yes, it's a signature. The point is not that it is not created (it just works well). The problem is that when you create *.htm in the required format for signing and save this file, the view of viewing all *.docx files changes to viewing a web document 61992dda40ce9603762647.jpeg. Not that this is a direct problem, but I want the view to change to "Page Layout".
If anyone is interested, the code itself is below. The script is not mine, but thoroughly revised.
UPD. Final version

Clear-Host
#Set Varibles
$CompanyName = "TFM-Spectehnika"
$SigSource = "\\srv-db1\Config.1C$\Signatures"
#Connect to ad and set Signatures Path
$AppData=(Get-Item env:appdata) .value
$SigPath = "\Microsoft\Signatures"
$LocalSignaturePath = $AppData+$SigPath
$fullPath = $LocalSignaturePath+"\"+$CompanyName+".docx"
$fullPathHTM = $LocalSignaturePath+"\"+$CompanyName+".htm"
#Get User information
$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.TelephoneNumber
$ADDepartment = $ADUser.Department
$CompanyRegPath = "HKCU: \Software\"+$CompanyName
#Check reg
function isRegistryValue {
param (
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]$Path,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]$ValueName
)
try {Get-ItemProperty -Path $Path | Select-Object -ExpandProperty $ValueName -ErrorAction Stop | Out-Null
return $true }
catch {
return $false}
}
#Delete Folder
Function DELETE_Folder {
If (Test-Path -Path $LocalSignaturePath) {
Remove-Item -Path $LocalSignaturePath -Recurse
}}
#Delete REG
Function DELETE_REG {
If (Test-Path -Path $CompanyRegPath ) {
Remove-Item -Path $CompanyRegPath -Recurse
}}
#Create REG PATH
Function CREATE_REG {
if (Test-Path $CompanyRegPath)
{}
else
{New-Item -path "HKCU:\Software" -name $CompanyName}
if ( Test-Path $CompanyRegPath"\OutlookSignatureSettings")
{}
else
{New-Item -path $CompanyRegPath -name "OutlookSignatureSettings"}
}
#Set main signatures
Function Main_Sign {
if (isRegistryValue -Path "HKCU:\Software\Microsoft\Office\16.0\Outlook\Setup" -ValueName ImportPRF) {
$currentState = (Get-ItemProperty -Path "HKCU:\Software\Microsoft \Office\16.0\Outlook\Setup" -Name $key.Value_Name).$( $key.Value_Name )
if (($currentState -eq $key.Value) -or (([string]::IsNullOrEmpty($key. Value)) -and ([string]::IsNullOrEmpty($currentState))))
{}
else {
Remove-ItemProperty -Path HKCU:\Software\Microsoft\Office\16.0\Outlook\Setup -Name First-Run -Force - ErrorAction SilentlyContinue -Verbose
New-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'ReplySignature' -Value $CompanyName -PropertyType 'String' -Force
New-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\ Common\MailSettings' -Name 'NewSignature' -Value $CompanyName -PropertyType 'String' -Force
}
}
else {
Remove-ItemProperty -Path HKCU:\Software\Microsoft\Office\16.0\Outlook\Setup -Name First-Run -Force -ErrorAction SilentlyContinue -Verbose
New-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'ReplySignature' -Value $CompanyName -PropertyType 'String' -Force
New-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'NewSignature' -Value $CompanyName -PropertyType 'String' -Force
}
}
#Set data to reg
Function REG_DATA {
Set-ItemProperty $CompanyRegPath "\OutlookSignatureSettings" -name SignatureSourceFiles -Value $SigSource
New-ItemProperty $CompanyRegPath"\OutlookSignatureSettings" -name Title -PropertyType String -Value $ADTitle
New-ItemProperty $CompanyRegPath"\OutlookSignatureSettings" -name EmailAddress -PropertyType String -Value $ADEmailAddress
New -ItemProperty $CompanyRegPath"\OutlookSignatureSettings" -name Department -PropertyType String -Value $ADDepartment
New-ItemProperty $CompanyRegPath"\OutlookSignatureSettings" -name TelePhoneNumber -PropertyType String -Value $ADTelePhoneNumber
}
#Create signatures
Function Create_SIGN {
Copy-Item -Path $SigSource $AppData"\Microsoft" -Recurse -Force
#Set Enviroment for New-Object -com word.application
$ReplaceAll = 2
$FindContinue = 1
$MatchCase = $True
$MatchWholeWord = $True
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False
#Start applet
$MSWord = New-Object -com word.application
#$MSWord.Visible = $True
$MSWord.Documents.Open($fullPath)
$FindText = "DisplayName"
$ReplaceText = $ADDisplayName.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $ MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll )
$FindText = "Title"
$ReplaceText = $ADTitle.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll )
$FindText = "Telephone"
$ReplaceText = $ADTelePhoneNumber.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll )
$FindText = "Department"
$ReplaceText = $ADDepartment.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll )
$ MSWord.Selection.Find.Execute("Email")
$MSWord.ActiveDocument.Hyperlinks.Add($MSWord.Selection.Range, "mailto:"+$ADEmailAddress.ToString(), $missing, $missing, $ADEmailAddress.ToString ())
#Save chenged documents
$MSWord.ActiveDocument.Save()
#Save to HTM
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatHTML");
[ref]$BrowserLevel = "microsoft.office.interop.word.WdBrowserLevel" -as [type]
$MSWord.ActiveDocument.WebOptions.OrganizeInFolder = $true
$MSWord.ActiveDocument.WebOptions.UseLongFileNames = $true
$MSWord.ActiveDocument.WebOptions .BrowserLevel = $BrowserLevel::wdBrowserLevelMicrosoftInternetExplorer6
$path = $LocalSignaturePath+"\"+$CompanyName+".htm"
$MSWord.ActiveDocument.saveas([ref]$path, [ref]$saveFormat)
#Save to RTF
$saveFormat = [ Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatRTF");
$path = $LocalSignaturePath+"\"+$CompanyName+".rtf"
$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$saveFormat)
#Save to TXT
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatText");
#Needn't
#$path = $LocalSignaturePath+"\"+$CompanyName+".rtf"
#$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$saveFormat)
$path = $LocalSignaturePath+"\"+$ CompanyName+".txt"
$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$SaveFormat)
$MSWord.ActiveDocument.Close()
$MSWord.Quit()
}
#Check all
if ($ADTitle -eq ($ Title = (Get-ItemProperty $CompanyRegPath"\OutlookSignatureSettings").Title))
{if ($ADDepartment -eq ($Department = (Get-ItemProperty $CompanyRegPath"
{if ($ADTelePhoneNumber -eq ($TelePhoneNumber = (Get-ItemProperty $CompanyRegPath"\OutlookSignatureSettings").TelePhoneNumber))
{if (Test-Path -PathType Leaf -Path $fullPathHTM)
{Main_Sign
}
else{
DELETE_Folder
DELETE_REG
CREATE_REG
REG_DATA
Create_SIGN
Main_Sign}}
else {
DELETE_Folder
DELETE_REG
CREATE_REG
REG_DATA
Create_SIGN
Main_Sign}}
else {
DELETE_Folder
DELETE_REG
CREATE_REG
REG_DATA
Create_SIGN
Main_Sign}}
else {
DELETE_Folder
DELETE_REG
CREATE_REG
REG_DATA
Create_SIGN
Main_Sign}
Exit

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question