Powershell exclude pdf extension files - powershell

I am trying to run powershell script to separate files of all extensions by iterating all the subfolders and creating a subfolder attachments at depth 3 except pdf but it is not working. Can someone help me out by pointing what I am doing incorrectly in script.
Thanks in advance
ForEach($Folder in (Get-ChildItem -Directory .\*\*\*)){
echo "Done"
Get-ChildItem -path $Folder -Exclude *.pdf | Move-Item -Destination $Folder\Attachments -ErrorAction Stop
}

I'd suggest adding the -WhatIf parameter to Move-Item to troubleshoot what that command is actually trying to do. It will probably be quite clear from the output that it's not doing what you think it's doing.
My guess is the problem is the fact that $Folder contains a DirectoryInfo item. The default string expansion for that is just the name, and you probably want the FullName.
Try:
ForEach($Folder in (Get-ChildItem -Directory .\*\*\*)){
echo "Done"
Get-ChildItem -path $Folder -Exclude *.pdf | Move-Item -Destination "$($Folder.FullName)\Attachments" -ErrorAction Stop
}
However, it's not clear from your question what you're actually trying to accomplish, primarily because "it doesn't work" is not a problem description. I'm not sure where the attachments folder is supposed to be.

Extending from my comment. Try something like this.
'PowerShell -Whatif or Confirm'
$Destination = 'D:\temp'
(Get-ChildItem -Directory -Recurse -Exclude '*.pdf' -Depth 3) |
ForEach-Object {
Write-Verbose -Message "Processing: $PSItem" -Verbose
# Remove the whatIf after you validate the results of the move and run it again.
Try {Move-Item -Path $PSItem.FullName -Destination "$Destination\Attachments" -ErrorAction Stop -WhatIf}
Catch
{
Write-Warning -Message "Error processing request"
$PSItem.Exception.Message
}
}
# Results
<#
VERBOSE: Processing: D:\Scripts\.vs
What if: Performing the operation "Move Directory" on target "Item: D:\Scripts\.vs Destination: D:\temp\Attachments".
VERBOSE: Processing: D:\Scripts\.vs\Scripts
What if: Performing the operation "Move Directory" on target "Item: D:\Scripts\.vs\Scripts Destination: D:\temp\Attachments".
VERBOSE: Processing: D:\Scripts\.vs\Scripts\v16
What if: Performing the operation "Move Directory" on target "Item: D:\Scripts\.vs\Scripts\v16 Destination: D:\temp\Attachments".
...
#>
If you want to see what is happening under the covers as part of your check, you can do this.
Trace-Command
# Review what the command expression is doing
Trace-Command -Name metadata,parameterbinding,cmdlet -Expression {
$Destination = 'D:\temp'
(Get-ChildItem -Directory -Recurse -Exclude '*.pdf' -Depth 3) |
ForEach-Object {
Write-Verbose -Message "Processing: $PSItem" -Verbose
# Remove the whatIf after you validate the results of the move and run it again.
Try {Move-Item -Path $PSItem.FullName -Destination "$Destination\Attachments" -ErrorAction Stop -WhatIf}
Catch
{
Write-Warning -Message "Error processing request"
$PSItem.Exception.Message
}
}
} -PSHost

Related

powershell Rename Script - Mostly functional, looking to finish and fully automate task

