Powershell Codewrap for repeat option and bug with form - forms

I got a script which is handling some things. I know a lot say I should get more short scripts which are working. But there are many people which can't handle many files or scripts and want 1 which can do all, and I can't tell 600 people which script does what. I need a kind of assembling at least of a few.
I wanted to make a workaround for the canceld options. The easiest way is to wrap all the code in a do {} while () for sure. But are there any options where I can repeat a single option? Something like when it asks do you really want to cancel.
And a real annoying bug I can't fix is that after every single action the start form blops up again. I tried out diffrent ways to debug with a counter but it didn't count up and also I tried to put the function assembling at a other place didn't fix it as well. Don't know why it happens.
Code for repro
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Set-PSDebug -Strict #Errorcall if a variable isnt declared
#Function Assembling
function Saveat()
{
#working
$Saveat = New-Object -Typename System.Windows.Forms.SaveFileDialog
$Saveat.filter = "CSV (*.csv)| *.csv"
#IF selection is canceld
$result = $form.ShowDialog()
[void]$Saveat.ShowDialog()
return $Saveat.FileName
}
function Compare($location1, $location2)
{
#work in progress
$CSV1 = Import-Csv -Path $location1 -UseCulture
$CSV2 = Import-Csv -Path $location2 -UseCulture
$Compared = Compare-Object -ReferenceObject $CSV1 -DifferenceObject $CSV2 |
select -ExpandProperty inputObject |
sort
[void] $CSV1
[void] $CSV2
return $Compared
}
function whichcsv()
{
#working
$location = New-Object System.Windows.Forms.OpenFileDialog
$location.Filter = "CSV (*.csv)| *.csv"
$result = $form.ShowDialog()
[void]$location.ShowDialog()
return $location.FileName
}
#Select which option Form
#region Initiate Form **This Form Blops up after every user action**
$form = New-Object System.Windows.Forms.Form
$form.Text = "CSV Liste"
$form.Size = New-Object System.Drawing.Size(300,300)
$form.StartPosition = "CenterScreen"
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,195)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,195)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = "Welche CSV Liste soll geladen werden:"
$form.Controls.Add($label)
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(260,20)
$listBox.Height = 150
[void] $listBox.Items.Add("List Filter")
[void] $listBox.Items.Add("ADComputer")
[void] $listBox.Items.Add("AS400 Personal Not implemented yet")
[void] $listBox.Items.Add("ADBenutzer Not implemented yet")
#endregion
$form.Controls.Add($listBox)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
#Choosed Option
$x = $listBox.SelectedItem
switch ($x)
{
#Option 1 working
"List Filter"
{
#Select path of the CSV
$csvpath = whichcsv
#IF selection is canceld
if ($csvpath -eq "")
{
Write-Host "Operation Canceld"
}
else
{
#CSV Import and Filter set
$CSV = Import-Csv -Path $csvpath -UseCulture
$Filter = Read-Host "Please enter columname. Leave clear for cancel"
if ($Filter -eq "")
{
Write-Host "Operation canceld"
}
else
{
$y = $CSV | Select $Filter
Write-Host "CSV Successfull Imported and Filter set"
}
$SDestination = Saveat
if ($SDestination -eq "")
{
Write-Host "Operation Canceld"
}
else
{
Write-Host "Process started"
foreach ($y1 in $y)
{
New-Object PSObject -Property #{Inventarnummer=$y1.$Filter} | Export-Csv $SDestination -NoTypeInformation -Append
}
Write-Host "Process finished"
}
}
}
#Option 2 working
"ADComputer"
{
#Select path of the CSV
$csvpath = whichcsv
#IF selection is canceld
if ($csvpath -eq "")
{
Write-Host "Operation Canceld"
}
else
{
#CSV Import with filter
$CSV = Import-Csv -Path $csvpath -Delimiter ','
$Filter = Read-Host "Please enter columname. Leave clear for cancel"
if ($Filter -eq "")
{
Write-Host "Operation canceld"
}
else
{
$y = $CSV | Select $Filter
Write-Host "CSV Successfull Imported and Filter set"
}
#Path selection
$Saveworking = Saveat
$SaveFailed = Saveat
if($Saveworking -eq "")
{
Write-Host "Operation canceld"
}
elseif ($SaveFailed -eq "")
{
Write-Host "Operation canceld"
}
else
{
#Progress
Write-Host "Process Start"
foreach($n in $y)
{
try
{
$Computer = [system.net.dns]::resolve($n.$Filter) | Select HostName,AddressList
$IP = ($Computer.AddressList).IPAddressToString
Write-Host $n.$Filter $IP
New-Object PSObject -Property #{IPAddress=$IP; Name=$n.$Filter} | Export-Csv $Saveworking -NoTypeInformation -Append
}
catch
{
Write-Host "$($n.$Filter) is unreachable."
New-Object PSObject -Property #{Name=$n.$Filter} | Export-Csv $SaveFailed -NoTypeInformation -Append
}
}
Write-Host "Process successfull completed"
}
}
}
#Option 3 Not implemented yet
"AS400 Personal Not implemented yet"
{
Write-Host "Not implemented yet"
}
#Option 4 not implemented yet
"ADBenutzer Not implemented yet"
{
Write-Host "Not implemented yet"
}
}
}
else
{
Write-Host "Operation Canceld"
}

