カスタム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
呼び出しが行われます。