This is my first post to Stack Overflow, and I avoided asking for help and tried to figure this out as much as I could on my own. I have very little scripting experience, but I'm looking to learn. I chose this project as a place to start, and felt like my goals for this script got out of hand rather quickly.
What I have is a functional, probably very bloated, script, that only does a fraction of what I wanted it to do for me.
Here is the task I have, that before we were doing 100% by hand - manually file by file:
I have MP3 files of high importance that need to get copied off of an SD card and eventually moved to a shared drive that is backed up regularly.
These files are in the file name format of MMDDYYYYHHMMSS_RC-700R.mp3
We store these files on our data share in its own directory, organized further by the month, leading me try to add that in as part of my script, but it is a less important feature.
My goal was to safely move these files off of the SD card, rename them - removing the TIME of the file, but if there were 2 (or more) files made on the same date to append an alphabetical iterative count up. I tried to comment out every step, not only for others to read, but to keep myself apprised of what I was trying to accomplish in each section of the code.
#Start by Clearing Host and Saving Transcript
Clear-Host
$date = Get-Date -Format 'dddd MM-dd-yyyy'
Start-Transcript -Path "F:\Script$date.txt" -NoClobber -Append
#Set locations - SD Card:Import
$Import = "C:\Users\Death\Desktop\Minutes"
$Source = "F:\Minutes\"
$Destination = "F:\Final\"
#Test if $Source Exists, if not Create directory for Files to be transferred to
if(!(Test-Path -Path $Source)) {
New-Item -ItemType directory -Path $Source
Write-Host "Folder path has been created successfully at: " $Source
}
else {
Write-Host "The given folder path $Source already exists";
}
#Test if $Destination exists and create if false
if(!(Test-Path -Path $Destination)) {
New-Item -ItemType directory -Path $Destination
Write-Host "Folder path has been created successfully at: $Destination "}
else {
Write-Host "The given folder path $Destination already exists";
}
#Copy Items from $Import location
Get-ChildItem -Path $Import -Filter *.mp3 | Copy-Item -Destination $Source
#Rename Files adding Dashes between MM DD YYYY and HHMMSS
Get-ChildItem -Path $Source -Filter *.mp3 | Rename-Item -NewName {$_.Name -Replace ('^\n*(\d{2})(\d{2})(\d{4})(\d{6}).(?:...)(\d{3})\w','TC $1-$2-$3-$4')}
#Move files into $Destination\Year\Month created - Need to add
#Move files into $NewPath\Year\Month created
#Running in to problems with moving the files after they have been renamed - Likely due to
Get-ChildItem -File -Path $Source -Filter '*.mp3' |
ForEach-Object {
$Year = $_.LastWriteTime.Year
$Month = $_.LastWriteTime.Month
$Monthname = (Get-Culture).DateTimeFormat.GetMonthName($Month)
$ArchDir = "$Destination\$Year\$Monthname\"
if (-not (Test-Path -Path $ArchDir)) { New-Item -ItemType "directory" -Path $ArchDir | Out-Null }
Move-Item -Path $Source\*.mp3 -Destination $ArchDir -Verbose
}
#Would like to add a list of files renamed and where they moved to instead of just Enter to exit
Read-Host -Prompt "Press Enter to exit"
I have had little parts of my goals working in other versions of this code, but this is my most functional one.
Problems that currently exist:
I haven't figured out how to safely iterate files created on the same day when renaming files and leaving off the TIME - So as it is currently functioning I have it leaving the TIME on the file and I am manually removing it and adding any letters when needed
It is throwing all of the files in to $Destination in the Month of the first file, and putting all the files in there (not a huge issue as this was extra)
I would like it to list every move operation as well as any errors. It is doing this now with the $Source & $Destination folders & the -Verbose on the final GCI - Move operation.
Until I demonstrate that the script is 100% functional I have all locations in the script on my local machine to keep my boss happy.
I am sorry for the wall of text & Thanks in advance for any assistance.
This looks way over-complicated.
For the file parts, it could be as simple as this...
As per your stated use case:
My goal was to safely move these files off of the SD card,
rename them - removing the TIME of the file,
Clear-Host
$SourcePath = 'C:\Temp'
$TargetPath = 'C:\Temp\TempChild'
Get-ChildItem -Path $SourcePath -Filter '*.mp3' |
ForEach {
$FileName = $PSItem
Try
{
If ((Get-Item -Path "$TargetPath\$($FileName.Name)" -ErrorAction Stop))
{
Rename-Item -Path "$TargetPath\$($PSItem.Name)" -NewName "$($FileName.Name -replace '\d+_')" -WhatIf
Move-Item -Path $FileName.FullName -Destination $TargetPath -WhatIf
}
}
Catch {Move-Item -Path $FileName.FullName -Destination $TargetPath -WhatIf}
}
# Results
<#
# When the file does not exists
What if: Performing the operation "Move File" on target "Item: C:\Temp\04122021143000_RC-M1234R.mp3 Destination: C:\Temp\TempChild\04122021143000_RC-M1234R.mp3".
# When the file exists
What if: Performing the operation "Rename File" on target "Item: C:\Temp\TempChild\04122021143000_RC-M1234R.mp3 Destination: C:\Temp\TempChild\RC-M1234R.mp3".
What if: Performing the operation "Move File" on target "Item: C:\Temp\04122021143000_RC-M1234R.mp3 Destination: C:\Temp\TempChild\04122021143000_RC-M1234R.mp3".
#>
You can create new paths, without using New-Item. Just use the -Force switch/parameter on the copy/move action.
Test-Path -Path "$TargetPath\test1"
# Results
<#
False
#>
Get-ChildItem -Path $SourcePath -Filter '*.mp3' |
Copy-Item -Destination "$TargetPath\test1" -Force -WhatIf
# Results
<#
What if: Performing the operation "Copy File" on target "Item: C:\Temp\04122021143000_RC-M1234R.mp3 Destination: C:\Temp\TempChild\test1".
#>
Get-ChildItem -Path $SourcePath -Filter '*.mp3' |
Copy-Item -Destination "$TargetPath\test1" -Force
Test-Path -Path "$TargetPath\test1"
Get-ChildItem -Path $TargetPath -Filter '*.mp3'
# Results
<#
True
Directory: C:\Temp\TempChild
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 4/8/2021 6:04 PM 39 04122021143000_RC-M12345R.mp3
-a---- 4/8/2021 6:04 PM 39 04122021143000_RC-M1234R.mp3
#>
As for
but if there were 2 (or more) files made on the same date to append an alphabetical iterative count up.
I am not sure why you use alpha vs numeric. Since alpha would limit you to 26 letters before you'd end up having to double that string. Numeric of course, you can just look at the number and increment by 1.
Here's what I mean, just using your file name vs file properties. Yet, you can do the same approach, by looking at the file properties in the mix.
Clear-Host
$SourcePath = 'C:\Temp'
$TargetPath = 'C:\Temp\TempChild'
Get-ChildItem -Path $SourcePath -Filter '*.mp3' |
ForEach {
$FileName = $PSItem
Try
{
If (
-Not ((Get-ChildItem -Path $TargetPath -Filter $FileName.Name) -match "(?<=RC-M\d+R\d)") -and
($FileName.Name -replace '_\.*') -match
((Get-ChildItem -Path $TargetPath -Filter $FileName.Name) -replace '_\.*')
)
{
Rename-Item -Path "$TargetPath\$($FileName.Name)" -NewName "$(
$FileName.Name -replace 'R\.', 'R1.'
)" -ErrorAction Stop -WhatIf
Move-Item -Path $FileName.FullName -Destination $TargetPath -Verbose -WhatIf
}
}
Catch
{
$FileToIncrement = (
Get-ChildItem -Path $TargetPath |
Where-Object -Property Name -Match ($FileName.BaseName -replace 'R\d+')
).FullName
if($FileToIncrement -match "(?<=RC-M\d+R)(?<bv>\d+)")
{
Rename-Item -Path $FileToIncrement -NewName (
$FileToIncrement -replace "(?<=RC-M\d+R)(\d+)",
("{0:0000}" -f (([int]::Parse($matches.bv)+1)))
) -Verbose -WhatIf
Move-Item -Path $FileName.FullName -Destination $TargetPath -Verbose -WhatIf
}
}
}
# Results - when incrementer does not exist for the matched time string
<#
VERBOSE: Performing the operation "Rename File" on target "Item: C:\Temp\TempChild\04122021143000_RC-M12345R.mp3 Destination: C:\Temp\TempChild\04122021143000_RC-M12345R1.mp3".
VERBOSE: Performing the operation "Move File" on target "Item: C:\Temp\04122021143000_RC-M12345R.mp3 Destination: C:\Temp\TempChild\04122021143000_RC-M12345R.mp3".
VERBOSE: Performing the operation "Rename File" on target "Item: C:\Temp\TempChild\04122021143000_RC-M1234R.mp3 Destination: C:\Temp\TempChild\04122021143000_RC-M1234R1.mp3".
VERBOSE: Performing the operation "Move File" on target "Item: C:\Temp\04122021143000_RC-M1234R.mp3 Destination: C:\Temp\TempChild\04122021143000_RC-M1234R.mp3".
#>
# Results - when incrementer exists for the matched time string
<#
What if: Performing the operation "Rename File" on target "Item: C:\Temp\TempChild\04122021143000_RC-M12345R1.mp3 Destination: C:\Temp\TempChild\04122021143000_RC-M12345R0002.mp3".
What if: Performing the operation "Move File" on target "Item: C:\Temp\04122021143000_RC-M12345R.mp3 Destination: C:\Temp\TempChild\04122021143000_RC-M12345R.mp3".
What if: Performing the operation "Rename File" on target "Item: C:\Temp\TempChild\04122021143000_RC-M1234R1.mp3 Destination: C:\Temp\TempChild\04122021143000_RC-M1234R0002.mp3".
What if: Performing the operation "Move File" on target "Item: C:\Temp\04122021143000_RC-M1234R.mp3 Destination: C:\Temp\TempChild\04122021143000_RC-M1234R.mp3".
#>

