使用PowerShell和XAML,我希望用户选择选定的文件夹,然后将内容从其一个子文件夹(例如subfolder1)中复制到不同驱动器中的另一个目录(说"说")C盘)。一切都起作用,除了我包括评论。代码的描述:用户单击"选择"按钮,然后选择所需的文件夹。此文件夹路径显示在名为" sourcePath"的列表框中。接下来,在文本框中的"目录名称"(例如" 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 "SelectedFoldersubfolder1" 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()
您拥有该行:
Copy-Item -Path C:"$a"subfolder1 C:$var -Recurse
为了获得完整的文件夹路径,我将替换为:
Copy-Item -Path "$($sourcePath.SelectedValue)subfolder1" C:$var -Recurse
请注意围绕$ sourcePath周围的额外$()。SelectedValueit迫使PowerShell整体评估它。另外,在PowerShell中,您可以将变量放在引号中。