Delete children directories in powershell including symlinks - windows

Currently experiencing issue, I'm currently doing this:
Get-ChildItem $PATH -Recurse -ErrorAction SilentlyContinue |
Where-Object {($_.Attributes -notmatch '\"Directory\"') -and
($_.LastWriteTime -lt (Get-Date).AddHours(-12))}|
Remove-Item -Force -Recurse
Now, it would delete fine IF I didn't have symlinks, but I do. I am getting this error:
Remove-Item : There is a mismatch between the tag specified in the request and the tag present in the reparse point
At line:1 char:184
+ ... ($_.LastWriteTime -lt (Get-Date).AddHours(-12))}| Remove-Item -Force
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Remove-Item], Win32Exception
+ FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.RemoveItemCommand
I'm unable to upgrade powershell to v6. It seems to be related to:https://github.com/powershell/powershell/issues/621#issuecomment-289230180
Anyone have a workaround?

Tested today on PowerShell 7 and unfortunately the issue is still there: PowerShell cannot delete symlink.
I had to delete the directory through an elevated prompt typing cmd /c rmdir /s /q C:\Users\Your_User_Name\Your_Folder_Name

This problem seems to be fixed in PS 6 (ref: https://github.com/powershell/powershell/issues/621)
In PS 5.1 one can work around it by using:
$(get-item $theSymlinkDir).Delete()
or as LotPings noted in the comments to the Q for this specific Foreach-Object loop:
|? LinkType -eq 'SymbolicLink'| % { $_.Delete() }

Related

How to use Remove-Item -Confirm:$false -Force properly in Windows PowerShell

So, I am writing this script in PowerShell and I am required to delete a few files in APPDATA on Windows. I wrote this line of code and it doesn't remove the item silently. It asks for confirmation even after using $Confirm:false. How do I fix this issue?
My code:
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\blob_storage" | Remove-Item -Confirm:$false -Force
I get this unwanted confirmation box every time I run the script:
Here is your modified code. I hope it will work for you.
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\blob_storage" | Remove-Item -Recurse -Force

How kill a process using powershell without getting errors when the process does not exist

I want to kill the nodepad process if it exists. If I use this:
PS C:\> get-process -name notepad | Stop-Process -Force
I will get an error when the process does not exist.
get-process : Cannot find a process with the name "notepad". Verify the process name and call the cmdlet again.
At line:1 char:1
+ get-process -name notepad | Stop-Process -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (notepad:String) [Get-Process], ProcessCommandException
+ FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand
I feel it should be silent, as it is not an error, the object should be null.
I know I could do:
PS C:\> get-process | where { $_.processname -eq 'notepad' } | Stop-Process -Force
but I prefer a simple way if it exists. Thanks.
PS: I need to kill the notepad because when I non-interactively install ClamAV, it create the notepad with a user manual. I could not find a way to tell ClamAV not to open the user manual.
Just add -ErrorAction SilentlyContinue. This one is simpler and does not prompt any erros if process does not exist.
Get-Process -Name notepad -ErrorAction SilentlyContinue | Stop-Process -Force
I suggest checking if the notepad process is the one you want first before just force-ending all notepad processes on the system:
Try {
(Get-WmiObject win32_process -Filter "name='notepad.exe'" |
Where commandline -like '*\path\to\manual.txt'
).Terminate()
}
# Handle "can't call method on null" error:
Catch [System.SystemException] { "Manual.txt process not found, skipping..." }
or ...
Stop-Process -Name "chrome" -Force -ErrorAction SilentlyContinue
And if you are using this with Gitlab beware that it has a bug with PowerShell runner, that you can work around by encapsulation inside parenthesis resulting in:
(Stop-Process -Name "chrome" -Force -ErrorAction SilentlyContinue)
source:
Gitlab powershell issue breaking on ErrorAction

Azure devops powershell task issue

Could someone help me with how to zip multiple files using powershell task? I am using a windows vm ..hence couldn't use zip command.
I have multiple files which need to be zipped to a particular folder with different name.
I tried to do as below, but I'm getting an error on the second line.
Error:
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
##[error]PowerShell exited with code '1'.
Finishing: PowerShell Script
pipeline:
Compress-Archive -Path 'FR1PHPPRDAPP1V\*' -DestinationPath 'Output\APP1V.zip'
Compress-Archive -Path 'FR1PHPPRDAPP4V\*' -DestinationPath 'Output\APP4V.zip'
Compress-Archive -Path 'FR1PHPPRDAPP5V\*' -DestinationPath 'Output\APP5V.zip
Compress-Archive -Path 'FR1PHPPRDSRE1V\*' -DestinationPath 'Output\SRE1V.zip
Compress-Archive -Path 'FR1PHPPRDAPP7V\*' -DestinationPath 'Output\APP7V.zip
It worked..I just had to add a semicolon in between the lines.

In a dockerfile, how to delete a directory and its contents from docker image? (windows)

I'm using the python:3.6.5-windowsservercore base image.
COPY . /app copies the build context into C:\app. This includes certain secret keys required for building the project.
After running the build, I want to delete keys folder (C:\app\keys), for this I use:
RUN powershell.exe Remove-Item -Path C:\app\keys -Force
Note - I have also tried each of following alternatives:
RUN Remove-Item -Path C:\app\keys -Force
RUN RD /S /Q C:\app\keys
This gives me following error:
Step 10/14 : RUN powershell.exe Remove-Item -Path C:\app\keys -Force
---> Running in 4e22124332b1
Remove-Item : Object reference not set to an instance of an object.
At line:1 char:1
+ Remove-Item -Path C:\app\keys -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Remove-Item], NullReferenceEx
ception
+ FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShe
ll.Commands.RemoveItemCommand
The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; powershell.exe Remove-Item -Path C:\app\keys -Force' returned a non-zero code: 1
What is the way to delete directory inside the image?
Solution:
RUN Remove-Item -Path C:\app\keys -Force -Recurse
There are 2 aspects to resolve this.
Based on your base image, what is your default shell? Bash or powershell? In my case it was powershell, so there is no need to mention powershell.exe at the beginning of the command.
The original command was incorrect RUN Remove-Item -Path C:\app\keys -Force because the folder had sub-folders and files. So you have to mention -Recurse

Set location to newly mounted disk image fails in PowerShell

I'm trying to run the following code in a function in my script:
$result = Mount-DiskImage -ImagePath $imagepath -PassThru
$driveLetter = ($result | Get-Volume).DriveLetter
Set-Location "$($driveLetter):"
But it constantly fails with this error:
Set-Location : Cannot find drive. A drive with the name 'G' does not exist.
At C:\Users\Agent\BuildAgent\scripts\helpers.psm1:35 char:3
+ Set-Location "$($driveLetter):"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (G:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
But after the script has terminated I can change the drive, no problem.
It might be timing related, but injecting a sleep (even a large one) before setting location, does not help.
Does anyone know about this issue?
Let's all up-vote the bug report.
Then, I think I have a workaround by manually adding the drive as a new PSDrive. I guess the New-PSDrive cmdlet can access the mounted drive even though others can't.
$mount = Mount-DiskImage $isoPath -PassThru
$driveLetter = ($mount | Get-Volume).DriveLetter
# Have to use New-PSDrive so other cmdlets in this session can see the new drive
New-PSDrive -Name $driveLetter -PSProvider FileSystem -Root "$($driveLetter):\"
// ...do things...
Dismount-DiskImage $mount.ImagePath
I can't try this but your command looks odd to me
Set-Location "$($driveLetter):"
have you tried
Set-Location "$driveLetter:"
without the parens

Resources