I guess you need to work with form events rather than .DialogResult.
For the Cancel button you would probably do something like: $CancelButton.Add_Click({[Void]$Form.Window.Close()})
For the OK button you would probably want to put the majority of your OK task in a function and invoke it from a similar event:
Function Task {
#Choosed Option
$x = $listBox.SelectedItem
switch ($x)
{
#Option 1 working
"List Filter"
{
#Select path of the CSV
$csvpath = whichcsv
...
$OkButton.Add_Click({Task})
(And close the dialog ([Void]$Form.Window.Close()) when the task is completed)

Related

Powershell GUI, define variables per button

Right now i write an gui for a simple filter script for completnes this is the whole script right now
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objForm = New-Object System.Windows.Forms.Form
$objForm.StartPosition = "CenterScreen"
$objForm.Size = New-Object System.Drawing.Size(1200,800)
$objForm.Text = "Test GUI"
$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(900,600)
$dataGridView = New-Object System.Windows.Forms.DataGridView
$dataGridView.Size=New-Object System.Drawing.Size(800,400)
#Filtern
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(30,10)
$OKButton.Size = New-Object System.Drawing.Size(300,92)
$OKButton.Text = "Filtern"
$OKButton.Name = "Filter"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::None
$OKButton.Add_Click({$i= 0
$path = "C:\temp\smtpfilter\LNS5filter.txt"
$length = (Get-Content $path).Length
#Datum, Hostname und Message Nummer
$result = Get-Content $path | ForEach-Object {
if($_ -match '(\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}:\d{2}).*\(((?:\d{1,3}\.){3}\d{1,3})\) disconnected\.?\s+(\d+) message\[s\]'){
try {
#$dns = [System.Net.Dns]::GetHostEntry($matches[2]).HostName
}
catch {
#$dns = 'Not available'
}
[PsCustomObject]#{
IP = $matches[2]
Messages = [int]$matches[3]
#DNSName = $dns
Date = [datetime]::ParseExact($matches[1], 'dd.MM.yyyy HH:mm:ss', $null)
}}
$i++
if($i % 1000 -eq 0){
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length) * 100)
}}
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length) * 100)
#Messages Counted
$cumulative = $result | Group-Object -Property IP | ForEach-Object {
[PsCustomObject]#{
IP = $_.Name
Messages = ($_.Group | Measure-Object -Property Messages -Sum).Sum
#DNSName = $_.Group[0].DNSName
Date = ($_.Group | Sort-Object Date)[-1].Date
}
}})
$objForm.Controls.Add($OKButton)
#Ergebnis Anzeigen
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(30,112)
$OKButton.Size = New-Object System.Drawing.Size(300,92)
$OKButton.Text = "Ergebnis anzeigen"
$OKButton.Name = "Egebnis Button"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::None
$OKButton.Add_Click({$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Multiline = $True;
$objTextBox1.Location = New-Object System.Drawing.Size(360,10)
$objTextBox1.Size = New-Object System.Drawing.Size(800,600)
$objTextBox1.Text = $cumulative | Out-String
$objTextBox1.Font = "courier New, 13"
$objTextBox1.Scrollbars = "Vertical"
$objForm.Controls.Add($objTextBox1)
#outgridview
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(30,214)
$OKButton.Size = New-Object System.Drawing.Size(300,92)
$OKButton.Text = "Ergebnis in GridView"
$OKButton.Name = "GridView"
$OKButton.DialogResult = "OK"
$OKButton.Add_Click({$cumulative | Out-GridView})
$objForm.Controls.Add($OKButton)
#Export CSV
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(30,316)
$OKButton.Size = New-Object System.Drawing.Size(300,92)
$OKButton.Text = "Export CSV (in C:/temp)"
$OKButton.Name = "CSV"
$OKButton.DialogResult = "OK"
$OKButton.Add_Click({$cumulative | Export-Csv -Path 'C:\temp\SMTPresult.Csv'})
$objForm.Controls.Add($OKButton) })
$objForm.Controls.Add($OKButton)
[void] $objForm.ShowDialog()
The first $OKButton should basically filter the .txt file which is defined in $path and then in the lower part count the results together, when i press it an progressbar starts in the background in the ISE, but i noticed that there is no result saved in $result or in $cumulative. If it would work than i guess i could display the results with the lower button.
What do i miss here, cant i define varaibles with buttons?
For anyone who might get the same Problem i got the result after trying. The Problem was the scope of both of my variables $result & $cummulative. Since they were created in an Button they also only function in that Button. To use them after i clicked the Button i just had to add $global:
So in the end it looked like
$OKButton.Add_Click({$i= 0
$length = (Get-Content $path).Length
#Datum, Hostname und Message Nummer
$global:result = Get-Content $path | ForEach-Object {
if($_ -match '(\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}:\d{2}).*\(((?:\d{1,3}\.){3}\d{1,3})\) disconnected\.?\s+(\d+) message\[s\]'){
try {
#$dns = [System.Net.Dns]::GetHostEntry($matches[2]).HostName
}
catch {
#$dns = 'Not available'
}
[PsCustomObject]#{
IP = $matches[2]
Messages = [int]$matches[3]
#DNSName = $dns
Date = [datetime]::ParseExact($matches[1], 'dd.MM.yyyy HH:mm:ss', $null)
}}
$i++
if($i % 1000 -eq 0){
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length) * 100)
}}
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length) * 100)
#Messages Counted
$global:cumulative = $result | Group-Object -Property IP | ForEach-Object {
[PsCustomObject]#{
IP = $_.Name
Messages = ($_.Group | Measure-Object -Property Messages -Sum).Sum
#DNSName = $_.Group[0].DNSName
Date = ($_.Group | Sort-Object Date)[-1].Date
}
}})
$objForm.Controls.Add($OKButton)

