I had develop a script that basically restart a service in a remove server based on a selection.
This selection is done by a form.
The problem is... when I run this using the ISE... the script work totally fine.
When I run this using the RIGHT CLICK / RUN with Powershell
My form doesn't work. The Button that I had created didn't appear...
What can be wrong?
Here is my code:
Function Write-Centered {
Param( [string] $message,
[string] $color = "black")
$offsetvalue = [Math]::Round(([Console]::WindowWidth / 2) + ($message.Length / 2))
Write-Host ("{0,$offsetvalue}" -f $message) -ForegroundColor $color
}
clear
$timestamp=Get-date -format yyyy_MM_dd_hh_mm_ss
$systems = #(
("System 1","Server1","bmc_ctsa_sm_SAP_Instance_2"),
("System 2","Server2","bmc_ctsa_sm_SAP_Instance_6"),
("System 3","Server3","bmc_ctsa_sm_SAP_Instance_6")
)
Write-Centered "Service Restart Tool" "Green"
Write-Centered "Choose the target system you would like to restart" "Green"
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form1 = New-Object System.Windows.Forms.Form
$Form1.ClientSize = New-Object System.Drawing.Size(300, 100)
$form1.topmost = $true
$Form1.Controls.Add($Button)
$Form1.Text = "SSPR Restart Tool"
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Point(150, 25)
$Button.Size = New-Object System.Drawing.Size(120, 25)
$Button.add_Click({
$label.Text = $comboBox1.SelectedItem.ToString()
$Form1.Close()
})
$Button.Text = "Start Process"
$Label = New-Object System.Windows.Forms.Label
$Label.Location = New-Object System.Drawing.Point(10, 10)
$Label.Size = New-Object System.Drawing.Size(300, 15)
$Label.Text = "Please select the system you would like to restart"
$Form1.Controls.Add($Label)
$comboBox1 = New-Object System.Windows.Forms.ComboBox
$comboBox1.Location = New-Object System.Drawing.Point(10, 25)
$comboBox1.Size = New-Object System.Drawing.Size(120, 25)
foreach($system in $systems)
{
$comboBox1.Items.add($system[0]) | Out-Null
}
$Form1.Controls.Add($comboBox1)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(70, 90)
$label.Size = New-Object System.Drawing.Size(98, 23)
$label.Text = ""
$Form1.Controls.Add($label)
[void]$form1.showdialog()
Write-Centered $comboBox1.Text "Yellow"
$do=0
$i=0
do {
if ($comboBox1.Text -eq $systems[$i][0]){
$result=$i
$i++
}
$do++
}while ($do -le $systems.length-1)
$System=$systems[$result][0]
$Server=$systems[$result][1]
$Instance=$systems[$result][2]
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
"Start the process."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
"Cancel the process."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice("",`
"`nWould you like to progress with the service restart? `n`nSystem: $System`nServer: $Server`nInstance: $Instance", $options, 0)
if ($result -eq 0) {
$services = Get-Service -computername $Server -name $Instance
$target=$services.name
$sharefolder = "\\"+$Server+"\c$"
New-PSDrive –Name “X” –PSProvider FileSystem –Root $sharefolder | out-null
Write-Host ======================================================
Write-Host = Searching for the destination folder. Please wait...
Write-Host ======================================================
$test1=Test-Path "X:\Program Files (x86)\BMC Software"
$test2=Test-Path "X:\Program Files\BMC Software"
if ($test1) {
$file=Get-ChildItem "X:\Program Files (x86)\BMC Software" -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "CONTROL-SA"}
} elseif ($test2){
$file=Get-ChildItem "X:\Program Files\BMC Software" -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "CONTROL-SA"}
}
$fullname=$file.FullName+"\Services Manager\"+$Instance
$fullname
Write-Host ======================================================
Write-Host = Stopping $target
Write-Host ======================================================
Get-Service -Name $target -ComputerName $Server | Set-Service -Status Stopped
$src=$fullname+"\log\*"
$des=$fullname+"\log_bkp_"+$timestamp+"\"
Write-Host ======================================================
Write-Host = Perform LOG folder backup for troubleshooting
Write-Host ======================================================
New-Item $des -type directory | out-null
Move-item -path $src -destination $des -force -verbose
#Remove-item $src -force -recurse -verbose
Get-Service -Name $target -ComputerName $Server | Set-Service -Status Running
Remove-PSDrive -Name "X" | out-null
}
elseif ($result -eq 1) {
BREAK
}
Write-Host ======================================================
Write-Host = Process Completed
Write-Host = You may now close this window
Write-Host ======================================================
Start-Sleep -s 120
Have the screen captures of the results.. but low reputation prevent me to post it... :-(
I typo'd my comment, it should be Controls and not Controles, but that's the issue. After $Form1.Controls.Add($label) add a new line:
$Form1.Controls.Add($Button)
See if it doesn't work as expected at that time. It does for me when I tested it.
A wrong place for the $Form1.Controls.Add($Button) was preventing my code to show up the control button...
Thanks for the hint
Related
I am fairly new with powershell scripting and trying to learn. I am trying to create a PS1 file that runs with a GUI for easy use for other people on my team, that can delete profiles off of a Desktop/Laptop remotely. I have a script below that works for local profiles and would like to enhance it for remote PC's so we dont physically have to collect devices when cleaning up desktops/laptops that are filled with profiles. These computers have a program that runs that refreshes the profiles daily so a script that cleans based on days since last log in will not work.
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(400,300)
$form.Text = "Delete User Profiles"
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Size = New-Object System.Drawing.Size(360,200)
$listBox.Location = New-Object System.Drawing.Point(20,20)
$listBox.SelectionMode = [System.Windows.Forms.SelectionMode]::MultiSimple
$userProfiles = Get-ciminstance -classname Win32_UserProfile
foreach ($userProfile in $userProfiles) {
if (($userProfile.localpath -notmatch "Public") -and ($userProfile.localpath -notmatch "Default")) {
$listBox.Items.Add($userProfile.localpath)
}
}
$form.Controls.Add($listBox)
$deleteButton = New-Object System.Windows.Forms.Button
$deleteButton.Size = New-Object System.Drawing.Size(100,30)
$deleteButton.Location = New-Object System.Drawing.Point(20,230)
$deleteButton.Text = "Delete"
$deleteButton.Add_Click({
foreach ($item in $listBox.SelectedItems) {
##Remove-Item -Path "$item" -Recurse -Force
##Properly removing item from WMI. note: -whatif currently specified so the operation doesn't actually occur
get-ciminstance -classname win32_userprofile | where-object -property localpath -like $item | remove-ciminstance ##-whatif
}
[System.Windows.Forms.MessageBox]::Show("Done","Delete Dialog",[Windows.Forms.MessageBoxButtons]::OkCancel)
})
$form.Controls.Add($deleteButton)
#$form.Controls.Add($listBox)
$showButton = New-Object System.Windows.Forms.Button
$showButton.Size = New-Object System.Drawing.Size(100,30)
$showButton.Location = New-Object System.Drawing.Point(140,230)
$showButton.Text = "Refresh"# "Show"
$showButton.Add_Click({
# foreach ($item in $listBox.SelectedItems) {
# [System.Windows.Forms.MessageBox]::Show("You have chosen to remove $item","Profile Selection Dialog",[Windows.Forms.MessageBoxButtons]::OkCancel)
# }
$listBox.Items.Clear()
$userProfiles = Get-ciminstance -classname Win32_UserProfile
foreach ($userProfile in $userProfiles) {
if (($userProfile.localpath -notmatch "Public") -and ($userProfile.localpath -notmatch "Default")) {
$listBox.Items.Add($userProfile.localpath)
}
}
})
$form.Controls.Add($showButton)
$form.ShowDialog()
Please Help.........
something is wrong and i don't know what's it ,the same script is working in my local machine but when i tried it in VM it just will not work and throw me exception
-the PowerShell is the same version
-the same PowerShell SDK
-i added rule to allowing PowerShell
-my user is admin
-all the parameters are correct and i can enter the SharePoint in browser
Import-Module 'C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll'
Import-Module 'C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll'
Clear-Host
# getting all argument before starting the process #
$SiteURL = "user"
$ListName = "list"
$Username ="email"
$Password ="pass"
if ($SiteURL -eq $null -or $ListName -eq $null -or $Username -eq $null -or $Password -eq $null)
{
Write-Output "Somthing went wrong!"
Write-Output "Some of the variables are not correct"
}
else
{
$outfile = $PSCommandPath | Split-Path -Parent
$outfile += '\items.txt'
Clear-Host
Write-Output "Getting Items"
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$securePassword=ConvertTo-SecureString $Password -AsPlainText -Force
$Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $securePassword)
$Web = $Context.Web
$List = $Web.get_lists().getByTitle($ListName)
$itemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$Context.Load($ListItems)
$Context.ExecuteQuery()
$ListItems | ForEach-Object {
$output=$_["Title"] + "~~"
$output | Out-File -FilePath $outfile -Append
}
Write-Output "Done!"
}
it's seems the security for the local machine has a SSL Certificate for my account by default but in the VM it was missing that Certificate, so i just invoked by using TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
to the first line of my power-shell code and everything worked nice
Works fine based on my testing.
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Clear-Host
# getting all argument before starting the process #
$SiteURL = "https://xxx.sharepoint.com/sites/lee"
$ListName = "testlist"
$Username ="user#xxx.onmicrosoft.com"
$Password ="password"
if ($SiteURL -eq $null -or $ListName -eq $null -or $Username -eq $null -or $Password -eq $null)
{
Write-Output "Somthing went wrong!"
Write-Output "Some of the variables are not correct"
}
else
{
$outfile = $PSCommandPath | Split-Path -Parent
$outfile += '\items.txt'
Clear-Host
Write-Output "Getting Items"
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$securePassword=ConvertTo-SecureString $Password -AsPlainText -Force
$Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $securePassword)
$Web = $Context.Web
$List = $Web.get_lists().getByTitle($ListName)
$itemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$Context.Load($ListItems)
$Context.ExecuteQuery()
$ListItems | ForEach-Object {
$output=$_["Title"] + "~~"
$output | Out-File -FilePath $outfile -Append
}
Write-Output "Done!"
}
Yes I confirm, it works, I had the same problem on a Windows 2012 R2 server
I want to create a GUI using PowerShell, that will allow users to select software to install. The software will be installed using unattended (silent) options, so the user doesn't have to do anything more that select the desired software, and click OK.
Since the installation is silent and there will be plenty of software to install, I want to give some feedback to the user, as to the status of the installation. So I put a textbox showing which software have been installed and which software is currently installing.
My problem is that all the text appears at the same time in the textbox and it also looks messy.
I want it to be like this:
installing 7-zip...OK
installing notepad ++...OK
installing visual studio code...OK
This is the script
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# software name
$software1 = "7-Zip"
$software2 = "Notepad++"
$software3 = "Visual Studio Code"
# installation status
$software1status = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where {$_.DisplayName -like "*$software1*"}
$software2status = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where {$_.DisplayName -like "*$software2*"}
$software3status = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where {$_.DisplayName -like "*$software3*"}
# set form size
$Form = New-Object System.Windows.Forms.Form
$Form.width = 500
$Form.height = 500
$Form.Text = 'Install Software'
# set font
$Font = New-Object System.Drawing.Font("Verdana",10)
$Form.Font = $Font
# results textbox
$ResultsTextBox = New-Object System.Windows.Forms.TextBox
$ResultsTextBox.Location = New-Object System.Drawing.Size(200,30)
$ResultsTextBox.Size = New-Object System.Drawing.Size(250,350)
$ResultsTextBox.Multiline = $true
$ResultsTextBox.Text = "make your selections on the left"
$Form.Controls.Add($ResultsTextBox)
# checkbox software1
$checkbox1 = new-object System.Windows.Forms.checkbox
$checkbox1.Location = new-object System.Drawing.Size(30,30)
$checkbox1.Size = new-object System.Drawing.Size(120,20)
$checkbox1.Text = "$software1"
if ($software1status -eq $null) {$checkbox1.Checked = $false} Else {$checkbox1.Checked = $true}
$Form.Controls.Add($checkbox1)
# checkbox software2
$checkbox2 = new-object System.Windows.Forms.checkbox
$checkbox2.Location = new-object System.Drawing.Size(30,50)
$checkbox2.Size = new-object System.Drawing.Size(120,20)
$checkbox2.Text = "$software2"
if ($software2status -eq $null) {$checkbox2.Checked = $false} Else {$checkbox2.Checked = $true}
$Form.Controls.Add($checkbox2)
# checkbox software3
$checkbox3 = new-object System.Windows.Forms.checkbox
$checkbox3.Location = new-object System.Drawing.Size(30,70)
$checkbox3.Size = new-object System.Drawing.Size(120,20)
$checkbox3.Text = "$software3"
if ($software3status -eq $null) {$checkbox3.Checked = $false} Else {$checkbox3.Checked = $true}
$Form.Controls.Add($checkbox3)
# ok button
$OKButton = new-object System.Windows.Forms.Button
$OKButton.Location = new-object System.Drawing.Size(130,400)
$OKButton.Size = new-object System.Drawing.Size(100,40)
$OKButton.Text = "OK"
$Form.Controls.Add($OKButton)
# close button
$CloseButton = new-object System.Windows.Forms.Button
$CloseButton.Location = new-object System.Drawing.Size(255,400)
$CloseButton.Size = new-object System.Drawing.Size(100,40)
$CloseButton.Text = "Close"
$CloseButton.Add_Click({$Form.Close()})
$Form.Controls.Add($CloseButton)
$OKButton.Add_Click{
if($checkbox1.Checked -and $software1status -eq $null) {Start-Process -FilePath $PSScriptRoot\software\7z1900-x64.msi /passive ; $ResultsTextBox.Text += "installing 7-zip"}
if($checkbox1.Checked -eq $false -and $software1status -ne $null ) {Start-Process MsiExec.exe "/x{23170F69-40C1-2702-1900-000001000000} /passive" ; $ResultsTextBox.Text += "removing 7-zip"}
if($checkbox2.Checked -and $software2status -eq $null) {Start-Process -FilePath $PSScriptRoot\software\npp.7.8.1.Installer.x64.exe /S ; $ResultsTextBox.Text += "installing notepad ++"}
if($checkbox2.Checked -eq $false -and $software2status -ne $null ) {Start-Process -FilePath "${env:ProgramFiles}\Notepad++\uninstall.exe" /S ; $ResultsTextBox.Text += "removing notepad ++"}
if($checkbox3.Checked -and $software3status -eq $null) {Start-Process -FilePath $PSScriptRoot\software\VSCodeSetup-x64-1.40.2.exe "/SILENT /NORESTART /MERGETASKS=!runcode" ; $ResultsTextBox.Text += "installing visual studio code"}
if($checkbox3.Checked -eq $false -and $software3status -ne $null ) {Start-Process -FilePath "${env:ProgramFiles}\Microsoft VS Code\unins000.exe" /SILENT ; $ResultsTextBox.Text += "removing visual studio code"}
}
# activate form
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
Use AppendText instead. you need to send carriage returns and new line characters also using that method:
$ResultsTextBox.AppendText("`r`nInstalling new file...")
However, you can only do things like this during an event like a button click. If you want to update more often you need to create events for that.
I've been trying to find a way to remotely, from a jumphost, verify that a patch has been installed. I am using a script I found on a Microsoft page but it shoots back an error. I've been trying to find a solution for days with no luck could any one please help me.---update
This is the error I get:
You cannot call a method on a null-valued expression.
At C:\Temp\HOTFIX.ps1:53 char:18
+ $Sheet.Cells.Item <<<< ($intRow,2) ="status"
+ CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Temp\HOTFIX.ps1:54 char:18
+ $Sheet.Cells.Item <<<< ($intRow,3) ="Patch status"
+ CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Temp\HOTFIX.ps1:55 char:18
+ $Sheet.Cells.Item <<<< ($intRow,4) ="OS"
+ CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Script:
#Check for a specific patch on remote PCs v1.2
# Tom Latham 04/02/2010
#
# Added v1.1: Error messaages
# Added v1.2: GUI Inputs
# Function to open file dialog box and select a file
Function Get-FileName($initialDirectory)
{
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "Text Files (*.txt)| *.txt" # Set the file types visible to dialog
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
# Function to prompt user for kb number
Function Get-Input
{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Enter KB Number"
$objForm.Size = New-Object System.Drawing.Size(300,200)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$objForm.Close()}})
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Please enter the KB number below (kbxxxxxx):"
$objForm.Controls.Add($objLabel)
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
$objTextBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($objTextBox)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
$x
}
# Main Program --------------------------------------
# Do not display errors
$erroractionpreference = "SilentlyContinue"
# Clear screen
clear-host
# Store user credentials
$cred = get-credential
# Supply text file of all PCs to be checked and KB number to search for
# Run Open File Dialog
$filename = Get-FileName -initialDirectory "c:"
# Get path of file to be used in storing results
$path = split-path $filename
# If kbresults.txt exists, delete it
if (test-path $path\kbresults.txt)
{ remove-item $path\kbresults.txt }
# Get kb number
$kb = Get-Input
# Extract content from filename object
$computernames = get-content $filename
# For each computer in list
foreach ($computer in $computernames)
{
# Set query string to query ping status
$strQuery = "select * from win32_pingstatus where address = '" + $computer + "'"
# Get WMI object using query
$wmi = gwmi -query $strquery
# If machine pings (status = 0)
if ($wmi.statuscode -eq 0)
{
# Get WMI object on computer where hotfixid equals our kb number
# Use stored user credentials
$checkkb = gwmi win32_QuickFixEngineering -computer $computer -credential $cred | where {$_.hotfixid -eq $kb} | select-object hotfixid, description
switch -regex ($Error[ 0 ].Exception)
{
"The RPC server is unavailable"
{
write-host -f blue $computer "`t" "RPC Unavailable on $computer" "`r"
"$computer `t RPC Unavailable." | out-file $path\kbresults.txt -append
continue
}
"Access denied"
{
write-host -f blue $computer "`t" "Access Denied" "`r"
"$computer `t Access Denied." | out-file $path\kbresults.txt -append
continue
}
"Access is denied"
{
write-host -f blue $computer "`t" "Access Denied" "`r"
"$computer `t Access Denied." | out-file $path\kbresults.txt -append
continue
}
# No error -> record our info!
$null
{
# If kb numbers match
if ($checkkb.hotfixid -eq $kb)
{
# Patch is installed. Test reboot status.
# Connect to remote registry hive (HKLM)
$regHive = [Microsoft.Win32.RegistryHive]"LocalMachine";
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$computer);
# Set subkey to 'UpdateExeVolatile', the existence of which show reboot pending status
$subKey = $regKey.OpenSubKey("SOFTWARE\Microsoft\Updates\UpdateExeVolatile");
# If subkey is not found
if (!$subKey)
{
# Patch is installed
write-host -f green $computer "`t" $checkkb.description "`r"
"$computer `t Installed." | out-file $path\kbresults.txt -append
}
else
{
# Patch installed. Reboot required.
write-host -f green $computer "`t" $checkkb.description "`r"
"$computer `t Reboot Required" | out-file $path\kbresults.txt -append
}
}
else
{
# Patch is not installed.
write-host -f red $computer "`t" "Not Found" "`r"
"$computer `t Not Installed." | out-file $path\kbresults.txt -append
}
}
}
$Error.clear()
}
else
{
# Machine doesn't ping. Write to screen and append to results file.
write-host $computer "`t" "Cannot ping." "`r"
"$computer `t Ping failed." | out-file $path\kbresults.txt -append
}
}
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")