如何从打开的文件对话框控件保存选定的路径

时间:2018-04-25 07:07:41

标签: powershell

正如您在我的代码中看到的,在执行它之后,我可以从打开的对话框中选择备份目录,并为备份选择目标文件夹。我的目的是将脚本放入组策略编辑器中,因此脚本将在每次关闭后执行。问题是每次重新运行脚本时都会打开openfolder对话框。我现在如何保存我选择的备份文件夹和目标路径,以便在重新运行脚本后不再设置它们?

这是代码

function Find-Folders {
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Windows.Forms.Application]::EnableVisualStyles()

Add-Type -AssemblyName System.Windows.Forms
$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
    SelectedPath = 'C:\Program Files\Planmeca\Romexis\client\cephmodule\analyses'
}
[void]$FolderBrowser.ShowDialog()
$FolderBrowser.SelectedPath 


$browse = New-Object System.Windows.Forms.FolderBrowserDialog
$browse.SelectedPath = "C:\"
$browse.ShowNewFolderButton = $true
$browse.Description = "Speicherort fuer Backup waehlen"

$loop = $true
while($loop)
{
    if ($browse.ShowDialog() -eq "OK")
    {
    $loop = $false



$Destination= $browse.SelectedPath #KOPIERE DIE DATEN --> ZIELPFAD
$Versions="3" #WIEVIEL BACKUPS SOLLEN BEHALTEN WERDEN
$BackupDirs= $FolderBrowser.SelectedPath #WELCHER ORDNER SOLL GESICHERT WERDEN
$Log="Log.txt" #Log Name
$LoggingLevel="1" #LoggingLevel only for Output in Powershell Window, 1=smart, 3=Heavy


#STOP-AB HIER KEINE AENDERUNGEN DURCHFUEHREN
#STOP-AB HIER KEINE AENDERUNGEN DURCHFUEHREN
#Settings - AB HIER KEINE AENDERUNGEN DURCHFUEHREN
$Backupdir=$Destination +"\Backup-"+ (Get-Date -format yyyy-MM-dd)+"-"+(Get-Random -Maximum 100000)+"\"
$Items=0
$Count=0
$ErrorCount=0
$StartDate=Get-Date #-format dd.MM.yyyy-HH:mm:ss

#FUNCTION
#Logging
Function Logging ($State, $Message) {
$Datum=Get-Date -format dd.MM.yyyy-HH:mm:ss

if (!(Test-Path -Path $Log)) {
    New-Item -Path $Log -ItemType File | Out-Null
}
$Text="$Datum - $State"+":"+" $Message"

if ($LoggingLevel -eq "1" -and $Message -notmatch "was copied") {Write-Host $Text}
elseif ($LoggingLevel -eq "3" -and $Message -match "was copied") {Write-Host $Text}

add-Content -Path $Log -Value $Text
}
Logging "INFO" "----------------------"
Logging "INFO" "Start the Script"

#Create Backupdir
Function Create-Backupdir {
Logging "INFO" "Create Backupdir $Backupdir"
New-Item -Path $Backupdir -ItemType Directory | Out-Null

Logging "INFO" "Move Log file to $Backupdir"
Move-Item -Path $Log -Destination $Backupdir

Set-Location $Backupdir
Logging "INFO" "Continue with Log File at $Backupdir"
}

#Loeschen von Backupdir
Function Delete-Backupdir {
$Folder=Get-ChildItem $Destination | where {$_.Attributes -eq "Directory"} | Sort-Object -Property $_.LastWriteTime -Descending:$false | Select-Object -First 1

Logging "INFO" "Remove Dir: $Folder"

$Folder.FullName | Remove-Item -Recurse -Force 
}

#Pruefe ob der Backupordner und der Zielpfad erreichbar bzw. verfügbar ist
function Check-Dir {
Logging "INFO" "Check if BackupDir and Destination exists"
if (!(Test-Path $BackupDirs)) {
    return $false
    Logging "Error" "$BackupDirs does not exist"
}
if (!(Test-Path $Destination)) {
    return $false
    Logging "Error" "$Destination does not exist"
  }
}

#Daten speichern
Function Make-Backup {
Logging "INFO" "Started the Backup"
$Files=@()
$SumMB=1
$SumItems=0
$SumCount=0
$colItems=0
Logging "INFO" "Count all files and create the Top Level Directories"

foreach ($Backup in $BackupDirs) {
    $colItems = (Get-ChildItem $Backup -recurse | Where-Object {$_.mode -notmatch "h"} | Measure-Object -property length -sum) 
    $Items=0
    $FilesCount = @()
    $FilesCount += Get-ChildItem $Backup -Recurse | Where-Object {$_.mode -notmatch "h"}  
    Copy-Item -Path $Backup -Destination $Backupdir -Force -ErrorAction SilentlyContinue
    $SumMB+=$colItems.Sum.ToString()
    $SumItems+=$colItems.Count
}

$TotalMB="{0:N2}" -f ($SumMB / 1MB) + " MB of Files"
Logging "INFO" "There are $SumItems Files with  $TotalMB to copy"

foreach ($Backup in $BackupDirs) {
    $Index=$Backup.LastIndexOf("\")
    $SplitBackup=$Backup.substring(0,$Index)
    $Files = Get-ChildItem $Backup -Recurse | Where-Object {$_.mode -notmatch "h"} 
    foreach ($File in $Files) {
        $restpath = $file.fullname.replace($SplitBackup,"")
        try {
            Copy-Item  $file.fullname $($Backupdir+$restpath) -Force -ErrorAction SilentlyContinue |Out-Null
            Logging "INFO" "$file was copied"
        }
        catch {
            $ErrorCount++
            Logging "ERROR" "$file returned an error an was not copied"
        }
        $Items += (Get-item $file.fullname).Length
        $status = "Copy file {0} of {1} and copied {3} MB of {4} MB: {2}" -f $count,$SumItems,$file.Name,("{0:N2}" -f ($Items / 1MB)).ToString(),("{0:N2}" -f ($SumMB / 1MB)).ToString()
        $Index=[array]::IndexOf($BackupDirs,$Backup)+1
        $Text="Copy data Location {0} of {1}" -f $Index ,$BackupDirs.Count
        Write-Progress -Activity $Text $status -PercentComplete ($Items / $SumMB * 100)  
        if ($File.Attributes -ne "Directory") {$count++}
    }
}
$SumCount+=$Count
$SumTotalMB="{0:N2}" -f ($Items / 1MB) + " MB of Files"
Logging "INFO" "----------------------"
Logging "INFO" "Copied $SumCount files with $SumTotalMB"
Logging "INFO" "$ErrorCount Files could not be copied"
 }


$Count=(Get-ChildItem $Destination | where {$_.Attributes -eq "Directory"}).count
Logging "INFO" "Check if there are more than $Versions Directories in the Backupdir"

if ($count -lt $Versions) {

Create-Backupdir

} else {

Delete-Backupdir

Create-Backupdir
}


$CheckDir=Check-Dir

if ($CheckDir -eq $false) {
Logging "ERROR" "Mindenstens ein Ordner ist nicht verfuegbar, bzw. existiert nicht. Script beendet"
} else {
Make-Backup

$Enddate=Get-Date #-format dd.MM.yyyy-HH:mm:ss
$span = $EndDate - $StartDate
$Minutes=$span.Minutes
$Seconds=$Span.Seconds

Logging "INFO" "Backupduration $Minutes Minutes and $Seconds Seconds"
Logging "INFO" "----------------------"
Logging "INFO" "----------------------" 
}

Write-Host "Druecken Sie eine beliebige Taste um dieses Fenster sofort zu schliessen ..."
#$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

} else
    {
        $res = [System.Windows.Forms.MessageBox]::Show("Du hast auf Abbrechen gedrueckt. Willst du es nochmal versuchen oder das Skript beenden? ", "Speicherort fuer Backup waehlen", [System.Windows.Forms.MessageBoxButtons]::RetryCancel)
        if($res -eq "Cancel")
        {
            #Ends script
            return
        }
    }
}
$browse.SelectedPath
$browse.Dispose()
} Find-Folders

0 个答案:

没有答案