Powershell脚本:已在对话框中显示预定义字段的用户输入

时间:2014-11-05 17:40:47

标签: powershell input field defined

我一直在编写一个脚本,将所有内容从我的下载文件夹移动到外部驱动器上的另一个文件夹(我们现在称之为#34;备份驱动器"),通过扩展将其分类到文件夹中(找到它在StackOverflow上进行初始启动 - Thanks to Nicola Cossu - )。每隔一段时间我就需要使用该脚本将其他驱动器中的内容提取到备份驱动器。

我想有一个脚本会询问我的源和目标驱动器,但希望它能够预定义我的下载文件夹和备份驱动器文件夹。

我认为可行的方法之一就是弹出一个对话框,让每个问题的位置都已填充,以便我只在需要时编辑它。我不确定如何做到这一点。

如果需要对变量$ MySRC和$ MyDST进行硬编码,那很好。 在此先感谢!!!

这是我的代码:

# Get Start Time of the Script
$startDTM = (Get-Date)

# Get Source and Destination -- this is where I am trying to get the predetermine variables to be
$source = Read-Host "Enter for Source"
$dest = Read-Host "Enter for Destination"

# This could be where my variables are located
# $MySRC = "C:\Users\ME\Downloads"
# $MyDST = "E:\Sorted Downloads"

# Logging information for personal reasons
echo ""
echo "This script is starting"
echo ""
echo "The source is " 
$source 
echo ""
echo "The destination is "
$dest
echo ""
echo ""

# Actual Script to Run
$file = gci -Recurse $source | ? {-not $_.psiscontainer} 
$file | group -property extension | 
        % {if(!(test-path(join-path $dest -child $_.name.replace('.','')))) { new-item -type directory $(join-path $dest -child $_.name.replace('.','')).toupper() }}
$file | % {  move-item $_.fullname -destination $(join-path $dest -child  $_.extension.replace(".",""))}

# End of Script Information -- Personal Reasons
echo "This Script is Done!"
echo 'Source: ' $source ' Destination: ' $dest
echo ""

# Get End Time:
$endDTM = (Get-Date)
# Echo Time Elapsed for the Script to Run:
"Elapsed Time: $(($endDTM-$startDTM).totalseconds) seconds"

1 个答案:

答案 0 :(得分:0)

这可以通过Windows窗体和简单的功能来完成。我保留了这个,以防我需要提示输入文件夹:

Function Get-FolderPath{
[CmdletBinding()]
Param(
    [String]$Description,
    [String]$InitialDirectory = "C:\",
    [Switch]$NewFolderButton = $false)

    [void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
    $FolderBrowserDialog = New-Object System.Windows.Forms.FolderBrowserDialog
    $FolderBrowserDialog.SelectedPath = $InitialDirectory
    $FolderBrowserDialog.Description = $Description
    $FolderBrowserDialog.ShowNewFolderButton = $NewFolderButton
    If($FolderBrowserDialog.ShowDialog() -eq "OK"){
        $FolderBrowserDialog.SelectedPath
    }
}

用法是这样的:

$MySRC = Get-FolderPath "Select source folder or drive:" "$env:USERPROFILE\Downloads"

这将弹出一个要求输入源文件夹的Windows文件夹选择对话框。还有一个开关,用于在对话框中显示“新建文件夹”按钮。它将被用作:

$MyDST = Get-FolderPath "Select the destination folder:" "E:\Sorted Downloads" -NewFolderButton

我建议在While循环中使用它来强制用户选择内容,或者如果$ MySRC或$ MyDST为空,则输入If以退出脚本。

While([string]::IsNullOrWhiteSpace($MySRC)){
    $MySRC = Get-FolderPath "Select source folder or drive:" "$env:USERPROFILE\Downloads"
}