I want to exclude a sub folder from a recursive search and copy

I want to look in directory "x" recursively for file type "y" excluding sub directory "m" and copy files to sub directory "m"
im trying this
$TargetDir = read-host "Please enter target Dir"
$sourceDir = read-host "Please enter source Dir"
$format = read-host "Format to look for"
Get-ChildItem -Path $sourceDir -Recurse -Filter $format | where FullName -Not -Like $TargetDir |
Copy-Item -Destination $TargetDir
You better try use foreach cycle. Here is example for searching for photo and video.
# Making an array of all files from Get-ChildItem
$searchItems = Get-ChildItem -Path $sourceDir -Recurse -Include *.mp4,*.jpg,*.jpeg | where FullName -notlike $TargetDir
# Copy files one by one in cycle
foreach($currentFile in $searchItems) {
Copy-Item -Path $currentFile.Fullname -Destination $TargetDir
}
I figured it out, But it would be great to have some things explained
CODE:
$TargetDir = read-host "Please enter target Dir"
$sourceDir = read-host "Please enter source Dir"
$format = read-host "Format to look for"
$folders = Get-ChildItem -Path $sourceDir -Recurse -filter $format | Where
{($_.PSIsContainer) -and ($TargetDir -notcontains $_.Name)}
foreach ($f in $folders){
Write-Host "These Files will be copied: $f"
Copy-Item - path $sourceDir$f -Destination $TargetDir\$f -Recure -Force}
I dont understand :
Where {($_.PSIsContainer) -and ($TargetDir -notcontains $_.Name)}
and why
Write-Host "These Files will be copied: $f"
does not show up when ran
This...
[Write-Host "These Files will be copied: $f"]
... is because you are doing this is a loop, and Write-Host clear the buffer. Except for when you need colorized screen output, Write-Host is mostly useless. Well, except for in some formatting use cases. Generally just don't use it. Even the PowerShell author says so.
Output to the screen is the PowerShell default unless you tell it otherwise. The better option to Write-Host is Write-Output, or Out-Host or Tee-Object. See the help files on their particulars.
Get-ChildItem has several switches and if you just want directories, there's a switch for that and -Exclude for well, you know.
# Get specifics for a module, cmdlet, or function
(Get-Command -Name Get-ChildItem).Parameters
(Get-Command -Name Get-ChildItem).Parameters.Keys
# Results
<#
...
Exclude
...
Directory --- (This is what that $_.PSIsContainer/$PSItem.PSIsContainer this is doing, but that is legacy stuff.)
...
#>
Get-help -Name Get-ChildItem -Examples
Get-help -Name Get-ChildItem -Full
Get-help -Name Get-ChildItem -Online
About Objects --- Objects in Pipelines
Thus...
# Get directory names only and return only the full UNC
(Get-ChildItem -Directory -Path 'D:\SourceFolder'-Recurse).FullName
# Results
<#
D:\SourceFolder\est
D:\SourceFolder\here
D:\SourceFolder\hold
D:\SourceFolder\TargetFolder
#>
# Just like the above, but exclude the TargetFolder
(Get-ChildItem -Directory -Path 'D:\SourceFolder' -Exclude 'TargetFolder' -Recurse).FullName
# Results
<#
D:\SourceFolder\est
D:\SourceFolder\here
D:\SourceFolder\hold
#>
So, a small refactoring of your code.
# Recursively get all text files, in all directories, except one for copy action
Get-ChildItem -Path 'D:\SourceFolder' -Filter '*.txt' -Exclude 'TargetFolder' -Recurse |
ForEach {
"These Files will be copied: $($PSItem.FullName)"
# Remove the -whatIf for the actual run.
Copy-Item -Path $PSItem.FullName -Destination 'D:\SourceFolder\TargetFolder' -Recurse -WhatIf
}
# Results
<#
These Files will be copied: D:\SourceFolder\here\mytest - Copy.txt
What if: Performing the operation "Copy File" on target "Item: D:\SourceFolder\here\mytest - Copy.txt Destination: D:\SourceFolder\TargetFolder\mytest - Copy.txt".
These Files will be copied: D:\SourceFolder\here\mytest.txt
What if: Performing the operation "Copy File" on target "Item: D:\SourceFolder\here\mytest.txt Destination: D:\SourceFolder\TargetFolder\mytest.txt".
These Files will be copied: D:\SourceFolder\hold\awél.txt
What if: Performing the operation "Copy File" on target "Item: D:\SourceFolder\hold\awél.txt Destination: D:\SourceFolder\TargetFolder\awél.txt".
#>
Of course, you need to tweak the above yo use your variables, and take out all the comments. Commenting is a good thing, but over commenting is just as bad as under commenting or bad/unintelligible commenting. All of which many have their preferences.
My rules:
Don't comment on the obvious, where the code speaks for itself.
Don't use shorthand stuff only you know or remember.
Write in the plain straight forward localized language.
Write for those that don't know you or shorthand stuff and will follow you or who may use/review your code; who can and often are new to this stuff.

