PowerShell Remove Junction - powershell

As of Windows 10 PowerShell is finally capable of creating Junctions and links natively.
Howerver the Remove-Item function seems to be unaware of the junction and tries to remove the directory asking for confirmation and if it should recursively delete items within.
So, the question is:
Is there a way to remove a junction using PowerShell native Cmdlets? (i.e. without calling cmd)

Is there a way to remove a junction using PowerShell?
Currently, at least in PowerShell v5, this is considered "fixed". What you can do is use the -Force switch, else you will get an error calling the path an NTFS junction. The reason that I at least use the quotes on fixed is that using the switch will still make the message about children in the directory show up. Selecting Y will still only delete the junction in my testing using PSv5.
Remove-Item "C:\temp\junction" -Force -Confirm:$False
If that doesn't work for you or you don't have v5 you can use the .Net method to delete a directory. This appears to work correctly as well.
[io.directory]::Delete("C:\temp\junction")

have a try on this "command-let":
cmd /c rmdir .\Target
source:Powershell Remove-Item and symbolic links

Simple command -
rm [path of file] -Force

After search by Google for a long time, I found the answer:
function Remove-Any-File-Force ($Target) {
if ( Test-Path -Path "$Target" ){
& $env:SystemRoot\System32\ATTRIB.exe -S -H -R "$Target" >$null 2>$null
} else {
return
}
$TargetAttributes = (Get-Item -Path $Target -Force).Attributes.ToString()
if ($TargetAttributes -match "ReparsePoint") {
if ($TargetAttributes -match "Archive") {
Remove-Item -Path "$Target" -Force
} else {
try {
& $env:SystemRoot\System32\cmd.exe /c rmdir /Q "$Target" >$null 2>$null
} catch {
try {
[io.directory]::Delete("$Target")
} catch {
Remove-Item -Path "$Target" -Force
}
}
}
} else {
if ($TargetAttributes -match "Directory") {
Remove-Item -Path "$Target" -Force -Recurse
} else {
Remove-Item -Path "$Target" -Force
}
}
}

Related

Powershell : Search the Subdirectory and copy the file to that directory

I have been working on a Powershell script from past 2 weeks and I haven't made much progress in that.
So I'm trying to copy a file called version.properties from the root of my gradle project to the Subdirectories like "src/main/resources", "src/main/webapp" and "src/main/application".
If i hard code the path it's working, but im trying to make it generic by finding the directory and copying my file to that directory.
I want my version.properties file to be copied to "resources","webapp" and "application" directory after i run my powershell script.
How can i do it? Any suggestions are appreciated.
$SourceDirectory = "Projectroot\version.properties"
$folders = gci $SourceDirectory -Recurse -Directory
$jar = "src/main/resources"
$ear = "src/main/application"
$war = "src/main/webapp"
foreach ($folder in Sfolders) {
if (Test-Path $folder/$jar) {
write-host "copying to $folder/$jar"
Copy-Item-Path "{$SourceDirectory}\version.properties" -Destination $folder/$jar -Recurse -Force
}
elseif (Test-Path $folder/$ear) {
write-host "copying to $folder/$ear"
Copy-Item-Path "{$SourceDirectory}\version.properties" -Destination $folder/$ear -Recurse -Force
}
elseif (Test-Path $folder/$war) {
write-host "copying to $folder/$war"
Copy-Item-Path "{$SourceDirectory}\version.properties" -Destination $folder/$war -Recurse -Force
}
else {
Write-Host "No such path"
}
}
Assuming this is the path structure of a project:
#ProjectRoot
#ProjectRoot\version.properties <--- File
#ProjectRoot\src
#ProjectRoot\src\main
#ProjectRoot\src\main\application
#ProjectRoot\src\main\resources
#ProjectRoot\src\main\webapp
The following script will do what you seek.
$SourceDirectory = "C:\temp\Projectroot"
$DestinationDirectories = 'resources','application','webapp'
foreach ($I in $DestinationDirectories) {
$CurrentDest = "$SourceDirectory\src\main\$I"
if (Test-Path -Path $CurrentDest) {
Copy-Item -Path "$SourceDirectory\version.properties" -Destination $CurrentDest
} else {
Write-Warning "Path not found: $CurrentDest"
}
}
If I didn't get the path structure, please clarify which is it.
I am assuming too that "main" is a static keyword here but if it is not, that script might need to be adjusted to reflect that.

Powershell 5.1.17763.1007 How to execute a string-command stored in a variable (Copy-Item)

I have a simple tasks that doesnt work:
$Copy = copy-item -path "C:\Folder 0" -destination "C:\Folder $x\" -recurse
for($x=1; $x -le 9;$x++)
{
$Copy
}
I cannot execute the command in the variable $Copy, when I run the loop it just prints $Copy to the console as the variable seems to be empty.
I tried Invoke-Expression, & $Copy, putting the Copy-Item command under "", but that doesnt work here...
Any advice for a beginner?
Thanks in advance!
As explained in the comments, Copy-Item doesn't return anything by default, so the value of $copy is $null.
From your clarifying comment:
I wanted actually just to store the command
If you want an executable block of code that you can invoke later, you might want to define a [scriptblock]. Scriptblock literals in PowerShell are easy, simply wrap your code in {}, and optionally supply parameter definitions:
$CopyCommand = {
param([string]$X)
Copy-Item -Path "C:\Folder 0" -Destination "C:\Folder $X\" -Recurse
}
& $CopyCommand 1
# later in the script
& $CopyCommand 2
or you can define a function with the same:
function Copy-MyFolderTree
{
param([string]$X)
Copy-Item -Path "C:\Folder 0" -Destination "C:\Folder $X\" -Recurse
}
Copy-MyFolderTree -X 1
# later in the script
Copy-MyFolderTree -X 2

