github.com/containers/podman/v4@v4.9.4/contrib/cirrus/win-sess-launch.ps1 (about)

     1  # Runs a script and established interactive session (session 1) and
     2  # tunnels the output such that WSL operations will complete
     3  $ErrorActionPreference = 'Stop'
     4  
     5  if ($Args.Length -lt 1) {
     6      Write-Object "Usage: " + $MyInvocation.MyCommand.Name + " <script>"
     7      Exit 1;
     8  }
     9  
    10  function RegenPassword {
    11      param($username)
    12      $syms = [char[]]([char]'a'..[char]'z' `
    13                 + [char]'A'..[char]'Z'  `
    14                 + [char]'0'..[char]'9')
    15      $rnd = [byte[]]::new(32)
    16      [System.Security.Cryptography.RandomNumberGenerator]::create().getBytes($rnd)
    17      $password = ($rnd | % { $syms[$_ % $syms.length] }) -join ''
    18      $encPass = ConvertTo-SecureString $password -AsPlainText -Force
    19      Set-LocalUser -Name $username -Password $encPass
    20      return $password
    21  }
    22  
    23  $runScript = $Args[0]
    24  $nil > tmpout
    25  $cwd = Get-Location
    26  Write-Output "Location: $cwd"
    27  
    28  # Reset the password to a new random pass since it's needed in the
    29  # clear to reauth.
    30  $pass = RegenPassword "Administrator"
    31  
    32  $ljob = Start-Job -ArgumentList $cwd -ScriptBlock {
    33      param($cwd)
    34      Get-Content -Wait "$cwd\tmpout"
    35  }
    36  $pjob = Start-Job -ArgumentList $cwd,$runScript,$pass -ScriptBlock {
    37      param($cwd, $runScript, $pass)
    38      $pwargs = @("-NonInteractive", "-WindowStyle", "hidden")
    39      $command = "& { powershell.exe $pwargs -File " +
    40                 $runScript + " 3>&1 2>&1 > `"$cwd\tmpout`";" +
    41                 "Exit `$LastExitCode }"
    42      $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
    43      & psexec -accepteula -w $cwd -i 1 -u Administrator -p $pass `
    44        powershell.exe $pwargs -EncodedCommand $encoded
    45      if ($LASTEXITCODE -ne 0) {
    46         throw "failure running psexec"
    47      }
    48  }
    49  
    50  while ($pjob.State -eq 'Running') {
    51     Start-Sleep -Milliseconds 200
    52     Receive-Job $ljob
    53  }
    54  
    55  Start-Sleep  2
    56  Stop-Job $ljob
    57  
    58  while ($ljob.HasMoreData) {
    59    Receive-Job $ljob
    60    Start-Sleep -Milliseconds 200
    61  }
    62  
    63  if ($pjob.State -eq 'Failed') {
    64    Write-Output "Failure occurred, see above. Extra info:"
    65    Receive-Job $pjob
    66    throw "wsl task failed on us!"
    67  }
    68  
    69  Remove-Job $ljob
    70  Remove-Job $pjob