How to move files based on filename using PowerShell?

I am new to PowerShell and am stuck at something.
How to move files based on filename using PowerShell?
Move 0001_ddmmyy_username[active1]_L_kkkkk.pdf to C:\Users\abc\London
Move 0001_ddmmyy_jacky[active1]_R_kkkkk.pdf to C:\Users\abc\Russia
Move 0001_ddmmyy_jim[active1]_P_kkkkk.pdf to C:\Users\abc\Poland
I used the following code to move files to a folder called London. It fails if the file name has any square bracket with text [kkkk].
gci 'C:\Users\abc' -Recurse -Include "*_L*" | %{ Move-Item $_.FullName 'C:\Users\abc\London'}
How can I automate this?
There are multiple ways:
Get-Location
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-location?view=powershell-7
gci (Get-Location).Path
or simply .\
gci .\
additionaly, gci will default to current path if none is specified. So the following will get the current folder:
gci
Use -LiteralPath in the Move-Item cmdlet.
Move-Item -LiteralPath $sourcePath $destinationPath
I'd do something similar to below:
# Note I'm using -File so it only returns files
$items = gci .\ -Recurse -File -Include *_L*, *_R*, *_P*
foreach($item in $items) {
# Could utilize something cleaner/better but this will do
if($item.Name -like "*_L*") {
Move-Item -LiteralPath $item 'C:\Users\abc\London'
} elseif($item.Name -like "*_R*") {
Move-Item -LiteralPath $item 'C:\Users\abc\Russia'
} elseif ($item.Name -like "*_P*") {
Move-Item -LiteralPath $item 'C:\Users\abc\Poland'
} else {
# Unexpected output
Write-Host "The path did not match what was expected"
Write-Host $item.Name
}
}
Windows 10 64-bit. PowerShell 5.
How to move files based on file basename using PowerShell gci, foreach, if, -like, move-item and -literalpath
Move 0001_ddmmyy_username[active1]_L_kkkkk.pdf to C:\Users\abc\London
Move 0001_ddmmyy_jacky[active1]_R_kkkkk.pdf to C:\Users\abc\Russia
Move 0001_ddmmyy_jim[active1]_P_kkkkk.pdf to C:\Users\abc\Poland
Change $env:userprofile\desktop. Remove -whatif when you are satisfied it works.
$items = gci -recurse -file *_L_*, *_R_*, *_P_*
foreach($item in $items) {
# Change $env:userprofile\desktop
if($item -like "*_L_*") {
Move-Item -LiteralPath $item "$env:userprofile\desktop\London" -whatif
} elseif($item -like "*_R_*") {
Move-Item -LiteralPath $item "$env:userprofile\desktop\Russia" -whatif
} elseif ($item -like '*_P_*') {
Move-Item -LiteralPath $item "$env:userprofile\desktop\Poland" -whatif
}
}
Comments:
With some cmdlets you will get odd results when you use -Path and any part of the full file name contains []. The fix is to use the -LiteralPath parameter. See Get-Help Move-Item -Parameter *path* – Lee_Dailey
How to move files based on file basename using PowerShell gci, foreach, if, -like, move-item and -literalpath

