PowerShell脚本块内自定义函数无法识别问题求助
问题描述
我正在编写PowerShell脚本,用于每日自动在测试机上安装服务器。所有自定义函数都定义在gecommon.psd1模块文件中,每个步骤执行前都会通过Import-Module .\modules\GenerateEnvironment\gecommon.psd1 -Force导入该模块。
模块中的WriteDebugLog函数定义如下:
function WriteDebugLog { param( [string]$message ) Write-DebugLog $message }
在调用RemoveServerIfExists函数时:
function RemoveServerIfExists { param ( [string]$serverToCheck ) WriteDebugLog("Checking if Server is already installed on $serverToCheck...") $checkServer = { $installedServer = gp HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | where { $_.DisplayName -like 'Server*' } if ($installedServer) { WriteDebugLog("Uninstalling Server on $using:serverToCheck...") $installedServer | foreach { & msiexec /x $_.PSChildName /passive | Out-Null } return "Uninstalled " + $installedServer.DisplayVersion } else { return "Not found" } } $result = Invoke-Command -ComputerName $serverToCheck -ScriptBlock $checkServer if(-not ($result -eq "")) { WriteLog("Server on $serverToCheck $result") } }
脚本块外的WriteDebugLog调用可正常执行,但Invoke-Command远程脚本块内的WriteDebugLog调用报错:
The term 'WriteDebugLog' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. + CategoryInfo : ObjectNotFound: (WriteDebugLog:String) [],
问题原因
- 远程会话与本地会话完全独立:
Invoke-Command执行的脚本块是在目标测试机的全新PowerShell会话中运行的,本地会话里导入的模块、定义的函数不会自动同步到远程会话中。 - 远程会话未导入目标模块:你在本地通过
Import-Module导入的gecommon.psd1仅对当前本地PowerShell会话生效,远程测试机的会话中没有加载这个模块,因此找不到WriteDebugLog函数。 - 额外提示:你的
WriteDebugLog函数存在递归调用问题(函数内部直接调用自身),这会导致无限循环报错,建议修正该函数的实现逻辑。
内容的提问来源于stack exchange,提问作者kollodziej
相关产品推荐
相关产品推荐

