Scripting Games 2010. Advanced Event 10 (Moving Files from the Desktop to a Folder)

Десятое задание:

Event Scenario

The network team manager complained to the desktop team manager that user profiles are too large and are therefore killing network performance. An investigation has revealed that users are in the habit of downloading pictures, videos, and other large files from the Internet and storing them on their desktops. This habit has created user profiles that are in some cases over one GB in size.

Your manager has tasked you with writing a script that will move all files from the desktop to a folder such as c:\fso that is not part of the user’s profile. Shortcut files, of course, are not to be moved.

Design Points

·         Your script needs to run only on a local machine.
·         The user should be prompted with a message stating which files will be moved and where. The user must agree to the move by clicking Yes.
·         The destination folder should be configurable; if the folder does not exist, it should be created.
·         Extra design points will be awarded if a selectable file filter mask is implemented. For example, allow the user to select to move .mp3 and .doc files, but not .xls files.
·         Style points will be awarded for the presentation of a GUI to select the destination folder.
·         Style points will be awarded for the presentation of a progress bar or other visual progress indicator. 

 

  • На вход скрипту даются следующие данные: полное имя папки, в которую будут перемещаться файлы, расширения файлов, которые будут перемещаться и/или расширения файлов, которые перемещаться не будут.
  • Во время старта скрипт построит перечень всех расширений файлов, хранящихся на рабочем столе и поместит их в визуальный компонент CheckedListBox.
  • Затем, скрипт проверит  – какие параметры ему передали.
    • Если были переданы расширения файлов, которые подлежат перемещению (параметр Include), то расширения файлов, подлежащие исключению из процесса перемещения, учтены не будут. Скрипт установит radio button “What to do with selected files” в состояние “Include to move” и «взведет галку» напротив тех расширений файлов, которые ему были переданы в качестве параметра Include
    • Если расширения в параметре Include переданы не были, но были переданы в параметре Exclude, то скрипт установит radio-button rbtnExlude, а затем пометит взведенными checkbox’ами те расширения, которые ему были переданы в качестве параметра Exclude и должны быть исключены из процесса перемещения.

 Например, после запуска скрипта с параметрами -Include *.txt мы увидим такое окно:

 

При нажатии кнопки $btnCopy (я назвал ее так по ошибке (надо было бы назвать btnMove), а переименовывать уже было лень ;))

  • Скрипт проверит существование папки, заданной в качестве целевой и, в  случае отсутствия оной, выполнит попытку ее создания.
  • Если целевая папка существует (или была успешно создана), запустится процесс копирования перемещения

 А вот и сам скрипт:

param($Include,$Exclude, $DestFolder="d:\_tmp")
##############################################################################
#
#		Function Select Folder
#		This function show Select Folder box dialog
#
function Select-Folder($message='Select a folder', $path = 0,[int]$handle=0) {
    $object = New-Object -comObject Shell.Application

    $folder = $object.BrowseForFolder($handle, $message, 0, $path)
    if ($folder -ne $null) {
        $folder.self.Path
    }
}
###############################################################################
#
#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.8.0
# Generated On: 13.05.2010 10:46
# Generated By: Администратор
########################################################################

#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion

#region Generated Form Objects
$frmMain = New-Object System.Windows.Forms.Form
$btnExit = New-Object System.Windows.Forms.Button
$lblNowCopying = New-Object System.Windows.Forms.Label
$btnSelectFolder = New-Object System.Windows.Forms.Button
$txtboxDestfolder = New-Object System.Windows.Forms.TextBox
$btnCopy = New-Object System.Windows.Forms.Button
$grpbxWhatToDo = New-Object System.Windows.Forms.GroupBox
$rbtnExclude = New-Object System.Windows.Forms.RadioButton
$rbtnInclude = New-Object System.Windows.Forms.RadioButton
$prsbarCopy = New-Object System.Windows.Forms.ProgressBar
$clstbxExtensions = New-Object System.Windows.Forms.CheckedListBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$handler_frmMain_Load=
{
	#Set value for Destination Folder text box from input param
	$txtboxDestfolder.Text = $DestFolder
	#if param $Include is not empty then...
	if ($Include) {
		#...set radioButton for Include in checked state and...
		$rbtnInclude.Checked=$true
		#...add  to the list in the check list box all extensions...
		$Extensions | foreach {
			$clstbxExtensions.Items.Add("*$_")|Out-Null
			#and set extension as checked if it contains in the $Include param
			if ($Include -contains "*$_") {
				$clstbxExtensions.SetItemCheckState($clstbxExtensions.Items.Count-1,[System.Windows.Forms.CheckState]::Checked)
			}
		}
	}
	#If param $Include is empty then...
	else {
		#...set radioButton for Exclude in checked state and...
		$rbtnExclude.Checked=$true
		#...add  to the list in the check list box all extensions...
		$Extensions | foreach {
			$clstbxExtensions.Items.Add("*$_")|Out-Null
			#and set extension as checked if it contains in the $Exclude param
			if ($Exclude -contains "*$_") {
				$clstbxExtensions.SetItemCheckState($clstbxExtensions.Items.Count-1,[System.Windows.Forms.CheckState]::Checked)
			}
		}
	}
}

$handler_clstbxExtensions_ItemCheck=
{
#TODO: Place custom script here

}

$handler_rbtnInclude_CheckedChanged=
{
#TODO: Place custom script here

}

$handler_btnExit_Click=
{
#TODO: Place custom script here
	$frmMain.Close()
}
########################################################################################################################
$handler_btnCopy_Click=
{
#if path to destination folder is not empty...
if ($txtboxDestfolder.Text) {
	#...and destination folder does not exist...
	if (!(Test-Path $txtboxDestfolder.Text)) {
		#try to create destination folder
		New-Item -Path $txtboxDestfolder.Text -type directory -ErrorAction SilentlyContinue
	}
	#if destination folder created successfuly...
	if ($?) {
		#Disable this button
		$btnCopy.Enabled=$false
		#Prepare to move
		#create include|exclude extensions list
		#start values ($Exclude have to always contains *.lnk)
		$Exclude=@("*.lnk")
		$Include=@()
		#set new value of destination folder
		$DestFolder=$txtboxDestfolder.Text
		#
		If ($rbtnExclude.Checked) {
			#add extensions to exclude list from check list box
			$Exclude+=$clstbxExtensions.CheckedItems
			Write-Verbose "Exclude items = $Exclude"
		}
		else {
			#add extensions to include list from check list box
			$Include+=$clstbxExtensions.CheckedItems
			Write-Verbose "$Include items = $Include"
		}
		#Get full names and names of files except *.lnk
		$FilesToMove=@(dir $DesktopDirectory -recurse -force -Include $Include -Exclude $Exclude|?{!$_.PSIsContainer}|select FullName,Name)
		$NumFilesToMove=$FilesToMove.count
		#Show question befor moving files
		$Msg="Do you want to move $NumFilesToMove file(s) to folder $DestFolder"
		$Answer=[Windows.Forms.MessageBox]::Show($Msg,"Question",[Windows.Forms.MessageBoxButtons]::YesNo,[Windows.Forms.MessageBoxIcon]::Question)
		if ($Answer -eq [Windows.Forms.DialogResult]::Yes) {
			Write-Verbose "Number of files to be moved - $NumFilesToMove"
			#What to delete from full name to get relative path
			$Del=[regex]::Escape($DesktopDirectory)
			#set maximum for progressbar
			$prsbarCopy.Maximum = $NumFilesToMove
			#moving files
			for($i=1;$i -le $NumFilesToMove; $i++) {
				#set progress bar value
				$prsbarCopy.Value=$i
				#corent file in array $NumFilesToMove
				$File=$FilesToMove[$i-1]
				#Get relative path of file from full file name
				$RelPath=$File.FullName -replace "^$Del" -replace "\\[^\\]+$"
				#if destination  doesn't exists...
				if (!(Test-Path "$DestFolder$RelPath")) {
					#...make this destination folder
					New-Item -Path "$DestFolder$RelPath" -type directory -ErrorAction SilentlyContinue | Out-Null
				}
				#remove -Whatif befor use in production
				move -Path $File.FullName -Destination "$DestFolder$RelPath\$($File.Name)" -WhatIf
			}
		}
		$btnCopy.Enabled=$true
	}
	else {
		#Show error message "Error creating destination folder"
		$Msg="Error creating destination folder $($txtboxDestfolder.Text)"
		[Windows.Forms.MessageBox]::Show($Msg,"Error",[Windows.Forms.MessageBoxButtons]::OK,[Windows.Forms.MessageBoxIcon]::Error)

	}
}
else {
	#Show warning message "Value for destination folder does not set"
	$Msg="Value for destination folder does not set"
	[Windows.Forms.MessageBox]::Show($Msg,"Warning",[Windows.Forms.MessageBoxButtons]::OK,[Windows.Forms.MessageBoxIcon]::Warning)
}
}
#########################################################################################################################
$handler_btnSelectFolder_Click=
{
#
	$DestFolder = Select-Folder #-path $txtboxDestfolder.Text
	#if not Cancel button has been clicked...
	if ($DestFolder) {
		#...set new folder path value
		$txtboxDestfolder.Text = $DestFolder
	}

}

