我正在 powershell 中創建一個用于復制檔案的 gui。首先我添加一個帶有按鈕的檔案,接下來我選擇要復制的檔案夾,然后我要復制。不幸的是,腳本說檔案路徑為空。我怎么解決這個問題?此外,我想添加 2 個功能。
如果未標記復選框,則發出警告
選擇按鈕旁邊的文本欄位,我可以在其中看到要復制的檔案的路徑
$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()
uj5u.com熱心網友回復:
有很多改進建議,但讓我們專注于您的問題:
問題是您的$file 變數的范圍是函式 Get-Filename的本地。因此,當從函式外部訪問時,它始終為空。
如評論中所述,您的腳本作業的最小修改是更改以下行(為了清楚起見,我還建議最初在函式外部宣告它,在全域級別):
# From this
$file = Get-FileName -initialDirectory "c:"
# To this
$Global:file = Get-FileName -initialDirectory "c:"
要添加具有所選檔案名的文本框,請按照其他控制元件進行操作:
#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)
要更新文本,請在設定 $Global:file 變數后添加以下行:
$Global:file = Get-FileName -initialDirectory "c:"
$txtBox.Text = $Global:file
最后,如果您將以下代碼添加到$Button2.Add_Click代碼,則會顯示一條訊息:
#nothing checked
if(($checkBox.Checked -eq $false) -and ($checkBox.Checked -eq $false)) {
[System.Windows.Forms.Messagebox]::Show("No CheckBox checked")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/415811.html
標籤:
