使用powershell和XAML,我希望用户选择所选文件夹,然后将其中一个子文件夹(例如subfolder1)中的内容复制到不同驱动器中的另一个目录(比如“C”驱动器) . 一切正常,除非我包含评论 . 代码说明:用户点击“选择”按钮,然后选择所需的文件夹 . 此文件夹路径显示在名为“sourcePath”的列表框中 . 接下来,用户在文本框中的“directoryName”中键入所需的名称(例如“folderA”) . 当用户按下“创建”按钮时,如果存在“folderA”,则将使用“Remove-Item C:\ $ var -Recurse -Force”删除它,并使用“Copy-Item -Path C:\”再次创建$ a“\ subfolder1 C:\ $ var -Recurse” . 最后,使用“Copy-Item -Path C:\”$ a“C:\ $ var -Recurse”,我希望将“subfolder1”内容复制到这个“folderA”上 .
$XAML = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Folder-Browser"
Height="500"
Width="600"
>
<Grid>
<Button Name="create" Content="create" HorizontalAlignment="Left"
Margin="158,175,0,0" VerticalAlignment="Top" Width="121" />
<TextBox Name="directoryName" HorizontalAlignment="Left" Height="23"
Margin="33,175,0,0" TextWrapping="Wrap" Text="directoryName"
VerticalAlignment="Top" Width="120"/>
<Button Name="choose" Content="choose" HorizontalAlignment="Left"
Margin="32,47,0,0" VerticalAlignment="Top" Width="121" />
<ListBox Name="sourcePath" HorizontalAlignment="left" Height="45"
Margin="32,87,0,0" VerticalAlignment="Top" Width="430"/>
<Button Name="copyItems" Content="copy-items" HorizontalAlignment="Left"
Margin="284,176,0,0" VerticalAlignment="Top" Width="121"
AutomationProperties.Name="copyItems" />
</Grid>
</Window>
'@
#Parse XAML
$Win = [Windows.Markup.XamlReader]::Parse($XAML)
# Define variables
$sourcePath = $Win.FindName("sourcePath")
$choose= $Win.FindName("choose")
$directoryName=$Win.FindName("directoryName")
$create=$Win.FindName("create")
$copyItems=$Win.FindName("copyItems")
#Event Handling
$choose.Add_Click({Select-FolderDialog})
# $a =$objForm.SelectedPath()
Add-Type -Assembly System.Windows.forms
$create.Add_Click({
$script:var = $directoryName.Text.ToString()
Remove-Item C:\$var -Recurse -Force
new-item c:\$var -itemType directory
# cannot achieve copy the contents from the "SelectedFolder\subfolder1" onto
# the new "directoryName" created.
# Copy-Item -Path C:\"$a"\subfolder1 C:\$var -Recurse
})
# Functions
# "Select-FolderDialog" is used for the "choose" button
function Select-FolderDialog
{
param([String]$Description="Select Folder",
[String]$RootFolder="Desktop")
$objForm = New-Object System.Windows.Forms.FolderBrowserDialog
$objForm.Rootfolder = $RootFolder
$objForm.Description = $Description
$Show = $objForm.ShowDialog()
if ($Show -eq "OK")
{
$SourcePath.Items.Add($objForm.SelectedPath)
}
}
$Win.ShowDialog()
1 回答
你有线的地方:
为了获得完整的文件夹路径,我将替换为:
请注意$ sourcePath.SelectedValue周围的额外$()它会强制PowerShell作为一个整体进行评估 . 此外,在PowerShell中,您可以将变量放在引号内 .