Loop Multiple Values In Variable Output To csv Powershell - 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.

Related

learning powershell, and having some issues with GetADUser with -Filter

So I am having some issues with the below script. The weird part is, when I run the apparently offending part separately by itself, it works fine. It's only when it tries to run in the add_Click function that it throws an error message.
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$SearchTermTest=Read-Host -Prompt "Enter First or last name"
$UsersTest = Get-ADUser -Filter "GivenName -eq '$SearchTermTest' -or SurName -eq '$SearchTermTest'"
Write-Output $UsersTest
# Create the form
$SearchForm = New-Object System.Windows.Forms.Form
$SearchForm.Text = "Search User"
$SearchForm.Size = New-Object System.Drawing.Size(500,500)
# Create the label and textbox for user input
$FirstLastNameLabel = New-Object System.Windows.Forms.Label
$FirstLastNameLabel.Location = New-Object System.Drawing.Size(20,20)
$FirstLastNameLabel.Text = "Enter First or Last Name"
$SearchForm.Controls.Add($FirstLastNameLabel)
$InputTextBox = New-Object System.Windows.Forms.TextBox
$InputTextBox.Location = New-Object System.Drawing.Size(150,20)
$SearchForm.Controls.Add($InputTextBox)
# Create the DataGridView
$DataGridView1 = New-Object System.Windows.Forms.DataGridView
$DataGridView1.Location = New-Object System.Drawing.Size(20,50)
$DataGridView1.Size = New-Object System.Drawing.Size(450,400)
$SearchForm.Controls.Add($DataGridView1)
# Create the search button
$SearchButton = New-Object System.Windows.Forms.Button
$SearchButton.Location = New-Object System.Drawing.Size(280,20)
$SearchButton.Size = New-Object System.Drawing.Size(100,20)
$SearchButton.Text = "Search"
$SearchButton.Add_Click({
$SearchTerm = $InputTextBox.Text
$Users = Get-ADUser -Filter "GivenName -eq '$SearchTerm' -or SurName -eq '$SearchTerm'"
$DataGridView1.DataSource = $null
$DataGridView1.DataSource = $Users
$DataGridView1.AutoResizeColumns([System.Windows.Forms.DataGridViewAutoSizeColumnMode]::DisplayedCells)
})
$SearchForm.Controls.Add($SearchButton)
$SearchForm.ShowDialog()
Get-ADUser : The search filter cannot be recognized
At C:\Users\ad_forrest.vasilinda\Desktop\user password search.ps1:36 char:14
+ ... $Users = Get-ADUser -Filter "GivenName -eq '$SearchTerm' -or SurNa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Error message is above. Any ideas? I am at my wits end honestly. I have the exact same GetADUser statement running with the same filter at the beginning of the script with no errors, its only in the add_click function it throws it.
Update -- changing some of the variable names to be more descriptive and not match any of the reserved names now only causes the error to pop up when the field is left blank. However, now when there is text in the field and I push the button, nothing happens.
I was getting a blank screen as well so I changed it a bit and added some error checking. Now you can search an empty string or part of the name. I changed the filter to -Like so you get better results.
I added a variable $properties so you can add/remove the AD attributes you would like to use.
Cheers
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Properties to display
$properties = "GivenName","SurName","Mail","UserPrincipalName","Company"
# Create the form
$SearchForm = New-Object System.Windows.Forms.Form
$SearchForm.Text = "Search User"
$SearchForm.Size = New-Object System.Drawing.Size(800,500)
# Create the label and textbox for user input
$FirstLastNameLabel = New-Object System.Windows.Forms.Label
$FirstLastNameLabel.Location = New-Object System.Drawing.Size(20,20)
$FirstLastNameLabel.Text = "Enter First or Last Name"
$SearchForm.Controls.Add($FirstLastNameLabel)
$InputTextBox = New-Object System.Windows.Forms.TextBox
$InputTextBox.Location = New-Object System.Drawing.Size(160,20)
$SearchForm.Controls.Add($InputTextBox)
# Create the DataGridView
$DataGridView1 = New-Object System.Windows.Forms.DataGridView
$DataGridView1.Location = New-Object System.Drawing.Size(20,50)
$DataGridView1.Size = New-Object System.Drawing.Size(750,400)
$dataGridView1.ColumnCount = $properties.count
$dataGridView1.ColumnHeadersVisible = $true
$i=0
$properties | %{
$dataGridView1.Columns[$i++].Name = $_
}
$SearchForm.Controls.Add($DataGridView1)
# Create the search button
$SearchButton = New-Object System.Windows.Forms.Button
$SearchButton.Location = New-Object System.Drawing.Size(280,20)
$SearchButton.Size = New-Object System.Drawing.Size(100,20)
$SearchButton.Text = "Search"
$SearchButton.add_click({
$SearchTerm = ($InputTextBox.Text).trim()
$filter = "*"
if ($searchTerm) {
$filter = "GivenName -like '*$SearchTerm*' -or SurName -like '*$SearchTerm*'"
}
[array]$users = Get-ADUser -Filter $filter -Properties $properties | select $properties
$DataGridView1.Rows.Clear()
if ($users) {
$users | %{
$DataGridView1.Rows.Add($_.psobject.Properties.value)
}
}
$DataGridView1.AutoResizeColumns([System.Windows.Forms.DataGridViewAutoSizeColumnMode]::DisplayedCells)
})
$SearchForm.Controls.Add($SearchButton)
$SearchForm.ShowDialog()

