Powershell GUI如何使用选定的文件夹并将其项目复制到另一个驱动器中的其他文件夹中

时间:2017-03-06 22:02:12

标签: c# wpf xaml powershell

使用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",我想要"子文件夹1"要复制到此"文件夹A"。

的内容
$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 个答案:

答案 0 :(得分:0)

你有这条线:

Copy-Item -Path C:\"$a"\subfolder1 C:\$var -Recurse

为了获得完整的文件夹路径,我将替换为:

Copy-Item -Path "$($sourcePath.SelectedValue)\subfolder1" C:\$var -Recurse

注意$ sourcePath.SelectedValue周围的额外$()它会强制PowerShell作为一个整体进行评估。 此外,在PowerShell中,您可以将变量放在引号内。