forked from TAo4ma/PS_Script
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChange_Properties_Word_v9.ps1
942 lines (827 loc) · 34.5 KB
/
Change_Properties_Word_v9.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
param (
[string]$filePath,
[string]$approver,
[bool]$approvalFlag,
[string]$imagePath,
[string]$iniFilePath
)
class PC {
[string]$Name
[string]$IPAddress
[string]$MACAddress
PC([string]$name, [string]$iniFilePath) {
$this.Name = $name
$this.IPAddress = $this.GetIPAddress()
$this.MACAddress = $this.GetMACAddress()
$this.Import_InteropAssembly($iniFilePath)
}
[void]DisplayInfo() {
Write-Host "PC Name: $($this.Name)"
Write-Host "IP Address: $($this.IPAddress)"
Write-Host "MAC Address: $($this.MACAddress)"
}
[string]GetIPAddress() {
$ipConfig = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -notlike "*Loopback*" }
return $ipConfig.IPAddress
}
[string]GetMACAddress() {
$macConfig = Get-NetAdapter | Where-Object { $_.Status -eq "Up" }
return $macConfig.MacAddress
}
[string]GetScriptDirectory() {
return Split-Path -Parent -Path $PSCommandPath
}
[void]ChangeToScriptDirectory() {
$scriptDir = $this.GetScriptDirectory()
Set-Location -Path $scriptDir
Write-Host "Changed directory to script location: $scriptDir"
}
[hashtable]GetIniContent([string]$iniFilePath) {
$iniContent = @{}
if (Test-Path $iniFilePath) {
$lines = Get-Content -Path $iniFilePath
foreach ($line in $lines) {
if ($line -match "^\s*`"([^\`"]+?)`"\s*,\s*`"([^\`"]+?)`"\s*$") {
$key = $matches[1]
$value = $matches[2]
$iniContent[$key] = $value
}
}
}
return $iniContent
}
[void]SavePCInfoToIni([string]$iniFilePath) {
$iniContent = $this.GetIniContent($iniFilePath)
$iniContent[$this.Name] = "$($this.IPAddress),$($this.MACAddress),$($this.GetScriptDirectory())"
$iniLines = @()
foreach ($key in $iniContent.Keys) {
$iniLines += "`"$key`",`"$($iniContent[$key])`""
}
Set-Content -Path $iniFilePath -Value $iniLines
}
[void]LoadPCInfoFromIni([string]$iniFilePath) {
$iniContent = $this.GetIniContent($iniFilePath)
if ($iniContent.ContainsKey($this.Name)) {
$info = $iniContent[$this.Name] -split ","
$this.IPAddress = $info[0]
$this.MACAddress = $info[1]
$scriptDir = $info[2]
Set-Location -Path $scriptDir
Write-Host "Loaded PC info from INI file: $($this.Name), $($this.IPAddress), $($this.MACAddress), $scriptDir"
} else {
Write-Host "PC info not found in INI file for: $($this.Name)"
}
}
[void]Import_InteropAssembly([string]$iniFilePath) {
$assemblyName = "Microsoft.Office.Interop.Word"
Write-Host "Import_InteropAssemblyメソッドを実行中..."
# INIファイルからアセンブリパスを読み込む
if (Test-Path $iniFilePath) {
$iniContent = $this.GetIniContent($iniFilePath)
$assemblyPath = $iniContent[$assemblyName]
} else {
$assemblyPath = $null
}
switch ($true) {
($assemblyPath -and (Test-Path $assemblyPath)) {
Write-Host "$assemblyName is found in INI file. Using the existing assembly."
Add-Type -Path $assemblyPath
}
($null -eq $assemblyPath -or -not (Test-Path $assemblyPath)) {
Write-Host "$assemblyName is not found in INI file or path does not exist. Searching in Windows directory..."
# Windowsディレクトリ下をサーチ
$assemblyPath = Get-ChildItem -Path "C:\Windows\assembly\GAC_MSIL" -Recurse -Filter "Microsoft.Office.Interop.Word.dll" | Select-Object -First 1 -ExpandProperty FullName
if ($assemblyPath) {
Write-Host "$assemblyName is found in Windows directory. Using the existing assembly."
if ($iniFilePath) {
Set-Content -Path $iniFilePath -Value "$assemblyName=$assemblyPath"
}
Add-Type -Path $assemblyPath
} else {
Write-Host "$assemblyName is not found in Windows directory. Installing from NuGet..."
# NuGetプロバイダーのインストール
if (-not (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) {
Install-PackageProvider -Name NuGet -Force -Scope CurrentUser
Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
}
# Microsoft.Office.Interop.Wordのインストール
Install-Package -Name "Microsoft.Office.Interop.Word" -Source "PSGallery" -Scope CurrentUser -Force
$assemblyPath = (Get-Package -Name "Microsoft.Office.Interop.Word" -Source "PSGallery").Source
if ($iniFilePath) {
Set-Content -Path $iniFilePath -Value "$assemblyName=$assemblyPath"
}
Add-Type -Path $assemblyPath
}
}
}
Write-Host "Import_InteropAssemblyメソッドが完了しました。"
}
}
class Word {
[object]$Application
[object]$Document
[hashtable]$DocumentProperties
[hashtable]$CustomProperties
Word([string]$filePath) {
$this.Application = New-Object -ComObject Word.Application
$this.Application.Visible = $true
$this.Document = $this.Application.Documents.Open($filePath)
$this.DocumentProperties = $this.GetDocumentProperties()
$this.CustomProperties = $this.GetCustomProperties()
}
[void]Close() {
$this.Document.Close()
$this.Application.Quit()
}
[void]SetCustomProperty([string]$propName, [object]$propValue) {
try {
$properties = $this.Document.CustomDocumentProperties
if ($null -eq $properties) {
Write-Error "カスタムプロパティが見つかりませんでした。"
return
}
} catch {
Write-Error "カスタムプロパティの取得に失敗しました: $_"
return
}
# カスタムプロパティの一覧を表示(デバッグ用)
foreach ($property in $properties) {
Write-Host "Property Name: $($property.Name), Property Value: $($property.Value)"
}
# 既存のカスタムプロパティをチェック
try {
$property = $properties.Item($propName)
Write-Host "Property found: $($property.Name), Value: $($property.Value)"
} catch {
# プロパティが存在しない場合は例外が発生するので無視
Write-Host "Property '$propName' not found."
$property = $null
}
if ($null -ne $property) {
if ($null -eq $propValue) {
# プロパティを削除
try {
Write-Host "Deleting custom property: $propName"
$properties.Remove($propName)
} catch {
Write-Error "カスタムプロパティの削除に失敗しました: $_"
}
} else {
# 既存のプロパティを更新
Write-Host "Updating custom property: $propName = $propValue"
$property.Value = $propValue
}
} else {
if ($null -ne $propValue) {
# 新しいプロパティを追加
try {
Write-Host "Adding new custom property: $propName = $propValue"
$properties.Add($propName, $false, 4, $propValue) # 4はmsoPropertyTypeString
} catch {
Write-Error "カスタムプロパティの追加に失敗しました: $_"
}
}
}
# クラス変数を更新
$this.CustomProperties = $this.GetCustomProperties()
}
[object]GetCustomProperty([string]$propName) {
try {
$properties = $this.Document.CustomDocumentProperties
if ($null -eq $properties) {
Write-Error "カスタムプロパティが見つかりませんでした。"
return $null
}
} catch {
Write-Error "カスタムプロパティの取得に失敗しました: $_"
return $null
}
# 既存のカスタムプロパティをチェック
try {
$property = $properties.Item($propName)
Write-Host "Property found: $($property.Name), Value: $($property.Value)"
return $property.Value
} catch {
# プロパティが存在しない場合は例外が発生するので無視
Write-Host "Property '$propName' not found."
return $null
}
}
[hashtable]GetCustomProperties() {
$properties = @{}
try {
$this.CustomProperties = $this.Document.CustomDocumentProperties
foreach ($property in $this.CustomProperties) {
$properties[$property.Name] = $property.Value
}
} catch {
Write-Error "カスタムプロパティの取得に失敗しました: $_"
}
return $properties
}
[hashtable]GetDocumentProperties() {
$properties = @{}
$binding = "System.Reflection.BindingFlags" -as [type]
$AryProperties = "Title", "Author", "Keywords", "Number of words", "Number of pages"
try {
$BuiltinProperties = $this.Document.BuiltInDocumentProperties
foreach ($p in $AryProperties) {
try {
$pn = [System.__ComObject].InvokeMember("Item", $binding::GetProperty, $null, $BuiltinProperties, $p)
$value = [System.__ComObject].InvokeMember("Value", $binding::GetProperty, $null, $pn, $null)
$properties[$p] = $value
} catch [System.Exception] {
Write-Host -ForegroundColor Blue "Value not found for $p"
}
}
} catch {
Write-Warning "Failed to get document properties: $_"
}
return $properties
}
[void]SetDocumentProperties([hashtable]$properties) {
foreach ($key in $properties.Keys) {
try {
$this.Document.BuiltInDocumentProperties($key).Value = $properties[$key]
Write-Host "Property '$key' set to '$($properties[$key])'"
} catch {
Write-Error "Failed to set property '$key': $_"
}
}
# クラス変数を更新
$this.DocumentProperties = $this.GetDocumentProperties()
}
[void]ProcessTable() {
Write-Host "1つ目のテーブルを取得中..."
try {
$table = $this.Document.Tables.Item(1)
Write-Host "First table retrieved."
} catch {
Write-Error "テーブルの取得に失敗しました: $_"
return
}
# テーブルのプロパティを取得
$rows = $table.Rows.Count
$columns = $table.Columns.Count
Write-Host "Table properties retrieved: Rows=$rows, Columns=$columns"
# 各セルの情報を取得
foreach ($row in 1..$rows) {
foreach ($col in 1..$columns) {
try {
$cell = $table.Cell($row, $col)
$cellText = $cell.Range.Text
Write-Host "Row: $row, Column: $col, Text: $cellText"
} catch {
Write-Host "Row: $row, Column: $col, Text: (cell not found)" -Foreground Red
}
}
}
}
[void]ProcessImage([string]$imagePath) {
# 1つ目のセルを取得
Write-Host "1つ目のセルを取得中..."
$cell = $this.Document.Tables.Item(1).Cell(2, 6)
Write-Host "Cell (2, 6) retrieved."
# セルの座標とサイズを取得
$left = $cell.Range.Information(1) # 1 corresponds to wdHorizontalPositionRelativeToPage
$top = $cell.Range.Information(2) # 2 corresponds to wdVerticalPositionRelativeToPage
$width = $cell.Width
$height = $cell.Height
Write-Host "Cell coordinates and size retrieved: Left=$left, Top=$top, Width=$width, Height=$height"
# 画像のサイズを設定
$imageWidth = 50
$imageHeight = 50
# 画像の中央位置を計算
$imageLeft = $left + ($width - $imageWidth) / 2
$imageTop = $top + ($height - $imageHeight) / 2
# 既存の画像を削除(もしあれば)
Write-Host "既存の画像を削除中..."
foreach ($shape in $this.Document.Shapes) {
if ($shape.Type -eq 3) { # 3 corresponds to wdInlineShapePicture
$shape.Delete()
}
}
Write-Host "Existing images deleted."
# 新しい画像を挿入
Write-Host "新しい画像を挿入中..."
$shape = $this.Document.Shapes.AddPicture($imagePath, $false, $true, $imageLeft, $imageTop, $imageWidth, $imageHeight)
Write-Host "New image inserted."
# 画像のプロパティを変更
Write-Host "画像のプロパティを変更中..."
$shape.LockAspectRatio = $false
$shape.Width = 50
$shape.Height = 50
Write-Host "Image properties modified."
}
}
function ProcessDocument {
param (
[PC]$pc,
[string]$filePath,
[string]$approver,
[bool]$approvalFlag,
[string]$imagePath,
[string]$iniFilePath
)
if (-not (Test-Path $filePath)) {
Write-Error "ファイルパスが無効です: $filePath"
return
}
# スクリプト実行前に存在していたWordプロセスを取得
$existingWordProcesses = Get-Process -Name WINWORD -ErrorAction SilentlyContinue
# Wordアプリケーションを起動
Write-Host "Wordアプリケーションを起動中..."
$word = [Word]::new($filePath)
try {
# 文書プロパティを表示
Write-Host "現在の文書プロパティ:"
foreach ($key in $word.DocumentProperties.Keys) {
Write-Host "$($key): $($word.DocumentProperties[$key])"
}
# 承認者プロパティを設定
Write-Host "承認者プロパティを設定中..."
$word.SetCustomProperty("Approver", $approver)
# 承認フラグプロパティを設定
Write-Host "承認フラグプロパティを設定中..."
$word.SetCustomProperty("ApprovalFlag", ($approvalFlag ? "承認" : "未承認"))
# テーブル処理
$word.ProcessTable()
# 画像処理
$word.ProcessImage($imagePath)
# ドキュメントを保存して閉じる
Write-Host "ドキュメントを保存して閉じています..."
$word.Document.Save()
$word.Close()
} catch {
Write-Error "エラーが発生しました: $_"
} finally {
# スクリプト実行後に存在するWordプロセスを取得
$allWordProcesses = Get-Process -Name WINWORD -ErrorAction SilentlyContinue
# スクリプト実行前に存在していたプロセスを除外して終了
$newWordProcesses = $allWordProcesses | Where-Object { $_.Id -notin $existingWordProcesses.Id }
foreach ($proc in $newWordProcesses) {
try {
$proc.Kill()
} catch {
Write-Warning "プロセスの終了に失敗しました: $($_.Exception.Message)"
}
}
}
Write-Host "カスタムプロパティが設定されました。"
}
# ドキュメントプロパティを取得する関数
function Get-DocumentProperties {
param (
[string]$filePath
)
$properties = @{}
try {
$document = $word.Documents.Open($filePath)
$builtinProperties = $document.BuiltInDocumentProperties
foreach ($property in $builtinProperties) {
$properties[$property.Name] = $property.Value
}
$document.Close()
} catch {
Write-Warning "Failed to get document properties: $_"
}
return $properties
}
# ドキュメントプロパティを設定する関数
function Set-DocumentProperty {
param (
[string]$filePath,
[string]$propertyName,
[string]$newValue
)
[ref]$SaveOption = "Microsoft.Office.Interop.Word.WdSaveOptions" -as [type]
try {
$document = $word.Documents.Open($filePath)
$builtinProperties = $document.Bparam (
[string]$filePath,
[string]$approver,
[bool]$approvalFlag,
[string]$imagePath,
[string]$iniFilePath
)
class PC {
[string]$Name
[string]$IPAddress
[string]$MACAddress
PC([string]$name, [string]$iniFilePath) {
$this.Name = $name
$this.IPAddress = $this.GetIPAddress()
$this.MACAddress = $this.GetMACAddress()
$this.Import_InteropAssembly($iniFilePath)
}
[void]DisplayInfo() {
Write-Host "PC Name: $($this.Name)"
Write-Host "IP Address: $($this.IPAddress)"
Write-Host "MAC Address: $($this.MACAddress)"
}
[string]GetIPAddress() {
$ipConfig = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -notlike "*Loopback*" }
return $ipConfig.IPAddress
}
[string]GetMACAddress() {
$macConfig = Get-NetAdapter | Where-Object { $_.Status -eq "Up" }
return $macConfig.MacAddress
}
[string]GetScriptDirectory() {
return Split-Path -Parent -Path $PSCommandPath
}
[void]ChangeToScriptDirectory() {
$scriptDir = $this.GetScriptDirectory()
Set-Location -Path $scriptDir
Write-Host "Changed directory to script location: $scriptDir"
}
[hashtable]GetIniContent([string]$iniFilePath) {
$iniContent = @{}
if (Test-Path $iniFilePath) {
$lines = Get-Content -Path $iniFilePath
foreach ($line in $lines) {
if ($line -match "^\s*`"([^\`"]+?)`"\s*,\s*`"([^\`"]+?)`"\s*$") {
$key = $matches[1]
$value = $matches[2]
$iniContent[$key] = $value
}
}
}
return $iniContent
}
[void]SavePCInfoToIni([string]$iniFilePath) {
$iniContent = $this.GetIniContent($iniFilePath)
$iniContent[$this.Name] = "$($this.IPAddress),$($this.MACAddress),$($this.GetScriptDirectory())"
$iniLines = @()
foreach ($key in $iniContent.Keys) {
$iniLines += "`"$key`",`"$($iniContent[$key])`""
}
Set-Content -Path $iniFilePath -Value $iniLines
}
[void]LoadPCInfoFromIni([string]$iniFilePath) {
$iniContent = $this.GetIniContent($iniFilePath)
if ($iniContent.ContainsKey($this.Name)) {
$info = $iniContent[$this.Name] -split ","
$this.IPAddress = $info[0]
$this.MACAddress = $info[1]
$scriptDir = $info[2]
Set-Location -Path $scriptDir
Write-Host "Loaded PC info from INI file: $($this.Name), $($this.IPAddress), $($this.MACAddress), $scriptDir"
} else {
Write-Host "PC info not found in INI file for: $($this.Name)"
}
}
[void]Import_InteropAssembly([string]$iniFilePath) {
$assemblyName = "Microsoft.Office.Interop.Word"
Write-Host "Import_InteropAssemblyメソッドを実行中..."
# INIファイルからアセンブリパスを読み込む
if (Test-Path $iniFilePath) {
$iniContent = $this.GetIniContent($iniFilePath)
$assemblyPath = $iniContent[$assemblyName]
} else {
$assemblyPath = $null
}
switch ($true) {
($assemblyPath -and (Test-Path $assemblyPath)) {
Write-Host "$assemblyName is found in INI file. Using the existing assembly."
Add-Type -Path $assemblyPath
}
($null -eq $assemblyPath -or -not (Test-Path $assemblyPath)) {
Write-Host "$assemblyName is not found in INI file or path does not exist. Searching in Windows directory..."
# Windowsディレクトリ下をサーチ
$assemblyPath = Get-ChildItem -Path "C:\Windows\assembly\GAC_MSIL" -Recurse -Filter "Microsoft.Office.Interop.Word.dll" | Select-Object -First 1 -ExpandProperty FullName
if ($assemblyPath) {
Write-Host "$assemblyName is found in Windows directory. Using the existing assembly."
if ($iniFilePath) {
Set-Content -Path $iniFilePath -Value "$assemblyName=$assemblyPath"
}
Add-Type -Path $assemblyPath
} else {
Write-Host "$assemblyName is not found in Windows directory. Installing from NuGet..."
# NuGetプロバイダーのインストール
if (-not (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) {
Install-PackageProvider -Name NuGet -Force -Scope CurrentUser
Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
}
# Microsoft.Office.Interop.Wordのインストール
Install-Package -Name "Microsoft.Office.Interop.Word" -Source "PSGallery" -Scope CurrentUser -Force
$assemblyPath = (Get-Package -Name "Microsoft.Office.Interop.Word" -Source "PSGallery").Source
if ($iniFilePath) {
Set-Content -Path $iniFilePath -Value "$assemblyName=$assemblyPath"
}
Add-Type -Path $assemblyPath
}
}
}
Write-Host "Import_InteropAssemblyメソッドが完了しました。"
}
}
class Word {
[object]$Application
[object]$Document
[hashtable]$DocumentProperties
[hashtable]$CustomProperties
Word([string]$filePath) {
$this.Application = New-Object -ComObject Word.Application
$this.Application.Visible = $true
$this.Document = $this.Application.Documents.Open($filePath)
$this.DocumentProperties = $this.GetDocumentProperties()
$this.CustomProperties = $this.GetCustomProperties()
}
[void]Close() {
$this.Document.Close()
$this.Application.Quit()
}
[void]SetCustomProperty([string]$propName, [object]$propValue) {
try {
$properties = $this.Document.CustomDocumentProperties
if ($null -eq $properties) {
Write-Error "カスタムプロパティが見つかりませんでした。"
return
}
} catch {
Write-Error "カスタムプロパティの取得に失敗しました: $_"
return
}
# カスタムプロパティの一覧を表示(デバッグ用)
foreach ($property in $properties) {
Write-Host "Property Name: $($property.Name), Property Value: $($property.Value)"
}
# 既存のカスタムプロパティをチェック
try {
$property = $properties.Item($propName)
Write-Host "Property found: $($property.Name), Value: $($property.Value)"
} catch {
# プロパティが存在しない場合は例外が発生するので無視
Write-Host "Property '$propName' not found."
$property = $null
}
if ($null -ne $property) {
if ($null -eq $propValue) {
# プロパティを削除
try {
Write-Host "Deleting custom property: $propName"
$properties.Remove($propName)
} catch {
Write-Error "カスタムプロパティの削除に失敗しました: $_"
}
} else {
# 既存のプロパティを更新
Write-Host "Updating custom property: $propName = $propValue"
$property.Value = $propValue
}
} else {
if ($null -ne $propValue) {
# 新しいプロパティを追加
try {
Write-Host "Adding new custom property: $propName = $propValue"
$properties.Add($propName, $false, 4, $propValue) # 4はmsoPropertyTypeString
} catch {
Write-Error "カスタムプロパティの追加に失敗しました: $_"
}
}
}
# クラス変数を更新
$this.CustomProperties = $this.GetCustomProperties()
}
[object]GetCustomProperty([string]$propName) {
try {
$properties = $this.Document.CustomDocumentProperties
if ($null -eq $properties) {
Write-Error "カスタムプロパティが見つかりませんでした。"
return $null
}
} catch {
Write-Error "カスタムプロパティの取得に失敗しました: $_"
return $null
}
# 既存のカスタムプロパティをチェック
try {
$property = $properties.Item($propName)
Write-Host "Property found: $($property.Name), Value: $($property.Value)"
return $property.Value
} catch {
# プロパティが存在しない場合は例外が発生するので無視
Write-Host "Property '$propName' not found."
return $null
}
}
[hashtable]GetCustomProperties() {
$properties = @{}
try {
$this.CustomProperties = $this.Document.CustomDocumentProperties
foreach ($property in $this.CustomProperties) {
$properties[$property.Name] = $property.Value
}
} catch {
Write-Error "カスタムプロパティの取得に失敗しました: $_"
}
return $properties
}
[hashtable]GetDocumentProperties() {
$properties = @{}
$binding = "System.Reflection.BindingFlags" -as [type]
$AryProperties = "Title", "Author", "Keywords", "Number of words", "Number of pages"
try {
$BuiltinProperties = $this.Document.BuiltInDocumentProperties
foreach ($p in $AryProperties) {
try {
$pn = [System.__ComObject].InvokeMember("Item", $binding::GetProperty, $null, $BuiltinProperties, $p)
$value = [System.__ComObject].InvokeMember("Value", $binding::GetProperty, $null, $pn, $null)
$properties[$p] = $value
} catch [System.Exception] {
Write-Host -ForegroundColor Blue "Value not found for $p"
}
}
} catch {
Write-Warning "Failed to get document properties: $_"
}
return $properties
}
[void]SetDocumentProperties([hashtable]$properties) {
foreach ($key in $properties.Keys) {
try {
$this.Document.BuiltInDocumentProperties($key).Value = $properties[$key]
Write-Host "Property '$key' set to '$($properties[$key])'"
} catch {
Write-Error "Failed to set property '$key': $_"
}
}
# クラス変数を更新
$this.DocumentProperties = $this.GetDocumentProperties()
}
[void]ProcessTable() {
Write-Host "1つ目のテーブルを取得中..."
try {
$table = $this.Document.Tables.Item(1)
Write-Host "First table retrieved."
} catch {
Write-Error "テーブルの取得に失敗しました: $_"
return
}
# テーブルのプロパティを取得
$rows = $table.Rows.Count
$columns = $table.Columns.Count
Write-Host "Table properties retrieved: Rows=$rows, Columns=$columns"
# 各セルの情報を取得
foreach ($row in 1..$rows) {
foreach ($col in 1..$columns) {
try {
$cell = $table.Cell($row, $col)
$cellText = $cell.Range.Text
Write-Host "Row: $row, Column: $col, Text: $cellText"
} catch {
Write-Host "Row: $row, Column: $col, Text: (cell not found)" -Foreground Red
}
}
}
}
[void]ProcessImage([string]$imagePath) {
# 1つ目のセルを取得
Write-Host "1つ目のセルを取得中..."
$cell = $this.Document.Tables.Item(1).Cell(2, 6)
Write-Host "Cell (2, 6) retrieved."
# セルの座標とサイズを取得
$left = $cell.Range.Information(1) # 1 corresponds to wdHorizontalPositionRelativeToPage
$top = $cell.Range.Information(2) # 2 corresponds to wdVerticalPositionRelativeToPage
$width = $cell.Width
$height = $cell.Height
Write-Host "Cell coordinates and size retrieved: Left=$left, Top=$top, Width=$width, Height=$height"
# 画像のサイズを設定
$imageWidth = 50
$imageHeight = 50
# 画像の中央位置を計算
$imageLeft = $left + ($width - $imageWidth) / 2
$imageTop = $top + ($height - $imageHeight) / 2
# 既存の画像を削除(もしあれば)
Write-Host "既存の画像を削除中..."
foreach ($shape in $this.Document.Shapes) {
if ($shape.Type -eq 3) { # 3 corresponds to wdInlineShapePicture
$shape.Delete()
}
}
Write-Host "Existing images deleted."
# 新しい画像を挿入
Write-Host "新しい画像を挿入中..."
$shape = $this.Document.Shapes.AddPicture($imagePath, $false, $true, $imageLeft, $imageTop, $imageWidth, $imageHeight)
Write-Host "New image inserted."
# 画像のプロパティを変更
Write-Host "画像のプロパティを変更中..."
$shape.LockAspectRatio = $false
$shape.Width = 50
$shape.Height = 50
Write-Host "Image properties modified."
}
}
function ProcessDocument {
param (
[PC]$pc,
[string]$filePath,
[string]$approver,
[bool]$approvalFlag,
[string]$imagePath,
[string]$iniFilePath
)
if (-not (Test-Path $filePath)) {
Write-Error "ファイルパスが無効です: $filePath"
return
}
# スクリプト実行前に存在していたWordプロセスを取得
$existingWordProcesses = Get-Process -Name WINWORD -ErrorAction SilentlyContinue
# Wordアプリケーションを起動
Write-Host "Wordアプリケーションを起動中..."
$word = [Word]::new($filePath)
try {
# 文書プロパティを表示
Write-Host "現在の文書プロパティ:"
foreach ($key in $word.DocumentProperties.Keys) {
Write-Host "$($key): $($word.DocumentProperties[$key])"
}
# 承認者プロパティを設定
Write-Host "承認者プロパティを設定中..."
$word.SetCustomProperty("Approver", $approver)
# 承認フラグプロパティを設定
Write-Host "承認フラグプロパティを設定中..."
$word.SetCustomProperty("ApprovalFlag", ($approvalFlag ? "承認" : "未承認"))
# テーブル処理
$word.ProcessTable()
# 画像処理
$word.ProcessImage($imagePath)
# ドキュメントを保存して閉じる
Write-Host "ドキュメントを保存して閉じています..."
$word.Document.Save()
$word.Close()
} catch {
Write-Error "エラーが発生しました: $_"
} finally {
# スクリプト実行後に存在するWordプロセスを取得
$allWordProcesses = Get-Process -Name WINWORD -ErrorAction SilentlyContinue
# スクリプト実行前に存在していたプロセスを除外して終了
$newWordProcesses = $allWordProcesses | Where-Object { $_.Id -notin $existingWordProcesses.Id }
foreach ($proc in $newWordProcesses) {
try {
$proc.Kill()
} catch {
Write-Warning "プロセスの終了に失敗しました: $($_.Exception.Message)"
}
}
}
Write-Host "カスタムプロパティが設定されました。"
}
# Wordドキュメントプロパティを取得する関数
function Get-DocumentProperties {
param (
[string]$filePath
)
$properties = @{}
try {
$word = New-Object -ComObject Word.Application
$word.Visible = $false
$document = $word.Documents.Open($filePath)
$builtinProperties = $document.BuiltInDocumentProperties
foreach ($property in $builtinProperties) {
$properties[$property.Name] = $property.Value
}
$document.Close([ref]$SaveOption::wdDoNotSaveChanges)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($document) | Out-Null
$word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
} catch {
Write-Warning "Failed to get document properties: $_"
}
return $properties
}
# Wordドキュメントプロパティを設定する関数
function Set-DocumentProperty {
param (
[string]$filePath,
[string]$propertyName,
[string]$newValue
)
[ref]$SaveOption = "Microsoft.Office.Interop.Word.WdSaveOptions" -as [type]
try {
$word = New-Object -ComObject Word.Application
$word.Visible = $false
$document = $word.Documents.Open($filePath)
$builtinProperties = $document.BuiltInDocumentProperties
$builtinProperties.Item($propertyName).Value = $newValue
Write-Host "Property '$propertyName' set to '$newValue'"
$document.Save()
$document.Close([ref]$SaveOption::wdSaveChanges)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($document) | Out-Null
$word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
} catch {
Write-Error "Failed to set property '$propertyName': $_"
}
}
# 使用例
$filePath = "C:\Users\y0927\Documents\GitHub\PS_Script\技100-999.docx"
$propertyName = "Author"
$newValue = "近藤さん"
Set-DocumentProperty -filePath $filePath -propertyName $propertyName -newValue $newValue
Write-Host "Ready!" -ForegroundColor Green