copy file in a gui with checkboxes

i'm creating a gui in powershell for copying files. first i add a file with a button, next i choose the folder where to copy and then i want to copy. unfortunately the script says the file path is empty. how can i solve this problem? Furthermore, i want to add 2 functions.
a warning if no checkbox is marked
a text field next to the choose button where i can see the path from the file i want to copy
$PSDefaultParameterValues['*:Encoding'] = 'ascii'
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#create form
$form = New-Object System.Windows.Forms.Form
$form.Width = 500
$form.Height = 300
$form.MaximizeBox = $false
#choose file button
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(10,10)
$Button.Size = New-Object System.Drawing.Size(150,50)
$Button.Text = "choose file"
$Button.Add_Click({
Function Get-FileName($initialDirectory) {
[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
$file = Get-FileName -initialDirectory “c:”
})
$form.Controls.Add($Button)
#create checkbox1
$checkBox = New-Object System.Windows.Forms.CheckBox
$checkBox.Location = New-Object System.Drawing.Point (10, 100)
$checkBox.Size = New-Object System.Drawing.Size(350,30)
$checkBox.Text = "folder 1"
$form.Controls.Add($checkBox)
#create checkbox2
$checkBox2 = New-Object System.Windows.Forms.CheckBox
$checkBox2.Location = New-Object System.Drawing.Point (10, 150)
$checkBox2.Size = New-Object System.Drawing.Size(350,30)
$checkBox2.Text = "folder 2"
$form.Controls.Add($checkBox2)
#copy file button
$Button2 = New-Object System.Windows.Forms.Button
$Button2.Location = New-Object System.Drawing.Size(10,200)
$Button2.Size = New-Object System.Drawing.Size(150,50)
$Button2.Text = "copy file"
$Button2.Add_Click({
#checkbox1 action
if ($checkBox.Checked -eq $true)
{
copy-item -Path $file -Destination "C:\folder 1"
}
#checkbox2 action
if ($checkBox2.Checked -eq $true)
{
copy-item -Path $file -Destination "C:\folder 2"
}
})
$form.Controls.Add($Button2)
#end
[void]$form.ShowDialog()
There are plenty of improvements to be suggested but let's focus on your questions:
The problem is that the scope of your $file variable is local to the function Get-Filename.
So when accessed from outside of the function, it is always null.
As stated in the comments, the minimum modification for your script to work is the change the following line (I would also suggest to declare it initially outside of the function, at global level for sake of clarity):
# From this
$file = Get-FileName -initialDirectory "c:"
# To this
$Global:file = Get-FileName -initialDirectory "c:"
To add a textbox with the choosen filename, proceed as for the other controls:
#Text box with choosen file name
$txtBox = New-Object System.Windows.Forms.TextBox
$txtBox.Location = New-Object System.Drawing.Point (180, 20)
$txtBox.Size = New-Object System.Drawing.Size(280,20)
$form.Controls.Add($txtBox)
And to update the text, add the following line after setting the $Global:file variable:
$Global:file = Get-FileName -initialDirectory "c:"
$txtBox.Text = $Global:file
Finally, a message can be displayed if you add the following code to your $Button2.Add_Click code:
#nothing checked
if(($checkBox.Checked -eq $false) -and ($checkBox.Checked -eq $false)) {
[System.Windows.Forms.Messagebox]::Show("No CheckBox checked")
}

Powershell Codewrap for repeat option and bug with form

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)

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