У меня есть небольшая проблема, которую я пытаюсь выяснить, как решить:)
Мой «скрипт» / приложение должно заменить некоторый текст на определенных строках в файле конфигурации (PATH + $ TESTalias)
Я сделал wpf-форму, которая содержит список (отображающий некоторые имена), OK и кнопку отмены.
Я создал хеш-таблицу, содержащую «псевдонимы» для отображаемых имен в списке.
И сделал так, что при нажатии кнопки «ОК» псевдоним выбранного элемента в списке должен быть сохранен в переменную, которая затем будет использоваться в «path + $ TESTalias»
И все отлично работает при локальном запуске через ISE.
Но когда я «компилирую» «приложение» в EXE-файл (через ISESteroids или PS2EXE), меняется только первая часть пути, а НЕ переменная $ TESTalias.
Я также пытался объявить его как глобальную переменную сценария, с тем же результатом.
Не могу опубликовать фактические имена / местоположения здесь, но теперь опубликовал слегка пересмотренный сценарий, чтобы не раскрывать конфиденциальную информацию.
Загадочная часть для меня заключается в том, что он отлично работает при запуске из ISE, но НЕ после exe-компиляции ?
# Find currently logged on user
$Loggedon = Get-WmiObject -ComputerName $env:COMPUTERNAME -Class Win32_Computersystem | Select-Object UserName
# Split domain and username.
$Domain,$User = $Loggedon.Username.split('\',2)
# NOTE: When you use a SPECIFIC catch block, exceptions thrown by -ErrorAction Stop MAY LACK
# some InvocationInfo details such as ScriptLineNumber.
# REMEDY: If that affects you, remove the SPECIFIC exception type [System.Management.Automation.RuntimeException] in the code below
# and use ONE generic catch block instead. Such a catch block then handles ALL error types, so you would need to
# add the logic to handle different error types differently by yourself.
# catch [System.Management.Automation.RuntimeException]
# NOTE: When you use a SPECIFIC catch block, exceptions thrown by -ErrorAction Stop MAY LACK
# some InvocationInfo details such as ScriptLineNumber.
# REMEDY: If that affects you, remove the SPECIFIC exception type [System.Management.Automation.CommandNotFoundException] in the code below
# and use ONE generic catch block instead. Such a catch block then handles ALL error types, so you would need to
# add the logic to handle different error types differently by yourself.
{
# get error record
[Management.Automation.ErrorRecord]$e = $_
# retrieve information about runtime error
$info = [PSCustomObject]@{
Exception = $e.Exception.Message
Reason = $e.CategoryInfo.Reason
Target = $e.CategoryInfo.TargetName
Script = $e.InvocationInfo.ScriptName
Line = $e.InvocationInfo.ScriptLineNumber
Column = $e.InvocationInfo.OffsetInLine
}
# output information. Post-process collected info, and log info (optional)
$info
}
{
# get error record
[Management.Automation.ErrorRecord]$e = $_
# retrieve information about runtime error
$info = [PSCustomObject]@{
Exception = $e.Exception.Message
Reason = $e.CategoryInfo.Reason
Target = $e.CategoryInfo.TargetName
Script = $e.InvocationInfo.ScriptName
Line = $e.InvocationInfo.ScriptLineNumber
Column = $e.InvocationInfo.OffsetInLine
}
# output information. Post-process collected info, and log info (optional)
$info#>
}
# Oppretter WindowsForm / GUI for applikasjonen.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Heading
$form = New-Object -TypeName System.Windows.Forms.Form
$form.Text = 'Test-Heading'
$form.Size = New-Object -TypeName System.Drawing.Size -ArgumentList (400, 600)
$form.StartPosition = 'CenterScreen'
#OK-knapp
$OKButton = New-Object -TypeName System.Windows.Forms.Button
$OKButton.Location = New-Object -TypeName System.Drawing.Point -ArgumentList (170, 485)
$OKButton.Size = New-Object -TypeName System.Drawing.Size -ArgumentList (100, 50)
$OKButton.Text = 'OK'
$OKButton.DialogResult = [Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
#Avbryt-knapp
$CancelButton = New-Object -TypeName System.Windows.Forms.Button
$CancelButton.Location = New-Object -TypeName System.Drawing.Point -ArgumentList (270, 485)
$CancelButton.Size = New-Object -TypeName System.Drawing.Size -ArgumentList (100, 50)
$CancelButton.Text = 'Avbryt'
$CancelButton.DialogResult = [Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
# Tekst-label
$label = New-Object -TypeName System.Windows.Forms.Label
$label.Location = New-Object -TypeName System.Drawing.Point -ArgumentList (10, 20)
$label.Size = New-Object -TypeName System.Drawing.Size -ArgumentList (280, 20)
$label.Text = 'Test-Label'
$form.Controls.Add($label)
# Liste-boks
$listBox = New-Object -TypeName System.Windows.Forms.ListBox
$listBox.Location = New-Object -TypeName System.Drawing.Point -ArgumentList (10, 40)
$listBox.Size = New-Object -TypeName System.Drawing.Size -ArgumentList (360, 20)
$listBox.Height = 400
# Hashtable made to be able to show one text in the listbox, but return a different value.
$TESThash = @{
'TEST1' = '1'
'TEST2' = '2'
'TEST3' = '3'
}
# Listbox-objects, one listbox-item pr. line.
$null = $listBox.Items.Add('TEST1')
$null = $listBox.Items.Add('TEST2')
$null = $listBox.Items.Add('TEST3')
$form.Controls.Add($listBox)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [Windows.Forms.DialogResult]::OK)
{
$TESTalias = $TESThash[$listBox.SelectedItem]
# File to change
$file = "C:\Users\$User\ist.ini"
# Get file content and store it into $content variable
$content = Get-Content -Path $file
# Endrer tekst på linje 33 og linje 53
$content[32] = 'PICTUREPATH=K:\Opplaering\Bilete\'+"$TESTalias"
$content[52] = 'PICTUREPATH=K:\Opplaering\Bilete\'+"$TESTalias"
# Set the new content
$content | Set-Content -Path $file
if(!(Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows\Currentversion\Uninstall\ExtensBildeFix")){
New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ExtensBildeFix" -Value "1"}
$form.Controls|%{$_.Text}}