使用 Perl 检查已安装的 Powershell 模块

Using Perl to check installed Powershell modules

长话短说我使用多个版本的 PC 和 Powershell 版本,我需要在机器上自动安装更新。我有一个脚本可以在 windows 10 台机器上安装一个模块,然后在其他机器上安装这些模块。我想检查是否安装和导入了所需的模块,但我是 perl 的新手,找不到任何东西。

print "Installing new updates\n";
my ( $osvername, $major, $minor, $id ) = Win32::GetOSVersion();
if($major == 10 )
{
    my $ps_path = 'C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe';
    system("$ps_path -command Set-ExecutionPolicy RemoteSigned -force");
    system("$ps_path -command Install-Module PSWindowsUpdate -force");
    system("$ps_path -command Import-Module PSWindowsUpdate -force");
    system("$ps_path -command Get-WindowsUpdate -Install -AcceptAll");
    system("$ps_path -command Set-ExecutionPolicy Default -force");
}
else
{
    system("$gRootDir\Tools\WUInstall.exe /install");
} 

使用单一 system()调用:

system("
  $ps_path -NoProfile -ExecutionPolicy RemoteSigned -Command \"
    \$ErrorActionPreference = 'Stop'
    Install-Module PSWindowsUpdate -force
    Import-Module PSWindowsUpdate -force
    Get-WindowsUpdate -Install -AcceptAll
  \"
");

注:

  • system() 将所有输出流传递到终端(控制台)。

    • 顺便说一句:不幸的是,PowerShell 甚至会通过 stdout 报告 error 消息,尽管您可以使用 [=13] 有选择地捕获它们=] 重定向 - 请参阅 this answer.
    • 的底部部分
  • 您可以检查 $? >> 8 退出代码,但在这种情况下,如果失败,它将始终是 1

  • PowerShell CLI 参数:

    • -NoProfile 防止不必要地加载 PowerShell 配置文件,这些配置文件通常只在 interactive 会话中需要。

    • -ExecutionPolicy RemoteSigned仅更改此调用(进程)的执行策略,这避免了稍后恢复策略的需要。

  • $ErrorActionPreference = 'Stop' 告诉 PowerShell 在发生任何错误时中止处理。在 CLI 调用的上下文中,这转换为 1.

    的进程退出代码