Powershell copy and rename files

I'm trying to copy files from a source folder to a destination folder, and rename the files in the process.
$Source = "C:\Source"
$File01 = Get-ChildItem $Source | Where-Object {$_.name -like "File*"}
$Destination = "\\Server01\Destination"
Copy-Item "$Source\$File01" "$Destination\File01.test" -Force -
Confirm:$False -ErrorAction silentlyContinue
if(-not $?) {write-warning "Copy Failed"}
else {write-host "Successfully moved $Source\$File01 to
$Destination\File01.test"}
The problem is that since Get-ChildItem doesn't throw an error message if the file is not found, but rather just gives you a blank, I end up with a folder called File01.test in destination if no file named File* exists in $Source.
If it does exist, the copy operation carries out just fine. But I don't want a folder to be created if no matching files exist in $Source, rather I just want an error message logged in a log file, and no file operation to occur.
This shouldn't matter what the file name is, but it won't account for files that already exist in the destination. So if there is already File01.txt and you're trying to copy File01.txt again you'll have problems.
param
(
$Source = "C:\Source",
$Destination = "\\Server01\Destination",
$Filter = "File*"
)
$Files = `
Get-ChildItem -Path $Source `
| Where-Object -Property Name -Like -Value $Filter
for ($i=0;$i -lt $Files.Count;$i++ )
{
$NewName = '{0}{1:D2}{3}' -f $Files[$i].BaseName,$i,$Files[$i].Extension
$NewPath = Join-Path -Path $Destination -ChildPath $NewName
try
{
Write-Host "Moving file from '$($Files[$i].FullName)' to '$NewPath'"
Copy-Item -Path $Files[$i] -Destination
}
catch
{
throw "Error moving file from '$($Files[$i].FullName)' to '$NewPath'"
}
}
You can add an "if" statement to ensure that the code to copy the files only runs when the file exists.
$Source = "C:\Source"
$Destination = "\\Server01\Destination"
$File01 = Get-ChildItem $Source | Where-Object {$_.name -like "File*"}
if ($File01) {
Copy-Item "$Source\$File01" "$Destination\File01.test" -Force -Confirm:$False -ErrorAction silentlyContinue
if(-not $?) {write-warning "Copy Failed"}
else {write-host "Successfully moved $Source\$File01 to
$Destination\File01.test"}
} else {
Write-Output "File did not exist in $source" | Out-File log.log
}
In the "if" block, it will check to see if $File01 has anything in it, and if so, then it'll run the subsequent code. In the "else" block, if the previous code did not run, it'll send the output to the log file "log.log".

Formatting the verbose output of a Remove-Item command

I have the following command:
Get-ChildItem $build_path `
-Include *.bak, *.orig, *.txt, *.chirp.config `
-Recurse | Remove-Item -Verbose
to clear some files from the build folder of a VS solution. I use the Verbose switch so that I can see which files are being deleted. It works fine but the output is too verbose:
VERBOSE: Performing operation "Remove File" on Target "R:\Visual Studio 2010\Projects\SomeProject\SomeProject.Web.build\App_Readme\glimpse.mvc3.readme.txt".
VERBOSE: Performing operation "Remove File" on Target "R:\Visual Studio 2010\Projects\SomeProject\SomeProject.Web.build\App_Readme\glimpse.readme.txt".
I just need to see something like that:
Removing file \App_Readme\glimpse.mvc3.readme.txt".
Removing file \App_Readme\glimpse.readme.txt".
...
I know i can do this with a foreach statement and a Write-Host command, but I believe it can be done with some pipelining or something. Any ideas?
Using ForEach-Object is pretty straightforward:
Get-ChildItem $build_path `
-Include *.bak, *.orig, *.txt, *.chirp.config `
-Recurse | foreach{ "Removing file $($_.FullName)"; Remove-Item $_}
As #user978511 pointed out, using the verbose output is more complicated:
$ps = [PowerShell]::Create()
$null = $ps.AddScript(#'
Get-ChildItem $build_path `
-Include *.bak, *.orig, *.txt, *.chirp.config `
-Recurse | Remove-Item -Verbose
'#)
$ps.Invoke()
$ps.Streams.Verbose -replace '(.*)Target "(.*)"(.*)','Removing File $2'
In PowerShell 3.0 you can write the Verbose stream to the output stream (e.g 4>&1) and then replace the message:
Get-ChildItem $build_path `
-Include *.bak, *.orig, *.txt, *.chirp.config `
-Recurse | Remove-Item -Verbose 4>&1 | Foreach-Object{ `
Write-Host ($_.Message -replace'(.*)Target "(.*)"(.*)','Removing File $2') -ForegroundColor Yellow
}
This is a few years too late but it might help someone else who stumbles upon this like I did so I'll provide it anyway.
I would try the file deletion and then report on success or failure. See below:
$FileList = $build_path `
-Include *.bak, *.orig, *.txt, *.chirp.config `
-Recurse
foreach ($File in $FileList)
{
Try
{
Remove-Item $File.FullName -Force -ErrorAction Stop
Write-Output "Deleted: $($File.Parent)\$($File.Name)"
}
Catch
{
Write-Output "Error deleting: $($File.Parent)\$($File.Name); Error Message: $($_.Exception.Message)"
}
}
If you wanted to both output to console and log to a file you can use Tee-Object at the end of each line starting with Write-Output above.
| Tee-Object -FilePath $your_log_file -Append
To be able to modify the message you need first to cath the output that is not that easy. You can refer to answer on this page:
Powershell Invoke-Sqlcmd capture verbose output
to catch the output. From there on you can modify the message and show it in your format, but foreach options looks easier to me