本帖最后由 5i365 于 2022-2-28 20:19 编辑
回复 15# idwma
分享老外写的, 用PS对话框的形式来改HOST, 里面有控件的位置, 尺寸之类的, 感觉应该可以去掉, 应该可以精简, 以前看到过有类似的, 才几行代码就行!- Add-Type -AssemblyName System.Windows.Forms
- Add-Type -AssemblyName System.Drawing
-
- $hostsfilelocation = "$env:windir\System32\drivers\etc\hosts"
- $readhostsfile = Get-Content $hostsfilelocation
-
- $form = New-Object System.Windows.Forms.Form
- $form.Text = 'Update HOSTS File'
- $form.Size = New-Object System.Drawing.Size(300, 200)
- $form.StartPosition = 'CenterScreen'
-
- $AddHosts = New-Object System.Windows.Forms.Button
- $AddHosts.Location = New-Object System.Drawing.Point(55, 120)
- $AddHosts.Size = New-Object System.Drawing.Size(90, 25)
- $AddHosts.Text = 'Add Record'
- $AddHosts.DialogResult = [System.Windows.Forms.DialogResult]::OK
- $form.AcceptButton = $AddHosts
- $form.Controls.Add($AddHosts)
-
- $CancelButton = New-Object System.Windows.Forms.Button
- $CancelButton.Location = New-Object System.Drawing.Point(170, 120)
- $CancelButton.Size = New-Object System.Drawing.Size(75, 25)
- $CancelButton.Text = 'Cancel'
- $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
- $form.CancelButton = $CancelButton
- $form.Controls.Add($CancelButton)
-
- $Hostslabel = New-Object System.Windows.Forms.Label
- $Hostslabel.Location = New-Object System.Drawing.Point(10, 20)
- $Hostslabel.Size = New-Object System.Drawing.Size(280, 20)
- $Hostslabel.Text = 'Enter New HOSTNAME/FQDN:'
- $form.Controls.Add($Hostslabel)
-
- $HoststextBox = New-Object System.Windows.Forms.TextBox
- $HoststextBox.Location = New-Object System.Drawing.Point(10, 40)
- $HoststextBox.Size = New-Object System.Drawing.Size(260, 20)
- $form.Controls.Add($HoststextBox)
-
- $IPlabel = New-Object System.Windows.Forms.Label
- $IPlabel.Location = New-Object System.Drawing.Point(10, 60)
- $IPlabel.Size = New-Object System.Drawing.Size(280, 20)
- $IPlabel.Text = 'Enter IP:'
- $form.Controls.Add($IPlabel)
-
- $IPtextBox = New-Object System.Windows.Forms.TextBox
- $IPtextBox.Location = New-Object System.Drawing.Point(10, 80)
- $IPtextBox.Size = New-Object System.Drawing.Size(260, 20)
- $form.Controls.Add($IPtextBox)
-
- $form.Topmost = $true
-
- $form.Add_Shown({ ($HoststextBox, $IPtextbox).Select() })
-
- $result = $form.ShowDialog()
-
- if ($result -eq [System.Windows.Forms.DialogResult]::OK)
- {
- $inputhosts = $HoststextBox.Text
- $inputip = $IPtextBox.Text
- $newrecord = "$inputip $inputhosts"
- Add-Content -Path $hostsfilelocation -Value $newrecord
- }
复制代码
|