Powershell if else statement

I am having some difficulties with my Powershell script. With this script I am able to enable disabled AD accounts. It works, but I am receiving the wrong output. Accounts got enabled, but still receive the output from the else statement 'Account has not been enabled'. Anyone who can help me? Thanks!
Add-Type -AssemblyName System.Windows.Forms
$SystemInfoForm = New-Object System.Windows.Forms.Form
$SystemInfoForm.ClientSize = "300,100"
$SystemInfoForm.Text = "Enable AD Accounts"
$SystemInfoForm.BackColor = "#ffffff"
$SystemInfoForm.StartPosition = "CenterScreen"
$objIcon = New-Object system.drawing.icon ("C:\Temp\System Info.ico")
$SystemInfoForm.Icon = $objIcon
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = 'Please enter the disabled AD account below:'
$SystemInfoForm.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,40)
$textBox.Size = New-Object System.Drawing.Size(260,20)
$textBox.Text = "Enter AD account..."
$SystemInfoForm.Controls.Add($textBox)
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(10,70)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$okButton.Add_Click(
{
$Username = $textBox.Text
if (Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount)
{
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
else
{
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}
}
)
$SystemInfoForm.Controls.Add($okButton)
[void]$SystemInfoForm.ShowDialog()
Regards,
Ralph
Enable-ADAccount doesn't return any output by default, so the entire pipeline expression:
Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount
... will evaluate to nothing - and all of that nothing evaluates to $false in your if condition.
Use a try/catch block to catch errors from Enable-ADAccount and then alert the based on that:
try {
Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount -ErrorAction Stop
# We got this far because Enable-ADAccount didn't throw any errors
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
catch {
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}
Alternatively use the -PassThru switch with Enable-ADAccount to have it return the account, then inspect that:
$enabledAccount = Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount -PassThru
if($enabledAccount.Enabled){
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
else {
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}

Loop Multiple Values In Variable Output To csv Powershell

I created a script where a dialogue box pops up and the value you enter goes into foreach. I didn't know how to take a single value created in a running script and process it. It worked, although I knew it wasn't the right way to do it.. Now I've created a loop to prompt again and the goal is to append each value into a csv. My problem is now the original variable value is overwritten by the next value put into the prompt before writing out to a csv. How can I build each entry into the looping dialogue box and create the csv?
You can see in the powershell script that I create $x from the value input to the dialogue box, then I cycle the script into a function that repeats the dialogue prompt. When it does that it overwrites the first value of $x. I'm trying to figure out how to build many values before writing the all to the csv.
This script is to have a user enter a group, check it against Active Directory, and then generate a CSV.
...Update## I was able to resolve it. I'm removing the original test code and putting the final product. The following script creates a form which asks for an object in Active Directory. It checks active directory then outputs to a spreadsheet, and asks again until canceled. Building the variable repeatedly.
function ProcessOut ($x , $group) {
$result = #()
Foreach ($Line in $x){
$GroupName = "domain.local\" + $group
$OutList = New-Object System.Object
$OutList | Add-Member -type NoteProperty -Name "DisplayPath_GroupName" -value $GroupName
$OutList | Add-Member -type NoteProperty -Name "RuleName" -value "AutomaticApproval"
$OutList | Add-Member -type NoteProperty -Name "RuleClauses" -value '
$result+= $OutList
}
#Output to csv
$outputfilepath = 'c:\users\technician\desktop\'
$outputfilename = $outputfilepath + 'FinalFile.csv'
$result | export-csv $outputfilename -Append -encoding unicode -NoTypeInformation
}
function PromptInput {
add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Group Auto-Approval Setup'
$form.Size = New-Object System.Drawing.Size(500,230)
$form.StartPosition = 'CenterScreen'
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(170,100)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'OK'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(260,100)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(200,40)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = "Enter a group name:"
$form.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(100,65)
$textBox.Size = New-Object System.Drawing.Size(300,120)
$form.Controls.Add($textBox)
$form.Topmost = $true
$form.Add_Shown({$textBox.Select()})
$result = $form.ShowDialog()
if ($result -eq 'Cancel'){
Exit
}
if ($result -eq [System.Windows.Forms.DialogResult]::OK){
$x = $textBox.Text
}
return $x
}
$continue = $true
while($continue){
$input = PromptInput
Add-Type -AssemblyName microsoft.visualbasic
$searcher = [ADSISearcher]"(SAMAccountName=$input)"
$result = $searcher.FindOne()
if($result){
ProcessOut $result $input
$additional = [System.Windows.Forms.MessageBox]::Show("Would you like to enter another group?" , "Status" , 4)
if ($additional -eq "NO"){
Exit
}
} else{
[System.Windows.Forms.MessageBox]::Show("Group name not found - Please enter a valid group name")
}
}
Use an ArrayList or an Array to build things up. Create this at the Global level so that it is accessible within the code. Example:
# Create an empty array outside of the loop
$myArray = #()
# Get all running processes
$processes = Get-Process
# for each process in the list of processes we are going to do something
foreach($process in $processes)
{
# Create a Pipe separated string
$myString = $process.Name + "|" + $process.Id
# Add the process name to my array.
$myArray += $myString
}
# Export the array to a CSV file
$myArray | Export-Csv -Path c:\myfile.csv
Or if you don't like arrays (I don't for many reasons...) Try a List...
Replace the 2nd line with:
$myArray = New-Object System.Collections.ArrayList
Replacing the 14th line with
$myArray.Add($myString) > $null
Notice that I am piping the output to null. This is to stop it echoing back which may / maynot be useful to you.
Hope this helps.

Powershell Switchcase for CSV Filtering-> Process runtrough ->and Ouput

I would like to be able to select which csv runs through as the input csv's are standardiesd and i need to filter for the process. My problem is i cant handle the Filter part. The Process is running fine i tested it several times. Also the csv load is working and the save at part as well those got tested seperatly as well. But as soon as the switchcase and the filter part are in it doesnt work anymore. But i need it as otherwise i have to write 3 more scripts what wouldnt make sense. Any recommandtion how to pass this filter.
Full Code
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#Select which option and which CSV
$form = New-Object System.Windows.Forms.Form
$form.Text = "CSV Liste"
$form.Size = New-Object System.Drawing.Size(300,300)
$form.StartPosition = "CenterScreen"
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,195)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,195)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = "Welche CSV Liste soll geladen werden:"
$form.Controls.Add($label)
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(260,20)
$listBox.Height = 150
[void] $listBox.Items.Add("AS400 Computer")
[void] $listBox.Items.Add("AS400 Personalstamm")
[void] $listBox.Items.Add("ADComputer")
[void] $listBox.Items.Add("ADBenutzer")
$form.Controls.Add($listBox)
$form.Topmost = $True
$result = $form.ShowDialog()
#Filter for the CSV
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$location = New-Object System.Windows.Forms.OpenFileDialog
$location.initialDirectory = $initialDirectory
$location.filter = "CSV (*.csv)| *.csv"
$location.ShowDialog()
$CSV = Import-Csv -Path $location.FileName -UseCulture
$x = $listBox.SelectedItem
switch ($x)
{
"AS400 Computer"
{
$y = $CSV | Select Inventarnummer
}
"AS400 Personalstamm"
{
$y = $CSV | Select filter1
}
"ADComputer"
{
$y = $CSV | Select filter1
}
"ADBenutzer"
{
$y = $CSV | Select filter1
}
}
}
#Save Data at
$Saveworking = New-Object -Typename System.Windows.Forms.SaveFileDialog
$Saveworking.filter = "CSV (*.csv)| *.csv"
$Saveworking.ShowDialog()
$Savefailed = New-Object -Typename System.Windows.Forms.SaveFileDialog
$Savefailed.filter = "CSV (*.csv)| *.csv"
$Savefailed.ShowDialog()
#Process Runtrough
foreach($n in $y)
{
try {
$Computer = [system.net.dns]::resolve($n.NAME) | Select HostName,AddressList
$IP = ($Computer.AddressList).IPAddressToString
Write-Host $n.NAME $IP
New-Object PSObject -Property #{IPAddress=$IP; Name=$n.NAME} | Export-Csv $Saveworking.FileName -NoTypeInformation -Append
} catch {
Write-Host "$($n.NAME) is unreachable."
New-Object PSObject -Property #{Name=$n.NAME} | Export-Csv $Savefailed.FileName -NoTypeInformation -Append
}
}
edit: Code updated can now select Column and is working allmost. As it seems it cant run the Process right now as it is not felxible enough. Working on Solution appricate any recommandtions.

