具有脚本Powershell的自我删除文件夹 [英] Self Delete Folder with scripts powershell

查看:83
本文介绍了具有脚本Powershell的自我删除文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完成后,我一直试图让Powershell或批处理脚本删除包含我所有脚本的文件夹.最初,我尝试使用 Remove-Item -Path"C:\ Tool" -Recurse -Force ,如果在 C:\ Tool 以外的位置作为脚本运行,则没有任何问题.当从其中的脚本运行时,它将抱怨文件正在使用中.经过一番研究,我发现& cmd.exe/c rd/s/q"C:\ Tool" 效果更好,但是即使我关闭了GUI,该命令也不会删除正在使用img文件/文件夹.

I have been trying to have powershell or batch scripts delete a folder that contains all my scripts when I am finished. Originally I tried Remove-Item -Path "C:\Tool" -Recurse -Force which worked no problem if run as a script for a location outside of C:\Tool. It would complain the files were in use when run from a script within. After some research I found &cmd.exe /c rd /s /q "C:\Tool" which worked much better, but even though I closed the GUI, the command wouldn't delete the img files/folders in use.

从USB驱动器启动时,上述两个命令都能完美运行.

Both the above commands run perfectly when initiated from a USB drive.

以前,我在temp文件夹中创建了第二个脚本,该脚本将删除所有文件,然后删除其自身.我正在寻找一种新的方法来简化我正在研究的新设计.我希望脚本可以从 C:\ Tool 或USB驱动器中运行.

Previously I created a second script in the temp folder which would delete all the files and then itself. I am looking for a new way to do this to streamline the new design I'm working on. I want the script to work from either within C:\Tool or from a USB drive.

控制流程如下:
1)脚本加载所有功能
2)显示GUI(包含img)
3)按下按钮
4)GUI已关闭
5)包含脚本的文件夹被删除

The control flow is such:
1)Script loads all functions
2)GUI is displayed (which contains imgs)
3)Button is pressed
4)GUI is closed
5)Folder containing script is deleted

步骤5是我的问题,如前所述.尝试执行的命令和命令的变体都不会删除所有文件.

Step 5 is my issue as already explained. Not all files are removed by either attempted commands and variations of commands.

我希望第5步能够正常工作,无论是否从GUI上的按钮调用了命令,它都作为脚本的一部分自动运行,还是在USB等其他位置的脚本调用它来删除文件夹 C:\ Tool

I want step 5 to work regardless is command is called from a button on the GUI, it autoruns as a part of the script, or a script in another location such as a USB calls it to delete the folder C:\Tool

推荐答案

我们不知道GUI的显示方式的具体细节,但是,假设您使用的是在 PowerShell 代码,您的问题可能是您的GUI构造代码如何从以后要删除的文件夹中的文件中加载图像.

We don't know the specifics of how your GUI is displayed, but, assuming you're using a WinForms GUI constructed in PowerShell code, your problem may be how your GUI construction code loads images from files in the folder that you later want to delete.

值得注意的是,如果您使用类似以下内容的话:

Notably, if you use something like:

[Bitmap]::new(<file-path>)
[System.Drawing.Image]::FromFile(<file-path>)

指定的文件显然会在PowerShell会话的其余部分保持打开状态,并且您将无法删除该文件夹.

the specified file apparently stays open for the remainder of the PowerShell session, and you won't be able to delete your folder.

