在运行PowerShell脚本时,我使用的是“以其他用户身份运行”,其行为方式与在普通PowerShell终端中运行脚本时的行为有所不同。例如,如果我尝试在“运行方式”终端中运行以下代码,则会遇到错误。但是,如果我在普通终端上运行它,就可以正常工作。
function Replace-Word(
[string]$Document,
[string]$FindText,
[string]$ReplaceText
)
{
$ReplaceAll = 2
$FindContinue = 1
$MatchCase = $False
$MatchWholeWord = $True
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False
$Word = New-Object -comobject Word.Application
$Word.Visible = $False
$OpenDoc = $Word.Documents.Open($Document)
$Selection = $Word.Selection
$Selection.Find.Execute(
$FindText,
$MatchCase,
$MatchWholeWord,
$MatchWildcards,
$MatchSoundsLike,
$MatchAllWordForms,
$Forward,
$Wrap,
$Format,
$ReplaceText,
$ReplaceAll
) | Out-Null
$OpenDoc.Close()
$Word.quit()
}
Copy-Item "C:\Welcome.DOC" "C:\test.DOC"
Replace-Word -Document "C:\test.DOC" -FindText '<UserName>' -ReplaceText "JohnDoe"
Replace-Word -Document "C:\test.DOC" -FindText '<EmailAddress>' -ReplaceText "JohnDoe@example.com"
以其他用户身份运行时出现的错误是:
You cannot call a method on a null-valued expression.
At C:\Users\lbradstr\Desktop\TechRepo\NewEEsetup\NewUserSetup.ps1:2668 char:9
+ $Selection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\lbradstr\Desktop\TechRepo\NewEEsetup\NewUserSetup.ps1:2670 char:9
+ $OpenDoc.Close()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\lbradstr\Desktop\TechRepo\NewEEsetup\NewUserSetup.ps1:2668 char:9
+ $Selection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\lbradstr\Desktop\TechRepo\NewEEsetup\NewUserSetup.ps1:2670 char:9
+ $OpenDoc.Close()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
两个终端都运行相同版本的PowerShell:
Major Minor Build Revision
----- ----- ----- --------
5 1 14409 1012
如果可以的话,我会在普通终端中运行此代码,但这只是我正在运行的较大脚本的一部分。脚本的其余部分需要管理权限才能运行,这就是为什么我使用“运行方式”功能。关于为什么代码在两个用户帐户之间执行不同的任何想法?任何建议将不胜感激!
答案 0 :(得分:1)
其他人的建议仍然适用(一旦对文件的权限和ACL进行了排序),它仍然给您这个错误...然后:
这是Word中锁定文件的典型情况。您需要从上一个PowerShell会话中释放COM对象,因为它可能仍在访问文件并引起问题。
一旦释放COM对象或关闭所有文字处理,请尝试再次运行,它应该可以工作。