replace text with a textbox input using variable

In my script I have a textbox- the user inserts text in it and than I want to change the text in a file (which the script creates earlier) to what the user inserted in the textbox.
The problem: it does deletes the part I wanted to be changed in the file- but it doesn`t write the text of the user instead. I also tried to locate the variable in the if loop- and it did changed the text like i wanted, but when I run the script again it wrote the old text in the disabled textbox.
my script is kinda long so I wont post all of it, but here are the importent parts. Thanks for the help!
#This creates a checkbox called dsp.z
$objDspCheckbox = New-Object System.Windows.Forms.Checkbox
$objDspCheckbox.Location = New-Object System.Drawing.Size(20,40)
$objDspCheckbox.Size = New-Object System.Drawing.Size(150,20)
$objDspCheckbox.Text = "dsp.z"
$objDspCheckbox.TabIndex = 0
$objForm.Controls.Add($objDspCheckbox)
#This creates the TextBox1 and put it on disable
$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Location = New-Object System.Drawing.Size(450,40)
$objTextBox1.Size = New-Object System.Drawing.Size(140,150)
$objTextBox1.TabIndex = 3
$objTextBox1.text = $text1
$objTextBox1.Enabled = $false
$objForm.Controls.Add($objTextBox1)
#This creates a checkbox for textbox1
$objDsp2Checkbox = New-Object System.Windows.Forms.Checkbox
$objDsp2Checkbox.Location = New-Object System.Drawing.Size(430,40)
$objDsp2Checkbox.Size = New-Object System.Drawing.Size(150,20)
$objDsp2Checkbox.TabIndex = 0
$objForm.Controls.Add($objDsp2Checkbox)
#Enables the textbox when user check the box:
#textbox1
$objDsp2Checkbox_OnClick = {
if ($objDsp2Checkbox.Checked -eq $true)
{
$objTextBox1.Enabled = $true
}
elseif ($objDsp2Checkbox.Checked -eq $false)
{
$objTextBox1.Enabled = $false
}
}
$objDsp2Checkbox.Add_Click($objDsp2Checkbox_OnClick)
#variables
$text1=$objTextBox1.Text
#This creates the ok and cancle buttons:
#ok Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(220,155)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click(
{
if (($objDspCheckbox.Checked -eq $true) -and ($objDsp2Checkbox.Checked -eq $true))
{
New-Item $path -itemtype file -name Dsp.json -value "old" ;((Get-Content "c:\users\$env:USERNAME\documents\Json\dsp.json") -replace 'old', $text1 | out-file "c:\users\$env:USERNAME\documents\Json\dsp.json") ;$objForm.close()
}
Try to Change This Line (specifly the $text1) to $objTextBox1.Text :
New-Item $path -itemtype file -name Dsp.json -value "old" ;
((Get-Content "c:\users\$env:USERNAME\documents\Json\dsp.json") -replace 'old', $text1 |
Out-file "c:\users\$env:USERNAME\documents\Json\dsp.json") ;$objForm.close()
To:
New-Item $path -itemtype file -name Dsp.json -value "old" ;
((Get-Content "c:\users\$env:USERNAME\documents\Json\dsp.json") -replace 'old', $objTextBox1.Text |
Out-file "c:\users\$env:USERNAME\documents\Json\dsp.json") ;$objForm.close()
I'm not sure if it's the case but if you just need to save the textbox text to file there's an easier approach :
$objTextBox1.Text | Out-file "c:\users\$env:USERNAME\documents\Json\dsp.json")