解决方案是在内存中创建一个 new 图像实例,以复制从文件中加载的图像,然后处置 ,它释放了对底层文件的锁定,如此[C#]答案.

The solution is to create a new image instance in memory that copies the loaded-from-file image, and to then dispose of the loaded-from-file image, which releases the lock on the underlying file, as demonstrated in this [C#] answer.

这是一个最小的脚本 demo.ps1 ,它演示了该方法:

Here's a minimal script, demo.ps1, that demonstrates the approach:

  • 将其保存到自己的临时临时存放文件夹中.

  • Save it to its own, temporary, throw-away folder.

将名为 demo.png 的小图像文件复制到同一文件夹中.

Copy a small image file named demo.png into the same folder.

然后以< temp-folder>/demo -SelfDestruct 调用它以查看其运行情况;需要指定
-SelfDescript 是一种预防措施,因为意外调用会清除脚本所在的整个文件夹.

Then invoke it as <temp-folder>/demo -SelfDestruct to see it in action; the need to specify
-SelfDescript is a precaution, given that accidental invocation would wipe out the entire folder in which the script lives.

param([switch] $SelfDestruct)

# Load the WinForms assembly.
Add-Type -AssemblyName System.Windows.Forms    

# Create the form.
$form = New-Object system.Windows.Forms.Form -Property @{
    ClientSize = New-Object System.Drawing.Point 400,100
    Text       = "Dialog"
}    

# Add a PictureBox control that loads its image from 'demo.png'
$form.Controls.Add((New-Object System.Windows.Forms.PictureBox  -Property @{
Image = & { 
    # Load the image from file in the same folder as a script into
    # a temporary variable.
    $tmpImg = [System.Drawing.Image]::FromFile((Join-Path $PSScriptRoot 'demo.png')) 
    # Create an in-memory copy of the image. 
    New-Object System.Drawing.Bitmap $tmpImg
    # Dispose of the from-file image, which releases the file.
    $tmpImg.Dispose()
}
Location = New-Object System.Drawing.Point 10, 10
}))


# Show the form and wait for the use to close it.
$null = $form.ShowDialog()

if ($SelfDestruct) { # Remove the running script's entire folder.
  if ("$($PWD.Path)\" -like "$PSScriptRoot\*") {                                                      #"
      Push-Location C:\ # must switch to different dir. before deleting.
  }
  # Remove the entire folder.
  Remove-Item -literalpath $PSScriptRoot -Recurse -Force
  exit
}


这是一个变体,它通过事件处理程序通过按钮点击触发删除:


Here's a variant that triggers the removal by button click, via an event handler:

param([switch] $SelfDestruct)

Add-Type -AssemblyName System.Windows.Forms

function remove-OwnFolder {
    # If the current dir. is in the subtree of the folder to delete, 
    # we must switch to different dir. before deleting.
    if ("$($PWD.Path)\" -like "$PSScriptRoot\*") {                                                      #"
        Push-Location C:\ 
    }
    # Remove the script's parent folder as a whole.
    Remove-Item -literalpath $PSScriptRoot -Recurse -Force
}

# Create the form.
$form = New-Object system.Windows.Forms.Form -Property @{
    ClientSize = New-Object System.Drawing.Point 400,100
    Text       = "Dialog"
}    

# Add a PictureBox control that loads its image from 'demo.png'
$form.Controls.Add((New-Object System.Windows.Forms.PictureBox  -Property @{
    Image = & { 
        # Load the image from file in the same folder as a script into
        # a temporary variable.
        $tmpImg = [System.Drawing.Image]::FromFile((Join-Path $PSScriptRoot 'demo.png')) 
        # Create an in-memory copy of the image. 
        New-Object System.Drawing.Bitmap $tmpImg
        # Dispose of the from-file image, which releases the file.
        $tmpImg.Dispose()
    }
    Location = New-Object System.Drawing.Point 10, 10
}))


# Add a button that will trigger the self-destruction
$btnSelfDestruct = New-Object system.Windows.Forms.Button -Property @{
    Text              = "Submit"
    Location          = New-Object System.Drawing.Point 160, 60
}
$form.Controls.Add($btnSelfDestruct)

# Add the button-click event handler.
$btnSelfDestruct.Add_Click({
    $form.Close()
    if ($SelfDestruct) {
        remove-OwnFolder
    }
    exit
})

# Show the form and wait for the use to close it.
$null = $form.ShowDialog()

这篇关于具有脚本Powershell的自我删除文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