Home > Software design >  Using Perl to check installed Powershell modules [closed]
Using Perl to check installed Powershell modules [closed]

Time:10-01

Long Story short Im working with multiple versions of PCs and Powershell versions, I need to install updates on as machines automated. I have a script that installs a module on windows 10 machines, and installs the modules on the other machines. I would like to check if the required modules are installed and imported, but Im new to perl and cant find anything.

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");
} 

CodePudding user response:

Use a single system() call:

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

Note:

  • system() passes all output streams through to the terminal (console).

    • As an aside: unfortunately, PowerShell reports even error messages via stdout, though you can selectively capture them with a 2> redirection - see the bottom section of this answer.
  • You can inspect $? >> 8 for the exit code, though in the case of failure it will always be 1 in this case.

  • PowerShell CLI parameters:

    • -NoProfile prevents unnecessary loading of the PowerShell profiles, which are normally only needed for interactive sessions.

    • -ExecutionPolicy RemoteSigned changes the execution policy for this invocation (process) only, which obviates the need to restore the policy later.

  • $ErrorActionPreference = 'Stop' tells PowerShell to abort processing if and when any error should occur. In the context of a CLI call, this translates to a process exit code of 1.

  • Related