$handler_rbtnExclude_CheckedChanged=
{
#TODO: Place custom script here

}

$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
	$frmMain.WindowState = $InitialFormWindowState
}

#----------------------------------------------
#region Generated Form Code
$frmMain.Text = "Copy Files from Desktop"
$frmMain.Name = "frmMain"
$frmMain.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 742
$System_Drawing_Size.Height = 442
$frmMain.ClientSize = $System_Drawing_Size
$frmMain.add_Load($handler_frmMain_Load)

$btnExit.TabIndex = 7
$btnExit.Name = "btnExit"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 168
$btnExit.Size = $System_Drawing_Size
$btnExit.UseVisualStyleBackColor = $True

$btnExit.Text = "Exit"

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 606
$System_Drawing_Point.Y = 141
$btnExit.Location = $System_Drawing_Point
$btnExit.DataBindings.DefaultDataSourceUpdateMode = 0
$btnExit.add_Click($handler_btnExit_Click)

$frmMain.Controls.Add($btnExit)

$lblNowCopying.TabIndex = 6
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 443
$System_Drawing_Size.Height = 23
$lblNowCopying.Size = $System_Drawing_Size
$lblNowCopying.Text = "Now moving"

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 258
$System_Drawing_Point.Y = 370
$lblNowCopying.Location = $System_Drawing_Point
$lblNowCopying.DataBindings.DefaultDataSourceUpdateMode = 0
$lblNowCopying.Name = "lblNowCopying"

$frmMain.Controls.Add($lblNowCopying)

$btnSelectFolder.TabIndex = 5
$btnSelectFolder.Name = "btnSelectFolder"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$btnSelectFolder.Size = $System_Drawing_Size
$btnSelectFolder.UseVisualStyleBackColor = $True

$btnSelectFolder.Text = "SelectFolder"

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 626
$System_Drawing_Point.Y = 27
$btnSelectFolder.Location = $System_Drawing_Point
$btnSelectFolder.DataBindings.DefaultDataSourceUpdateMode = 0
$btnSelectFolder.add_Click($handler_btnSelectFolder_Click)

$frmMain.Controls.Add($btnSelectFolder)

$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 362
$System_Drawing_Size.Height = 20
$txtboxDestfolder.Size = $System_Drawing_Size
$txtboxDestfolder.DataBindings.DefaultDataSourceUpdateMode = 0
$txtboxDestfolder.Name = "txtboxDestfolder"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 258
$System_Drawing_Point.Y = 27
$txtboxDestfolder.Location = $System_Drawing_Point
$txtboxDestfolder.TabIndex = 4

$frmMain.Controls.Add($txtboxDestfolder)

$btnCopy.TabIndex = 3
$btnCopy.Name = "btnCopy"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 315
$System_Drawing_Size.Height = 168
$btnCopy.Size = $System_Drawing_Size
$btnCopy.UseVisualStyleBackColor = $True

$btnCopy.Text = "Press to move"

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 258
$System_Drawing_Point.Y = 141
$btnCopy.Location = $System_Drawing_Point
$btnCopy.DataBindings.DefaultDataSourceUpdateMode = 0
$btnCopy.add_Click($handler_btnCopy_Click)

