As part of my continuous integration build I am creating an SQL script. This SQL script has to be checked back in to TFS after it is generated. I'm using the TFS Powertools in Powershell.
The code I used on my machine was:
Add-TfsPendingChange -Add -Item $filename | New-TfsChangeSet
This worked fine on my dev box because the folder I was in is mapped to a TFS workspace. When I move it to my build server it no longer works because TeamCity doens't map it's checkouts to a workspace it just pulls the files down.
How do I check files into a specific folder in TFS without being in a mapped workspace? Is that even possible?
I worked on something to do this for our continuous delivery project using GO. I got it working using a combination of PowerShell and the .NET assemblies provider with Team Explorer. I could not get it working purely in PowerShell (although there may be a way!)
The following script will check-in whatever is contained in the material path which is supplied as a parameter into the specified server path (also a parameter). You can also specify credentials to use and a url for the TFS server.
This code requires either Visual Studio or the TFS Team Explorer client to be installed. You need to provide the directory location of the assemblies to the script in the AssemblyPath parameter. If these assemblies are not found then the script will error and show which ones are missing.
NOTE: The code has not been checked for a while so there may be typos etc. If you have any problems let me know and I will try to help.
[CmdletBinding(PositionalBinding=$false)]
Param(
[Parameter(Mandatory)] [string] $ServerUrl,
[Parameter(Mandatory)] [string] $ServerPath,
[Parameter(Mandatory=$False)] [string] $Domain = "",
[Parameter(Mandatory=$False)] [string] $Username = "",
[Parameter(Mandatory=$False)] [System.Security.SecureString] $Password,
[Parameter(Mandatory)] [string] [ValidateScript({($_ -eq $null) -or (Test-Path -Path $_ -PathType Container)})] $MaterialPath,
[Parameter(Mandatory)] [string] [ValidateScript({ Test-Path -Path $_ -PathType Container})] $AssemblyPath
)
<#
.SYNOPSIS
Responsible for checking in files into Source Control
.DESCRIPTION
#>
$clientDllName = "Microsoft.TeamFoundation.Client.dll"
$commonDllName = "Microsoft.TeamFoundation.Common.dll"
$versionControlClientDllName = "Microsoft.TeamFoundation.VersionControl.Client.dll"
$versionControlClientCommonDllName = "Microsoft.TeamFoundation.VersionControl.Common.dll"
#Create global variables to hold the value of Debug and Verbose action preferences which can then be used for all module function calls and passed into the remote session.
$verboseParameter = $PSCmdlet.MyInvocation.BoundParameters["Verbose"]
if ($verboseParameter -ne $null)
{
$Global:Verbose = [bool]$verboseParameter.IsPresent
}
else
{
$Global:Verbose = $false
}
$debugParameter = $PSCmdlet.MyInvocation.BoundParameters["Debug"]
if ($debugParameter -ne $null)
{
$Global:Debug = [bool]$debugParameter.IsPresent
}
else
{
$Global:Debug = $false
}
$scriptName = $(Split-Path -Leaf $PSCommandPath)
#Ensure any errors cause failure
$ErrorActionPreference = "Stop"
Write-Host "Running script ""$scriptName"" as user ""$env:USERDOMAIN\$env:USERNAME"""
#Check assembly path is a valid directory
If (Test-Path -Path $AssemblyPath -PathType Container)
{
Write-Host "Loading required assemblies from assembly path ""$AssemblyPath"""
$clientDllPath = Join-Path -Path $AssemblyPath -ChildPath $clientDllName
$commonDllPath = Join-Path -Path $AssemblyPath -ChildPath $commonDllName
$versionControlClientDllPath = Join-Path -Path $AssemblyPath -ChildPath $versionControlClientDllName
$versionControlClientCommonDllPath = Join-Path -Path $AssemblyPath -ChildPath $versionControlClientCommonDllName
If (!Test-Path -Path $clientDllPath -PathType Leaf)
{
Throw "Required assembly ""$clientDllName"" not found at path ""$clientDllPath"""
}
If (!Test-Path -Path $commonDllPath -PathType Leaf)
{
Throw "Required assembly ""$commonDllName"" not found at path ""$commonDllPath"""
}
If (!Test-Path -Path $versionControlClientDllPath -PathType Leaf)
{
Throw "Required assembly ""$versionControlClientDllName"" not found at path ""$versionControlClientDllPath"""
}
If (!Test-Path -Path $versionControlClientCommonDllPath -PathType Leaf)
{
Throw "Required assembly ""$versionControlClientCommonDllName"" not found at path ""$versionControlClientCommonDllPath"""
}
#Load the Assemblies
[Reflection.Assembly]::LoadFrom($clientDllPath) | Out-Null
[Reflection.Assembly]::LoadFrom($commonDllPath)| Out-Null
[Reflection.Assembly]::LoadFrom($versionControlClientDllPath) | Out-Null
[Reflection.Assembly]::LoadFrom($versionControlClientCommonDllPath) | Out-Null
#If the credentials have been specified then create a credential object otherwise we will use the default ones
If ($Username -and $Password)
{
$creds = New-Object System.Net.NetworkCredential($Username,$Password,$Domain)
Write-Host "Created credential object for user ""$($creds.UserName)"" in domain ""$($creds.Domain)"""
$tfsProjectCollection = New-Object Microsoft.TeamFoundation.Client.TFSTeamProjectCollection($ServerUrl, $creds)
}
else
{
Write-Host "Using default credentials for user ""$Env:Username"""
$tfsProjectCollection = New-Object Microsoft.TeamFoundation.Client.TFSTeamProjectCollection($ServerUrl)
}
$versionControlType = [Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]
$versionControlServer = $tfsProjectCollection.GetService($versionControlType)
Write-Host "Version control server authenticated user: $($versionControlServer.AuthenticatedUser)"
#Create a local path in the temp directory to hold the workspace
$LocalPath = Join-Path -Path $env:TEMP -ChildPath $([System.Guid]::NewGuid().ToString())
$null = New-Item -Path $LocalPath -ItemType Directory
#Create a "workspace" and map a local folder to a TFS location
$workspaceName = "PowerShell Workspace_{0}" -f [System.Guid]::NewGuid().ToString()
$workspace = $versionControlServer.CreateWorkspace($workspaceName, $versionControlServer.AuthenticatedUser)
$workingfolder = New-Object Microsoft.TeamFoundation.VersionControl.Client.WorkingFolder($ServerPath,$LocalPath)
$result = $workspace.CreateMapping($workingFolder)
$result = $workspace.Get() #Get the latest version into the workspace
Write-Host "Copying files from materials path ""$MaterialPath"" to temporary workspace path ""$LocalPath"""
robocopy $MaterialPath $LocalPath /s | Out-Null
$checkInComments = "Files automatically checked in by PowerShell script ""$scriptName"""
#Submit file as a Pending Change and submit the change
$result = $workspace.PendAdd($LocalPath,$true)
$pendingChanges = $workspace.GetPendingChanges()
Write-Host "Getting pending changes"
#Only try to check in if there are changes
If ($pendingChanges -ne $null)
{
If ($pendingChanges.Count -gt 0)
{
$changeSetId = $workspace.CheckIn($pendingChanges,$checkInComments)
Write-Host "Successfully checked in ""$($pendingChanges.Count)"" changes using changeset id ""$changeSetId"""
}
else
{
Write-Host "No changes to check-in"
}
}
else
{
Write-Host "No changes to check-in"
}
Write-Host "Deleting workspace and temporary folders"
$result = $workspace.Delete()
$null = Remove-Item -Path $LocalPath -Recurse -Force
}
else
{
Write-Error "The path to required assemblies ""$AssemblyPath"" cannot be found"
}
Related
So I have an assignment where I have to create an PowerShell script that takes three parameters, "$foldername", "$filename" and "$number".
The script checks if the folder "$foldername" exists and if not, creates it. After that it creates as many new files named "$filename" as "$number" specifies. After that it reports how many files have been created and lists them.
What I have so far.
Param (
[string]$foldername,
[string]$filename,
$number=1
)
if ((Test-Path -Path $foldername) -ne $true) {
new-item -path $foldername -ItemType directory #if the folder doesn't exist, create it.
}
$new_file= $foldername+"\$_"+$filename #save the path and name of the new file to an variable
if ((Test-Path -Path $new_file* -PathType leaf) -eq $true) {
Write-Host "$filename already exists in $foldername"
break #if a file with a name that contains $filename in it exists in $foldername, break and do not create any new files.
}
$null=1..$number | foreach { new-item -path $foldername -name $_$filename } #create new files using foreach.
write-host ("Created $number new files") #tell the user how many files were created
Get-ChildItem -path $foldername | where-object Name -like *$filename* | format-table Name #show the created files in a table format, formatted by name
There are a few problems and scuffed solutions in this script, but the main problem is the creation of the new files. Since the name of the new files come from $filename, simply running the script like so:
./script.ps1 -foldername C:\users\example\testing -filename "test.txt" -number 5
Would not work since it tries to create 5 files named "test.txt" and will just return errors.
I sort of solved it by using "foreach" and naming the files $_$filename which creates
1test.txt
2test.txt
...
5test.txt
But I found out that the correct way would be:
test1.txt
test2.txt
...
test5.txt
The number should be running in the filename somehow, but I am not sure how to do that.
Bonus points if you figure out how to check if the $filename files already exist in the target folder.
It's good to use Test-Path however I don't see a need for it here, you can use $ErrorAction = 'Stop' so that if the folder exists the script would instantly stop with a warning message. On the other hand, if the folder is a new folder there is no way the files already exist.
Param (
[parameter(Mandatory)]
[string]$FolderName,
[parameter(Mandatory)]
[string]$FileName,
[int]$Number = 1
)
$ErrorActionPreference = 'Stop'
try {
$newFolder = New-Item -Path $FolderName -ItemType Directory
}
catch {
# If the folder exists, show this exception and stop here
Write-Warning $_.Exception.Message
break
}
$files = 1..$Number | ForEach-Object {
# If this is a new Folder, there is no way the files already exist :)
$path = Join-Path $newFolder.FullName -ChildPath "$FileName $_.txt"
New-Item -Path $path -ItemType File
}
Write-Host 'Script finished successfully.'
$newFolder, $files | Format-Table -AutoSize
EDIT: I might have missed the point where you want to create the files in the folder even if the folder already exists, in that case you could use the following:
Param (
[parameter(Mandatory)]
[string]$FolderName,
[parameter(Mandatory)]
[string]$FileName,
[int]$Number = 1
)
$ErrorActionPreference = 'Stop'
$folder = try {
# If the Folder exists get it
Get-Item $FolderName
}
catch {
# If it does not, create it
New-Item -Path $FolderName -ItemType Directory
}
$files = 1..$Number | ForEach-Object {
$path = Join-Path $folder.FullName -ChildPath "$FileName $_.txt"
try {
# Try to create the new file
New-Item -Path $path -ItemType File
}
catch {
# If the file exists, display the Exception and continue
Write-Warning $_.Exception.Message
}
}
Write-Host "Script finished successfully."
Write-Host "Files created: $($files.Count) out of $Number"
$files | Format-Table -AutoSize
I have some code that checks a target file, waits for a change, and I want it to only move the most recent files based on their LastWriteTime Value. However, every time I change a file within the target directory nothing is copying over and I am having the copy-item directory change to "C:\Users\run". I
it recognizes that there are files to copy and even states their filename when throwing the error. What can I do in this situation to make sure my copy-item command is copying from my target directory?
Code for Reference:
$File = "C:\Users\run\Desktop\Target"
$destinationFolder = "c:\users\run\desktop\dest"
$maxDays = "-1"
$maxMins = "20"
$date = Get-Date
Write-Host "Waiting For File To Change in Job Cloud..."
$Action = '
dateChecker
Write-Host "Moving Files From Job Cloud To Server Shares... Please Do Not Disrupt This Service"
write-host "files copied to job cloud..."
exit
'
$global:FileChanged = $false
function dateChecker {
Foreach($File in (Get-ChildItem -Path $File)){
if($File.LastWriteTime -lt ($date).AddMinutes($maxMins)){
Write-Host "Moving Files From Job Cloud To Server Shares... Please Do Not Disrupt This Service"
Copy-Item -Path $File -Destination $destinationFolder -recurs #-ErrorAction #silentlyContinue
}
}
}
while($true) {
function Wait-FileChange {
param(
[string]$File,
[string]$Action
)
$FilePath = Split-Path $File -Parent
$FileName = Split-Path $File -Leaf
$ScriptBlock = [scriptblock]::Create($Action)
$Watcher = New-Object IO.FileSystemWatcher $FilePath, $FileName -Property #{
IncludeSubdirectories = $false
EnableRaisingEvents = $true
}
$onChange = Register-ObjectEvent $Watcher Changed -Action {$global:FileChanged = $true}
while ($global:FileChanged -eq $false){
Start-Sleep -Milliseconds 100
}
& $ScriptBlock
Unregister-Event -SubscriptionId $onChange.Id
}
Wait-FileChange -File $File -Action $Action
}
PowerShell is not switching directories - although I can certainly see why you'd think that based on the behavior. The explanation is closer than you might think though:
The -Path parameter takes a [string] argument.
$File is not a string - it's a [FileInfo] object - and PowerShell therefore converts it to a string before passing it to Copy-Item -Path. Unfortunately, this results in the name of the file (not the full path) being passed as the argument, and Copy-Item therefore has to resolve the full path, and does so relative to the current working directory.
You can fix this by passing the full path explicitly to Copy-Item -LiteralPath:
Copy-Item -LiteralPath $File.FullName ... |...
or you can let the pipeline parameter binder do it for you by piping the $File object to Copy-Item:
$File |Copy-Item ... |...
Why -LiteralPath instead of -Path? -Path accepts wildcard patterns like filenameprefix[0-9] and tries to resolve it to a file on disk, meaning if you have to operate on files with [ or ] in the name, it'll result in some unexpected behavior :)
Quick question regarding the PowerShell Copy-Item command. I was wondering if you have a directory structure and wanted to overwrite another directory structure is there a way to run the Copy-Item command in a 'preview' mode. It would output what files its overwriting from directory a to directory b but not actually perform the Copy-Item command.
Any help or advice appreciated.
Thanks.
Interesting question!
Here is my attempt of doing it all in Powershell, so not needing RoboCopy.
function Copy-Preview {
[CmdletBinding(DefaultParameterSetName = 'ByPath')]
param(
[Parameter(ValueFromPipeline = $true, Mandatory = $true, ParameterSetName = 'ByPath', Position = 0)]
[ValidateScript({ Test-Path $_ })]
[string]$Path,
[Parameter(ValueFromPipeline = $true, Mandatory = $true, ParameterSetName = 'ByLiteralPath', Position = 0)]
[ValidateScript({ Test-Path $_ })]
[string]$LiteralPath,
[Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 1)]
[string]$Destination,
[string]$Filter = $null,
[string]$Include = $null,
[string]$Exclude = $null,
[switch]$Recurse,
[switch]$Force
)
if ($PSCmdlet.ParameterSetName -eq 'ByLiteralPath') { $Path = $LiteralPath }
# determine if $Path and $Destination hold a file or a directory
$srcIsFolder = (Test-Path $Path -PathType Container -ErrorAction SilentlyContinue)
# cannot use Test-Path here because then the path has to exist.
# assume if it has an extension the path is a file, otherwise a directory
# NOTE:
# This is certainly not fullproof, so to avoid problems, always make sure
# the destination ends with a backslash if a directory is intended.
$destIsFolder = (-not ([System.IO.Path]::HasExtension($Destination)))
if ($destIsFolder -and !(Test-Path $Destination -PathType Container)) {
Write-Host "Destination path does not exist yet. All files from '$Path' will be copied fresh" -ForegroundColor Green
return
}
elseif ($srcIsFolder -and (!$destIsFolder)) {
# should not happen: source is a directory, while the destination is a file..
Write-Error "When parameter Path points to a directory, the Destination cannot be a file.."
return
}
$count = 0
if ($srcIsFolder -and $destIsFolder) {
# Both the source and the destinations are folders
# make sure both paths are qualified for .Replace() further down
if (-not $Path.EndsWith("\")) { $Path += "\" }
if (-not $Destination.EndsWith("\")) { $Destination += "\" }
$splat = #{
Filter = $Filter
Include = $Include
Exclude = $Exclude
Recurse = $Recurse
Force = $Force
}
# add either Path or LiteralPath to the parameters as they are mutually exclusive
if ($PSCmdlet.ParameterSetName -eq 'ByPath') { $splat.Path = $Path }
else { $splat.LiteralPath = $LiteralPath }
$srcFiles = Get-ChildItem #splat | Select-Object -ExpandProperty FullName
# reuse the splat parameters hash for the destination, but change the Path
if ($splat.LiteralPath) {($splat.Remove("LiteralPath"))}
$splat.Path = $Destination
$destFiles = Get-ChildItem #splat | Select-Object -ExpandProperty FullName
foreach ($srcItem in $srcFiles) {
$destItem = $srcItem.Replace($Path, $Destination)
if ($destFiles -contains $destItem) {
Write-Host "'$destItem' would be overwritten"
$count++
}
}
}
elseif (!$srcIsFolder) {
# the source is a file
if (!$destIsFolder) {
# the destination is also a file
if (Test-Path $Destination -PathType Leaf) {
Write-Host "'$Destination' would be overwritten"
$count++
}
}
else {
# source is file, destination is a directory
$destItem = Join-Path $Destination (Split-Path $Path -Leaf)
if (Test-Path $destItem -PathType Leaf) {
Write-Host "'$destItem' would be overwritten"
$count++
}
}
}
$msg = "$count item{0} would be overwritten by Copy-Item" -f $(if ($count -ne 1) { 's' })
$dash = "-" * ($msg.Length)
Write-Host "$dash`r`n$msg" -ForegroundColor Green
}
tl;dr:
Copy-Item -WhatIf will not give you the level of detail you're looking for - see below.
Use robocopy.exe -l instead (Windows only), as Ansgar Wiechers recommends, because it individually lists what files would be copied, including dynamically omitting those already present in the target dir (with the same size and last-modified time stamp, by default).
Generally, robocopy is faster and more fully featured than Copy-Item, and it avoids a notable pitfall of the latter.
Get-Help about_CommonParameters documents the -WhatIf common parameter supported by many (but not all) cmdlets, whose purpose is to preview an operation without actually performing it.
However, this feature is implemented in an abstract fashion, and often doesn't provide information as detailed as one would hope.
Case in point: while Copy-Item does support -WhatIf, it probably won't give you the level of detail you're looking for, because if the source item is a directory, only a single line such as the following is output:
What if: Performing the operation "Copy Directory" on target "Item: sourceDir Destination: destDir".
Note that you'll see the same line whether or not your Copy-Item call includes the -Recurse switch.
Even if you ensure existence of the target directory manually and append /* to the source directory path in order to see individual filenames, you'd only see them at the child level, not further down the subtree, and you'd never get the dynamic information that robocopy -l provides with respect to what files actually need replacement.
You can use the -whatif parameter.
Copy-item -path myfile.txt -destination myfoldertoCopyTo\ -whatif
We are currently working on a script, which is zipping a certain file, uploading it to a web server via API and then delete it locally again.
This is our current code:
$sourceFile = "D:\myfile.txt"
$destinationFile = "D:\myfile.zip"
function Add-Zip
{
Param([string]$zipfilename)
if (-not (Test-Path($zipfilename)))
{
Set-Content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
$shellApplication = New-Object -Com Shell.Application
$zipPackage = $shellApplication.NameSpace($zipfilename)
foreach ($file in $input)
{
$zipPackage.CopyHere($file.FullName)
Start-Sleep -Milliseconds 500
}
}
dir $sourceFile | Add-Zip $destinationFile
Write-Host "zip created"
# code to upload the zip here
Remove-Item $destinationFile
Write-Host "zip removed"
It creates the zip perfectly, upload works too, but when try to delete the zip file using Remove-Item, we get
Remove-Item : Cannot remove item D:\myfile.zip: The process cannot access the file 'D:\myfile.zip' because it is being used by another process.
How can we get rid of this lock? Is there anything we can .Dispose() to be able to delete the file afterwards?
Okay, found another way here: https://danvers72.wordpress.com/2014/11/18/creating-a-zip-file-from-a-single-file/
This is my working code:
$sourceFile = "D:\myfile.txt"
$destinationFile = "D:\myfile.zip"
<#
.Synopsis
Creates a new archive from a file
.DESCRIPTION
Creates a new archive with the contents from a file. This function relies on the
.NET Framework 4.5. On windwows Server 2012 R2 Core you can install it with
Install-WindowsFeature Net-Framework-45-Core
.EXAMPLE
New-ArchiveFromFile -Source c:\test\test.txt -Destination c:\test.zip
#>
function New-ArchiveFromFile
{
[CmdletBinding()]
[OutputType([int])]
Param
(
# Param1 help description
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
Position=0)]
[string]
$Source,
# Param2 help description
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$false,
Position=1)]
[string]
$Destination
)
Begin
{
[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
}
Process
{
try
{
Write-Verbose "Creating archive $Destination…."
$zipEntry = "$Source" | Split-Path -Leaf
$zipFile = [System.IO.Compression.ZipFile]::Open($Destination, 'Update')
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zipfile,$Source,$zipEntry,$compressionLevel)
Write-Verbose "Created archive $destination."
}
catch [System.IO.DirectoryNotFoundException]
{
Write-Host "ERROR: The source $source does not exist!" -ForegroundColor Red
}
catch [System.IO.IOException]
{
Write-Host "ERROR: The file $Source is in use or $destination already exists!" -ForegroundColor Red
}
catch [System.UnauthorizedAccessException]
{
Write-Host "ERROR: You are not authorized to access the source or destination" -ForegroundColor Red
}
}
End
{
$zipFile.Dispose()
}
}
New-ArchiveFromFile -Source $sourceFile -Destination $destinationFile
# code to upload the zip here
Remove-Item $destinationFile
When using the rm command to delete files in Powershell, they are permanently deleted.
Instead of this, I would like to have the deleted item go to the recycle bin, like what happens when files are deleted through the UI.
How can you do this in PowerShell?
2017 answer: use the Recycle module
Install-Module -Name Recycle
Then run:
Remove-ItemSafely file
I like to make an alias called trash for this.
If you don't want to always see the confirmation prompt, use the following:
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile('d:\foo.txt','OnlyErrorDialogs','SendToRecycleBin')
(solution courtesy of Shay Levy)
It works in PowerShell pretty much the same way as Chris Ballance's solution in JScript:
$shell = new-object -comobject "Shell.Application"
$folder = $shell.Namespace("<path to file>")
$item = $folder.ParseName("<name of file>")
$item.InvokeVerb("delete")
Here is a shorter version that reduces a bit of work
$path = "<path to file>"
$shell = new-object -comobject "Shell.Application"
$item = $shell.Namespace(0).ParseName("$path")
$item.InvokeVerb("delete")
Here's an improved function that supports directories as well as files as input:
Add-Type -AssemblyName Microsoft.VisualBasic
function Remove-Item-ToRecycleBin($Path) {
$item = Get-Item -Path $Path -ErrorAction SilentlyContinue
if ($item -eq $null)
{
Write-Error("'{0}' not found" -f $Path)
}
else
{
$fullpath=$item.FullName
Write-Verbose ("Moving '{0}' to the Recycle Bin" -f $fullpath)
if (Test-Path -Path $fullpath -PathType Container)
{
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}
else
{
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}
}
}
Remove file to RecycleBin:
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile('e:\test\test.txt','OnlyErrorDialogs','SendToRecycleBin')
Remove folder to RecycleBin:
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::Deletedirectory('e:\test\testfolder','OnlyErrorDialogs','SendToRecycleBin')
Here's slight mod to sba923s' great answer.
I've changed a few things like the parameter passing and added a -WhatIf to test the deletion for the file or directory.
function Remove-ItemToRecycleBin {
Param
(
[Parameter(Mandatory = $true, HelpMessage = 'Directory path of file path for deletion.')]
[String]$LiteralPath,
[Parameter(Mandatory = $false, HelpMessage = 'Switch for allowing the user to test the deletion first.')]
[Switch]$WhatIf
)
Add-Type -AssemblyName Microsoft.VisualBasic
$item = Get-Item -LiteralPath $LiteralPath -ErrorAction SilentlyContinue
if ($item -eq $null) {
Write-Error("'{0}' not found" -f $LiteralPath)
}
else {
$fullpath = $item.FullName
if (Test-Path -LiteralPath $fullpath -PathType Container) {
if (!$WhatIf) {
Write-Verbose ("Moving '{0}' folder to the Recycle Bin" -f $fullpath)
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}
else {
Write-Host "Testing deletion of folder: $fullpath"
}
}
else {
if (!$WhatIf) {
Write-Verbose ("Moving '{0}' file to the Recycle Bin" -f $fullpath)
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}
else {
Write-Host "Testing deletion of file: $fullpath"
}
}
}
}
$tempFile = [Environment]::GetFolderPath("Desktop") + "\deletion test.txt"
"stuff" | Out-File -FilePath $tempFile
$fileToDelete = $tempFile
Start-Sleep -Seconds 2 # Just here for you to see the file getting created before deletion.
# Tests the deletion of the folder or directory.
Remove-ItemToRecycleBin -WhatIf -LiteralPath $fileToDelete
# PS> Testing deletion of file: C:\Users\username\Desktop\deletion test.txt
# Actually deletes the file or directory.
# Remove-ItemToRecycleBin -LiteralPath $fileToDelete
Here is a complete solution that can be added to your user profile to make 'rm' send files to the Recycle Bin. In my limited testing, it handles relative paths better than the previous solutions.
Add-Type -AssemblyName Microsoft.VisualBasic
function Remove-Item-toRecycle($item) {
Get-Item -Path $item | %{ $fullpath = $_.FullName}
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}
Set-Alias rm Remove-Item-toRecycle -Option AllScope