我正在 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")
}
0 评论