Powershell Scripting Variables

I have set some variables in PowerShell. The variables are created at the beginning of my script. However, the values for the variables are being executed at start which in turns gives and error message. Ex:
$checker = get-item -path C:\users\user\desktop\Foldername
$finder = Test-path -Path $checker
if($finder -eq $finder )
{
}
Else
{
Create-Item -Path C:/users/user/desktop -name "Foldername" -itemtype Directory
}
I do know that if I run this it will give me an error because the directory never existed and I can just change the variable order to avoid errors.
My question is that this script is going to be more lines of code than this and I would have to create the variable right when its needed to avoid errors.
How can I use these variables like a regular programming language where the variables are ignored until called upon.
Using Get-Item and checking with Test-Path afterwards is not a good design. Two better ways:
Use Get-Item only and check for $null to check for its existence:
$checker = Get-Item -Path C:\users\user\desktop\Foldername -ErrorAction SilentlyContinue
if ($checker) {
# do something with the existing folder
} else {
Create-Item -Path C:/users/user/desktop -Name "Foldername" -ItemType Directory
}
Use Test-Path only to check for its existence:
if (Test-Path -Path C:\users\user\desktop\Foldername) {
# do something with the existing folder
} else {
Create-Item -Path C:/users/user/desktop -Name "Foldername" -ItemType Directory
}

Powershell is missing the terminator: " and Missing closing '}' in statement block or type definition

I am new on powershell and I have an issue. I am trying to make a script that cleans all my directories older than 30 days, but when I run it, it breaks. Does anyone know what problem I have?
$fromNDays = $args[0]
$cutOffDate = (Get-Date).AddDays(-$fromNDays)
$directoriesToDelete = Get-ChildItem -Path $path -Attributes Directory -Filter r* | Where-Object LastWriteTime -le $cutOffDate
echo "deleting from $cutOffDate"
cd $(Agent.ReleaseDirectory)
cd ..\..
pwd
Foreach($directoryToDelete in $directoriesToDelete)
{
if($directoryToDelete.Name -ne "ReleaseRootMapping")
{
try
{
echo "Deleting directory $directoryToDelete"
Remove-Item –path $directoryToDelete.FullName -Force -Recurse
}
catch
{
echo "Failed deleting $directoryToDelete.FullName"
}
}
}
The error that I have when it runs is:
echo "Failed deleting $directoryToDelete.FullName"
+ ~
2020-03-09T09:55:23.3827859Z ##[error]The string is missing the terminator: ".
deleteReleaseDirectoryFrom30.ps1:12 char:5
2020-03-09T09:55:23.3832466Z ##[error]+ {
2020-03-09T09:55:23.3836221Z ##[error]Missing closing '}' in statement block or type definition.
This error apears on line 12, 23, 8 and 10
In your code, the script doesn't know, that $directoryToDelete.FullName is a variable.
So first, put them one into brackets:
try{
echo "Deleting directory ${directoryToDelete}"
Remove-Item –path ${directoryToDelete.FullName} -Force -Recurse
}
catch
{
echo "Failed deleting ${directoryToDelete.FullName}"
}
As described here : https://github.com/PowerShell/vscode-powershell/issues/1308, there is this problem with PS and VSCode.
According to the answers on GitHub, a solution is to paste your code in the Powershell ISE (you can do a simple Windows search for that), and save using it. Then you can continue coding with VsCode or anything else you use.
Hope this helps you, even though I'm a bit late here...

Array handling in powershell

Context :
I have a folder and have some files inside it. I am running a PowerShell script from Jenkins to delete the list of files selected from Jenkins and copy the fresh file from the source. I am trying to delete the files all at an time and copy the list of files like Ctrl+A and copy and paste. I have the script but it is doing individual deletion and copy-paste.
foreach ($database_filename in $database_files) {
Remove-Item -Path $auditFile_Directory -Include $database_filename* -Recurse -Force
Remove-Item -Path $logFile_Directory -Include $database_filename* -Recurse -Force
if ($?) {
log "Deleting the old files complete."
}
try {
log "File sets for $database_filename copying...."
$primary_File = "$database_filename$primaryfile_extn"
$audit_Files = "$database_filename$auditfile_extn"
$log_Files = "$database_filename$logfile_extn"
Copy-Item -Path $sourceFile_Directory$primary_File -Destination $auditFile_Directory
Copy-Item -Path $sourceFile_Directory$audit_Files -Destination $auditFile_Directory
Copy-Item -Path $sourceFile_Directory$log_Files -Destination $logFile_Directory
if ($?) {
log "A fresh golden copy of the db files created."
} else {
Write-Error "Failed! error creating the golden copy, please check the log files"
}
}
catch [System.Net.WebException], [System.IO.IOException]
{
Write-Error "Failed! Unable to copy the SQL files"
}
}
}
You need to split the code into two loops then, the first loop will delete all the files and the second loop will copy all the files.