Powershell x64 не работает.Обойти с x86, выполняющим код дважды - PullRequest
0 голосов
/ 02 октября 2018

У меня есть код ниже, который работал нормально с Powershell x64.Короче говоря, в конфигурационном файле для x64 что-то повреждено, и я жду, когда я его исправлю (у меня нет прав администратора для исправления; отдельная проблема).

Верхние пять строк кода включены взаставить Powershell 32-битный работать, и это действительно работает.Моя проблема в том, что по какой-то причине после успешного запуска с 32-разрядным .exe, код запускается второй раз с 64-разрядным .exe, который, конечно, выбрасывает все виды ошибок, связанных с проблемами файла конфигурации.

Ошибки в стороне, есть ли какой-то очевидный фрагмент кода, который заставляет все, начиная со строки 7 и далее, запускаться второй раз?Я сделаю все возможное, чтобы предоставить больше информации, которая может вам понадобиться, чтобы помочь мне с этой проблемой.

ПРИМЕЧАНИЕ. Весь код, заданный в строке 7 и далее, работает отлично, поэтому ничего не нужно менять, кроме исправления.этот цикл.

Set-ExecutionPolicy -Scope CurrentUser Unrestricted
if ($env:Processor_Architecture -ne "x86")   
{ &"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" -noprofile -file $myinvocation.Mycommand.path }
$env:Processor_Architecture | Out-Null
[IntPtr]::Size | Out-Null

if ($startupvariables) { try {Remove-Variable -Name startupvariables  -Scope Global -ErrorAction SilentlyContinue } catch { } }
New-Variable -force -name startupVariables -value ( Get-Variable | ForEach-Object { $_.Name } )

Add-Type -AssemblyName PresentationCore,PresentationFramework
$ButtonType = [System.Windows.MessageBoxButton]::OKCancel
$MessageIcon = [System.Windows.MessageBoxImage]::Warning
$MessageTitle = "Strike 1"
$MessageBody = "This script sends the user Strike 1 of the 3 strike process.`n`nTo use it, enter the below information:`n`n`n`tTicket Number`n`n`tUser's Email Address`n`n`tInformation that you want to convey to user`n`n`nIf this is the script you want to use, click OK.`nIf not, click Cancel."
$Result = [System.Windows.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)

if ($Result -eq "Cancel")
{
Exit-PSSession
}
else

{
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$Separator = ".", "@"
$Ticket = [Microsoft.VisualBasic.Interaction]::InputBox("Enter ticket number" , "Ticket Number") 
$UserID = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the user's email address" , "User Email Address")
function Read-MultiLineInputBoxDialog([string]$Message, [string]$WindowTitle, [string]$DefaultText)
{
    Add-Type -AssemblyName System.Drawing
    Add-Type -AssemblyName System.Windows.Forms

    $label = New-Object System.Windows.Forms.Label
    $label.Location = New-Object System.Drawing.Size(10,10) 
    $label.Size = New-Object System.Drawing.Size(280,20)
    $label.AutoSize = $true
    $label.Text = $Message

    $textBox = New-Object System.Windows.Forms.TextBox 
    $textBox.Location = New-Object System.Drawing.Size(10,40) 
    $textBox.Size = New-Object System.Drawing.Size(575,200)
    $textBox.AcceptsReturn = $true
    $textBox.AcceptsTab = $false
    $textBox.Multiline = $true
    $textBox.ScrollBars = 'Both'
    $textBox.Text = $DefaultText

    $okButton = New-Object System.Windows.Forms.Button
    $okButton.Location = New-Object System.Drawing.Size(415,250)
    $okButton.Size = New-Object System.Drawing.Size(75,25)
    $okButton.Text = "OK"
    $okButton.Add_Click({ $form.Tag = $textBox.Text; $form.Close() })

    $cancelButton = New-Object System.Windows.Forms.Button
    $cancelButton.Location = New-Object System.Drawing.Size(510,250)
    $cancelButton.Size = New-Object System.Drawing.Size(75,25)
    $cancelButton.Text = "Cancel"
    $cancelButton.Add_Click({ $form.Tag = $null; $form.Close() })

    $form = New-Object System.Windows.Forms.Form 
    $form.Text = $WindowTitle
    $form.Size = New-Object System.Drawing.Size(610,320)
    $form.FormBorderStyle = 'FixedSingle'
    $form.StartPosition = "CenterScreen"
    $form.AutoSizeMode = 'GrowAndShrink'
    $form.Topmost = $True
    $form.AcceptButton = $okButton
    $form.CancelButton = $cancelButton
    $form.ShowInTaskbar = $true

    $form.Controls.Add($label)
    $form.Controls.Add($textBox)
    $form.Controls.Add($okButton)
    $form.Controls.Add($cancelButton)

    $form.Add_Shown({$form.Activate()})
    $form.ShowDialog() > $null

    return $form.Tag
}
$Issue = Read-MultiLineInputBoxDialog -Message "What is the information you want to convey to the user?" -WindowTitle  "Information Requested"
$User = $UserID.split($Separator)
$Firstname = $User[0].substring(0,1).toupper()+$User[0].substring(1).tolower()
$Lastname = $User[1].substring(0,1).toupper()+$User[1].substring(1).tolower()
$User = $Firstname, $Lastname
$Username = [System.Environment]::UserName
$subject = "Ticket $Ticket on Hold for User Response - Status Reminder #1"
$body = "

To $User, 

Your IT Service Desk ticket is currently in Hold for User Confirmation/Input status while we wait for feedback/action from you.  Without your feedback/action we cannot continue our efforts to resolve this ticket.

$Issue

As per policy, if a response is not received within 2 business days of your ticket being changed to Hold for User Confirmation/Input status, we will consider your issue resolved.


Thank You,

IT Service Desk
"

$ButtonType = [System.Windows.MessageBoxButton]::YesNo
$MessageIcon = [System.Windows.MessageBoxImage]::Warning
$MessageTitle = "Strike 1"
$MessageBody = "The information you have entered is show below:`n`n`nTicket Number: $Ticket`n`nUser's Email Address: $UserID`n`nInformation Requested: $Issue`n`n`nIf you would like to send the email, click Yes.`nOtherwise, click No."
$Result = [System.Windows.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)
if ($Result -eq "No")
{
Exit-PSSession
}
else

{
Send-MailMessage -To "<$UserID>" -bcc "<$Username@email.com>" -from "<itservicedesk@email.com>" -Subject $subject -SmtpServer "mailrelay.email.com" -body $body
}
}

Function Clean-Memory {
Get-Variable |
 Where-Object { $startupVariables -notcontains $_.Name } |
 ForEach-Object {
  try { Remove-Variable -Name "$($_.Name)" -Force -Scope "global" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue}
  catch { }
 }
}

1 Ответ

0 голосов
/ 02 октября 2018

проблема здесь

if ($env:Processor_Architecture -ne "x86")   
{ &"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" -noprofile -file $myinvocation.Mycommand.path }

Когда вы запускаете это в PowerShell x64, все, что вы делаете, это запускаете x86 powershell, но не убиваете x64, поэтому x64 продолжает выполнять скрипт.

Добавить выход как

if ($env:Processor_Architecture -ne "x86"){ 
    &"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" -noprofile -file $myinvocation.Mycommand.path 
    exit
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...