2

在自定义 PowerShell 模块中,我在模块定义的顶部有以下代码:

Update-FormatData -AppendPath (Join-Path $psscriptroot "*.ps1xml")

这工作正常,因为所有.ps1xml文件都已加载。

但是,有时会使用加载模块Import-Module MyModule -Force(实际上,这是在模块的安装脚本中)。

在这种情况下,调用Update-FormatData失败并出现以下错误:

Update-FormatData : There were errors in loading the format data file:
Microsoft.PowerShell, c:\pathto\myfile.Types.ext.ps1xml : File skipped because it was already present from "Microsoft.PowerShell".
At line:1 char:18
+ Update-FormatData <<<<  -AppendPath "c:\pathto\myfile.Types.ext.ps1xml"
    + CategoryInfo          : InvalidOperation: (:) [Update-FormatData], RuntimeException
    + FullyQualifiedErrorId : FormatXmlUpateException,Microsoft.PowerShell.Commands.UpdateFormatDataCommand

有没有办法安全地调用这个命令?

我知道我可以Update-FormatData不带参数调用,它会更新任何已知.ps1xml文件,但这只有在文件已经加载时才有效。

我可以在某处列出加载的格式数据文件吗?

这里有一点背景:

我正在构建一个使用脚本安装的自定义模块。安装脚本如下所示:

[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High")]
param()
process {
    $target = Join-Path $PSHOME "Modules\MyModule"
    if ($pscmdlet.ShouldProcess("$target","Deploying MyModule module"))
    {
        if(!(Test-Path $target)) { new-Item -ItemType Directory -Path $target | Out-Null }
        get-ChildItem -Path (Split-Path ((Get-Variable MyInvocation -Scope 0).Value).MyCommand.Path) | copy-Item -Destination $target -Force

        Write-Host -ForegroundColorWhite @"

The module has been installed. You can import it using :

    Import-Module MyModule

Or you can add it in your profile ($profile)
"@

        Write-Warning "To refresh any open PowerShell session, you should run ""Import-Module MyModule -Force"" to reload the module"

        Import-Module MyModule -Force

        Write-Warning "This session has been refreshed."
    }
}

MyModule 将这一行定义为第一条语句:

Update-FormatData -AppendPath (Join-Path $psscriptroot "*.ps1xml")

当我更新我$profile以始终加载此模块时,Update-Path当我运行安装脚本时已调用该命令。在安装脚本中,我强制导入模块,再次触发模块,然后Update-Path调用

4

1 回答 1

1

一种简单的方法是使用-erroraction(alias -ea) 参数:

Update-FormatData -AppendPath (Join-Path $psscriptroot "*.ps1xml") -force -ea SilentlyContinue

不会显示错误。

于 2012-11-28T19:38:26.230 回答