$frmMain.Controls.Add($btnCopy)

$grpbxWhatToDo.Name = "grpbxWhatToDo"

$grpbxWhatToDo.Text = "What to do with selected extensions"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 100
$grpbxWhatToDo.Size = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 12
$System_Drawing_Point.Y = 27
$grpbxWhatToDo.Location = $System_Drawing_Point
$grpbxWhatToDo.TabStop = $False
$grpbxWhatToDo.TabIndex = 2
$grpbxWhatToDo.DataBindings.DefaultDataSourceUpdateMode = 0

$frmMain.Controls.Add($grpbxWhatToDo)
$rbtnExclude.TabIndex = 1
$rbtnExclude.Name = "rbtnExclude"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 158
$System_Drawing_Size.Height = 24
$rbtnExclude.Size = $System_Drawing_Size
$rbtnExclude.UseVisualStyleBackColor = $True

$rbtnExclude.Text = "Exclude from move"

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 20
$System_Drawing_Point.Y = 59
$rbtnExclude.Location = $System_Drawing_Point
$rbtnExclude.DataBindings.DefaultDataSourceUpdateMode = 0
$rbtnExclude.TabStop = $True
$rbtnExclude.add_CheckedChanged($handler_rbtnExclude_CheckedChanged)

$grpbxWhatToDo.Controls.Add($rbtnExclude)

$rbtnInclude.TabIndex = 0
$rbtnInclude.Name = "rbtnInclude"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 158
$System_Drawing_Size.Height = 24
$rbtnInclude.Size = $System_Drawing_Size
$rbtnInclude.UseVisualStyleBackColor = $True

$rbtnInclude.Text = "Include to move"

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 20
$System_Drawing_Point.Y = 19
$rbtnInclude.Location = $System_Drawing_Point
$rbtnInclude.DataBindings.DefaultDataSourceUpdateMode = 0
$rbtnInclude.TabStop = $True
$rbtnInclude.add_CheckedChanged($handler_rbtnInclude_CheckedChanged)

$grpbxWhatToDo.Controls.Add($rbtnInclude)


$prsbarCopy.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 443
$System_Drawing_Size.Height = 23
$prsbarCopy.Size = $System_Drawing_Size
$prsbarCopy.TabIndex = 1
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 258
$System_Drawing_Point.Y = 407
$prsbarCopy.Location = $System_Drawing_Point
$prsbarCopy.Name = "prsbarCopy"

$frmMain.Controls.Add($prsbarCopy)

$clstbxExtensions.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 289
$clstbxExtensions.Size = $System_Drawing_Size
$clstbxExtensions.DataBindings.DefaultDataSourceUpdateMode = 0
$clstbxExtensions.Name = "clstbxExtensions"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 12
$System_Drawing_Point.Y = 141
$clstbxExtensions.Location = $System_Drawing_Point
$clstbxExtensions.TabIndex = 0
$clstbxExtensions.add_ItemCheck($handler_clstbxExtensions_ItemCheck)

$frmMain.Controls.Add($clstbxExtensions)



#endregion Generated Form Code

#Save the initial state of the form
$InitialFormWindowState = $frmMain.WindowState
#Init the OnLoad event to correct the initial state of the form
$frmMain.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$frmMain.ShowDialog()| Out-Null

} #End Function
#===========================    Script Entry point ================================
cls
$VerbosePreference="Continue"
#Get path to the current user desktop
$DesktopDirectory=[System.Environment]::GetFolderPath('DesktopDirectory')
#
#Make shure that variables $Include and $Exclude are arrays...
$Include=@($Include)
#...and Exclude always contain "*.lnk"
$Exclude=@($Exclude)+"*.lnk"
#
#Get full names, name and extensions of files except *.lnk
$DesktopFiles=dir $DesktopDirectory -recurse -force -Exclude "*.lnk"|?{!$_.PSIsContainer}|select FullName,Name,Extension
#
#Get extentions list of existent desktop files
$Extensions=$DesktopFiles| select -ExpandProperty Extension -Unique
#
#Show form
GenerateForm

Leave a Reply

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.