I'm trying to get a script to find and delete specific files on remote hosts. To do this the script cycles through a list of locations and file names in a couple of arrays.
One of the files I need to do this with is on called 101" "" "lyrics.vbs
but I can't find a way for it to detect the file without giving the error message test-path : Illegal characters in path
and reference to the ""
marks. I've searched around this and tried the solution of saving the file path into a text file and then calling it with get-item -literalpath
but this didn't work either. I've also tried using the backtick `
before each of the "
in the file paths but still get the same results. The part of the code that is used for this is:
$users | ForEach-Object {
#Creating an array file locations
$filelist = @("c$\Users\$($_.Name)\101__lyrics.vbs","c$\Users\$($_.Name)\101" "" "lyrics.vbs","c$\Users\$($_.Name)\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\101" "" "lyrics.vbs>")
foreach ($file in $filelist)
{
$newfilepath = Join-Path "\\$computer\" "$file"
if (test-path $newfilepath)
{
Write-Host -foregroundcolor Yellow "$newfilepath file exists"
try
{
Remove-Item $newfilepath -force -recurse -ErrorAction Stop
}
catch
{
Write-host -ForegroundColor red "Error while deleting $newfilepath on $computer.`n$($Error[0].Exception.Message)"
continue
}
Write-Host -ForegroundColor green "$newfilepath file deleted`n"
}
}
Thank you very much.
Edit: The error message I get when adding backticks before each "
and using -literalpath
is:
test-path : Illegal characters in path.
At .\Rb.ps1:126 char:22
+ if (test-path -literalpath $newfilepath)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (\\AAZAJCMW0459\...`" `"lyrics.vbs:String) [Test-Path], ArgumentException
+ FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell.Commands.TestPathCommand
In a later comment you say that it's a malicious file, so presumably its name was crafted to evade normal attempts to delete it.
Indeed, "
is not a legal filename character on NTFS on Windows, and attempts to target such a file directly will fail - no escaping technique will help.
You may be able to gain access to the file via enumeration / wildcard matching, obtain its short 8.3 name, and use that to delete it.
Update: The OP has confirmed that deleting via the 8.3 file name worked.