Reputation: 3481
I have the following script to remove folders/files remotely
$Directory = "E:\Data"
Invoke-Command -Computer $Server -ScriptBlock {
param ($dir, $name)
$f = Get-ChildItem -Path $dir | Where {$_.Name -Match "$name"}
If ($f) {
$f | Foreach {
Remove-Item $_ -confirm:$false -Recurse -Verbose
}
}
else {
Write-Verbose "No file found"
}
} -ArgumentList $Directory, $DB
for some reason, it tries to look for files in C:\users\documents
instead...even though i clearly defined the directory param at E:\Data
Cannot find path 'C:\Users\Documents\file.3.db' because it does not exist.
so file.3.db
actually exists on E:\Data
...yet somehow its merging that with C:\
directory...which the file doesnt exist on and outputting that error message. i am confused how is that happening
EDIT: the below code works just fine, but i updated it to that one above because i wanted file checking...though now that rendered the code to not work anymore:
Invoke-Command -Computer $Server -ScriptBlock {
param ($dir, $name)
Get-ChildItem -Path $dir |
Where {$_.Name -Match "$name"} |
Remove-Item -confirm:$false -Recurse -Verbose
} -ArgumentList $Directory, $DB
Upvotes: 0
Views: 192
Reputation: 7153
You can debug this all locally and see the issue. Mainly, you need to Select the FullName with -ExpandProperty
as well.
$Directory = "d:\temp"
Invoke-Command -Computer $Server -ScriptBlock {
param ($dir, $name)
Write-Output "dir='$dir', name='$name'"
$f = Get-ChildItem -Path $dir | Where {$_.Name -Match $name} | Select -ExpandProperty FullName
if ($f) {
$f | Foreach {
Remove-Item $_ -confirm:$false -Verbose -WhatIf
}
}
else {
Write-Verbose "No file found"
}
} -ArgumentList $Directory, "test*"
NOTE: I added a -WhatIf
to the Remove-Item call for testing so I did not remove any data in my machine. I also removed -Recurse
since that makes no sense to me...but you can add it back to my test code of course.
From this, I think you can get your final solution working.
Upvotes: 2