List 'target' of 'links' - powershell

I need to get the 'target' inside of a shortcut link to another server.
But… when I use -Recurse, it follows the links, instead of simply just getting the shortcut target.
Here is code that I found online that I edited to serve my purpose. But it goes into the links and tries to find shortcuts within another server:
#Created By Scott
$varLogFile = "E:\Server\GetBriefsTargets.log"
$varCSVFile = "E:\Server\GetBriefsTargets.csv"
function Get-StartMenuShortcuts
{
$Shortcuts = Get-ChildItem -Recurse "F:\Connect" -Include *.lnk
#$Shortcuts = Get-ChildItem -Recurse "D:\Scripts\scott_testing" -Include *.lnk
$Shell = New-Object -ComObject WScript.Shell
foreach ($Shortcut in $Shortcuts)
{
$Properties = #{
ShortcutName = $Shortcut.Name;
ShortcutFull = $Shortcut.FullName;
ShortcutPath = $shortcut.DirectoryName
Target = $Shell.CreateShortcut($Shortcut).targetpath
}
New-Object PSObject -Property $Properties
}
[Runtime.InteropServices.Marshal]::ReleaseComObject($Shell) | Out-Null
}
$Output = Get-StartMenuShortcuts
$Output
ECHO "$Output" >> $varLogFile
ECHO "$Output" >> $varCSVFile
Could someone please offer advice on what I can change so that it still finds all of the shortcut links in all of the folders? and stops going inside of those links?
ie:
F:\Connect\CLIENTA\shortcut.lnk
F:\Connect\CLIENTB\shortcut.lnk
etc.
There's about 100 clients that I have to get their links and I don't want to do it manually (each month).
Here is the error that I get upon trying to run this script:
Get-ChildItem : The specified path, file name, or both are too long. The fully
qualified file name must be less than 260 characters, and the directory name must
be less than 248 characters.
At D:\Scripts\scott_testing\GetShortcutTarget_edit1.ps1:8 char:18
+ $Shortcuts = Get-ChildItem -Recurse "F:\Connect" -Include *.lnk
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ReadError: (F:\Connect\CLIENTA\briefs\FILENAME:String) [Get-ChildItem], PathTooLongException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand
It is going 'inside' of the link and trying to find shortcuts on another server.

I can't reproduce. All the targets are probably found.
The results shown in the console by the $output-line should show everything as it should be. If not, update the question with the actual output, the desired output.
The only error I see here is that you try to save CSV-objects using output (text) redirection. That would only return the string-representation of the objects, which is not CSV. In this situation it doesn't output anything when I try it because $output is an array of objects that return nothing when the ToString() method is called.
Replace:
ECHO "$Output" >> $varCSVFile
With:
$Output | Select ShortcutName, ShortcutFull, ShortcutPath, Target | Export-CSV -Path $varCSVFile -NoTypeInformation
Sample output:
"ShortcutName","ShortcutFull","ShortcutPath","Target"
"WinSystem.lnk","C:\Users\frode\Desktop\test\WinSystem.lnk","C:\Users\frode\Desktop\test","C:\Windows\System"
"Lol.lnk","C:\Users\frode\Desktop\Lol.lnk","C:\Users\frode\Desktop","C:\Windows\System32\notepad.exe"
"Windows.lnk","C:\Users\frode\Desktop\Windows.lnk","C:\Users\frode\Desktop","\\localhost\c$\Windows"
"WinSystem32.lnk","C:\Users\frode\Desktop\WinSystem32.lnk","C:\Users\frode\Desktop","\\127.0.0.1\c$\Windows\System32"
UPDATE If you want it do a recursive search you could try something like this. Be aware that the target of the "second-level" shortcut (ex \\server\share\shortcutb.nk might have c:\temp as a target which means you'll get a local path and not an UNC for the remote computer (see MyEnd.lnk in sample output below).
Warning: This could easily result in a infinite loop (circular referencing) or long running search (because of recursive search).
function Get-StartMenuShortcuts ($path) {
$Shortcuts = Get-ChildItem -Path $path -Recurse -Include *.lnk
#$Shortcuts = Get-ChildItem -Recurse "D:\Scripts\scott_testing" -Include *.lnk
$Shell = New-Object -ComObject WScript.Shell
foreach ($Shortcut in $Shortcuts)
{
$Properties = #{
ShortcutName = $Shortcut.Name;
ShortcutFull = $Shortcut.FullName;
ShortcutPath = $shortcut.DirectoryName
Target = $Shell.CreateShortcut($Shortcut).targetpath
}
Get-StartMenuShortcuts -path $Properties.Target
New-Object PSObject -Property $Properties
}
[Runtime.InteropServices.Marshal]::ReleaseComObject($Shell) | Out-Null
}
$output = Get-StartMenuShortcuts -path "F:\Connect"
Example output:
"ShortcutName","ShortcutFull","ShortcutPath","Target"
"WinSystem.lnk","C:\Users\frode\desktop\test\WinSystem.lnk","C:\Users\frode\desktop\test","C:\Windows\System"
"MyEnd.lnk","\\127.0.0.1\c$\EFI\MyEnd.lnk","\\127.0.0.1\c$\EFI","C:\Users\frode\Desktop\TheEnd"
"EFI.lnk","C:\Users\frode\desktop\EFI.lnk","C:\Users\frode\desktop","\\127.0.0.1\c$\EFI"
"Lol.lnk","C:\Users\frode\desktop\Lol.lnk","C:\Users\frode\desktop","C:\Windows\System32\notepad.exe"
If you want to only get the deepest level, you should add a "level"-counter to each object that increases for each recursion call and then keep only the highest ones etc. It might get complicated depending on you needs so that would require a separate detailed question.

I found a command that will work in command prompt, but never seemed to work with powershell:
DIR /AL /S F:\Connect
It took a while to run... but it did.
Also, I found a program that did it in like 2 seconds:
http://sumtips.com/2012/10/find-symbolic-links-ntfs-junction-points-windows.html
I was trying to find the 'symbolic links' ... which I was stating targets.

Related

Powershell capture first filename from a folder

Newbie to powershell
I need to capture first file name from a directory. However my current script captures all file names. Please suggest changes to my code below.
# Storing path of the desired folder
$path = "C:\foo\bar\"
$contents = Get-ChildItem -Path $path -Force -Recurse
$contents.Name
The result is following
test-01.eof
test-02.eof
test-03.eof
i just want one file (any) from this list. So expected result should be
test-01.eof
You could use Select-Object with the -first switch and set it to 1
$path = "C:\foo\bar\"
$contents = Get-ChildItem -Path $path -Force -Recurse -File | Select-Object -First 1
I've added the -File switch to Get-ChildItem as well, since you only want to return files.
$path = "C:\foo\bar\"
$contents = Get-ChildItem -Path $path -Force -Recurse
$contents # lists out all details of all files
$contents.Name # lists out all files
$contents[0].Name # will return 1st file name
$contents[1].Name # will return 2nd file name
$contents[2].Name # will return 3rd file name
The count starts from 0. So $contents here is an array or a list and whatever integer you mention in [] is the position of the item in that array/list. So when you type $contents[9], you are telling powershell that get the 9th item from the array $contents. This is how you iterate through a list. In most programming languages the count begins from 0 and not 1. It is a bit confusing for a someone who is entering the coding world but you get used to it.
Please use below command which is simple and helpful. Adding recurse will only put slight load on the machine or powershell (when the code is huge and it has been used somewhere)
Storing path of the desired folder
$path = "C:\foo\bar\"
$contents = Get-ChildItem -Path $path | sort | Select-Object -First 1
$contents.Name
Output Will be as as expected:
test-01.eof
Select-Object -First will select each object (or row) and provide first row data as an output if you put as 1

Get-ChildItem can't find one specific directory?

I am writing a PowerShell script which is supposed to take a look at a directory, sort the children by name (numbered names) and check if there's a specific file inside. If there is, it's supposed to be copied somewhere, if not it's supposed to look at the next one. This is my code so far:
#[...]
$notExist = $true
#$LatestCiClient = [some directory from earlier in the script]
$buildDirectories = Get-ChildItem -Path $LatestCiClient | Sort Name -Descending
while ($notExist) {
$currentDir = $buildDirectories | Select-Object -First 1
$assembliesDir = Get-ChildItem -Path $currentDir.FullName -Include Desktop-Assemblies #Breakpoint
$script:exe = Get-ChildItem -Path $assembliesDir -Include SomeFile.exe | Select -First 1
if ($Script:exe.Exists) {
$notExist = $false
} else {
if ($buildDirectories.Count -gt 0) {
$buildDirectories = $buildDirectories | Select -Skip 1
} else {
$script:NoneFound = $true
$script:notExist = $false
}
}
}
#[more Powershell that is supposed to copy $script:exe]
I am getting the numbered directories ($buildDirectories), in the debugger I see the whole list.
I enter the while block (breakpoint is set at "#Breakpoint"), select the first directory to check ($currentDir`, which is again there and correct) and look for a folder called "Desktop-Assemblies".
I am looking at it, in the Explorer, right now, the folder is there, it's filled, it's not hidden (it is read-only but that shouldn't matter?), I am not doing anything I haven't done several times in the script - nothing. $assembliesDir is empty.
I tried using "Desktop-Assemblies", I tried Desktop*, I tried without the -Include . If I use $currentDir it says
Cannot find path [WeirdPath] because it doesn't exist
Weird Path being the FolderName of my $currentDir but the rest of the path is C:\Users\MyUserName.
If I use $currentDir.FullName it finds all the directories, INCLUDING the one I am looking for. I should probably add that the whole directory that is being searched is on another computer, it's a network drive.
Did you use this?
Get-ChildItem -Path $currentDir.FullName | Where-Object {$_.Name -eq 'Desktop-Assemblies'}

How to get Get-ChildItem to handle path with non-breaking space

I have the following code that works for most files. The input file (FoundLinks.csv) is a UTF-8 file with one file path per line. It is full paths of files on a particular drive that I need to process.
$inFiles = #()
$inFiles += #(Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv")
foreach ($inFile in $inFiles) {
Write-Host("Processing: " + $inFile)
$objFile = Get-ChildItem -LiteralPath $inFile
New-Object PSObject -Prop #{
FullName = $objFile.FullName
ModifyTime = $objFile.LastWriteTime
}
}
But even though I've used -LiteralPath, it continues to not be able to process files that have a non-breaking space in the file name.
Processing: q:\Executive\CLC\Budget\Co  2018 Budget - TO Bob (GA Prophix).xlsx
Get-ChildItem : Cannot find path 'Q:\Executive\CLC\Budget\Co  2018 Budget - TO Bob (GA Prophix).xlsx'
because it does not exist.
At ListFilesWithModifyTime.ps1:6 char:29
+ $objFile = Get-ChildItem <<<< -LiteralPath $inFile
+ CategoryInfo : ObjectNotFound: (Q:\Executive\CL...A Prophix).xlsx:String) [Get-ChildItem], ItemNotFound
Exception
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
I know my input file has the non-breaking space in the path because I'm able to open it in Notepad, copy the offending path, paste into Word, and turn on paragraph marks. It shows a normal space followed by a NBSP just before 2018.
Is PowerShell not reading in the NBSP? Am I passing it wrong to -LiteralPath? I'm at my wit's end. I saw this solution, but in that case they are supplying the path as a literal in the script, so I can't see how I could use that approach.
I've also tried: -Encoding UTF8 parameter on Get-Content, but no difference.
I'm not even sure how I can check $inFile in the code just to confirm if it still contains the NBSP.
Grateful for any help to get unstuck!
Confirmed that $inFile has NBSP
Thank you all! As per #TheMadTechnician, I have updated the code like this, and also reduced my input file to only the one file having a problem.
$inFiles = #()
$inFiles += #(Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" -Encoding UTF8)
foreach ($inFile in $inFiles) {
Write-Host("Processing: " + $inFile)
# list out all chars to confirm it has an NBSP
$inFile.ToCharArray()|%{"{0} -> {1}" -f $_,[int]$_}
$objFile = Get-ChildItem -LiteralPath $inFile
New-Object PSObject -Prop #{
FullName = $objFile.FullName
ModifyTime = $objFile.LastWriteTime
}
}
And so now I can confirm that $inFile in fact still contains the NBSP just as it gets passed to Get-ChildItem. Yet Get-ChildItem says the file does not exist.
More I've tried:
Same if I use Get-Item instead of Get-ChildItem
Same if I use -Path instead of -LiteralPath
Windows explorer and Excel can deal with the file successfully.
I'm on a Windows 7 machine, Powershell 2.
Thanks again for all the responses!
It's still unclear why Sandra's code didn't work: PowerShell v2+ is capable of retrieving files with paths containing non-ASCII characters; perhaps a non-NTFS filesystem with different character encoding was involved?
However, the following workaround turned out to be effective:
$objFile = Get-ChildItem -Path ($inFile -replace ([char] 0xa0), '?')
The idea is to replace the non-breaking space char. (Unicode U+00A0; hex. 0xa) in the input file path with wildcard character ?, which represents any single char.
For Get-ChildItem to perform wildcard matching, -Path rather than -LiteralPath must be used (note that -Path is actually the default if you pass a path argument positionally, as the first argument).
Hypothetically, the wildcard-based paths could match multiple files; if that were the case, the individual matches would have to be examined to identify the specific match that has a non-breaking space in the position of the ?.
Get-ChildItem is for listing children so you would be giving it a directory, but it seems you are giving it a file, so when it says it cannot find the path, it's because it can't find a directory with that name.
Instead, you would want to use Get-Item -LiteralPath to get each individual item (this would be the same items you would get if you ran Get-ChildItem on its parent.
I think swapping in Get-Item would make your code work as is.
After testing, I think the above is in fact false, so sorry for that, but I will leave the below in case it's helpful, even though it may not solve your immediate problem.
But let's take a look at how it can be simplified with the pipeline.
First, you're starting with an empty array, then calling a command (Get-Content) which likely already returns an array, wrapping that in an array, then concatenating it to the empty one.
You could just do:
$inFiles = Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv"
Yes, there is a chance that $inFiles will contain only a single item and not an array at all.
But the nice thing is that foreach won't mind one bit!
You can do something like this and it just works:
foreach ($string in "a literal single string") {
Write-Host $string
}
But Get-Item (and Get-ChildItem for that matter) accept pipeline input, so they accept multiple items.
That means you could do this:
$inFiles = Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" | Get-Item
foreach ($inFile in $inFiles) {
Write-Host("Processing: " + $inFile)
New-Object PSObject -Prop #{
FullName = $inFile.FullName
ModifyTime = $inFile.LastWriteTime
}
}
But even more than that, there is a pipeline-aware cmdlet for processing items, called ForEach-Object, to which you pass a [ScriptBlock], in which $_ represents the current item, so we could do it like this:
Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" |
Get-Item |
ForEach-Object -Process {
Write-Host("Processing: " + $_)
New-Object PSObject -Prop #{
FullName = $_.FullName
ModifyTime = $_.LastWriteTime
}
}
All in one pipeline!
But further, you're creating a new object with the 2 properties you want.
PowerShell has a nifty cmdlet called Select-Object which takes an input object and returns a new object containing only the properties you want; this would make for a cleaner syntax:
Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" |
Get-Item |
Select-Object -Property FullName,LastWriteTime
This is the power of the the pipeline passing real objects from one command to another.
I realize this last example does not write the processing message to the screen, however you could re-add that in if you wanted:
Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" |
Get-Item |
ForEach-Object -Process {
Write-Host("Processing: " + $_)
$_ | Select-Object -Property FullName,LastWriteTime
}
But you might also consider that many cmdlets support verbose output and try to just add -Verbose to some of your existing cmdlets. Sadly, it won't really help in this case.
One final note, when you pass items to the filesystem cmdlets via pipeline, the parameter they bind to is in fact -LiteralPath, not -Path, so your special characters are still safe.
I just run into the same issue. Looks like get-childitem ak gci expects the path in unicode (UTF-16). So either convert the csv file into unicode or convert the lines that include the path as unicode within your script.
Testet on PS 5.1.22621.608

Get-ChildItem -force reports "Access Denied" on My Documents folder and other junction points

I have a script that I wrote that replaces files. I pass params to it for the name of the file, and the base location to search from. The worker lines are:
$SubLocations = Get-ChildItem -Path $Startlocation -Recurse -include $Filename -Force |
Where { $_.FullName.ToUpper().contains($Filter.ToUpper())}
I set $Startlocation to "C:\Users", however, I am getting access denied when trying to recurse through other users folders. I'm full admin on the machine, and I have already tried running powershell as admin. I can access all the files via Windows explorer with no issue. Any idea?
Get-ChildItem : Access to the path 'C:\Users\jepa227\Documents\My Music' is denied.
At C:\Users\krla226\Google Drive\Documents\PowerShell\Replace-File.ps1:35 char:46
+ $SubLocations = Get-ChildItem <<<< -Path $Startlocation -Recurse - include $Filename -Force |
+ CategoryInfo : PermissionDenied: (C:\Users\jepa227\Documents\My Music:String) [Get-ChildItem], Una
uthorizedAccessException
+ FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
UPDATE
While I was unable to get it working via GCI, I was able to use WMI to solve my problem. For those interested:
$SubLocations = Get-WmiObject -Class cim_datafile -Filter "fileName = '$filename' AND Extension = '$extension'" |
Where { $_.Name.ToUpper().contains($Filter.ToUpper()) }
I was able to reproduce this on a Windows 7 machine with the following command logged in as an admin user named "admin", running powershell with elevated privileges, and UAC disabled:
get-childitem "c:\users\Admin\my documents"
and
cd "c:\users\admin\my documents"
get-childitem
Based on the article here, it looks like My Documents, My Music, etc., are defined as junction points for backwards-compatibility with pre-Vista software. Powershell doesn't natively do well with junction points. It seems like there are a couple options here:
1) Remove the -force from the Get-ChildItem command. This is likely your best bet.
get-childitem c:\users -recurse
works without error and skips junction points and system directories like AppData.
Editor's note: Omitting -Force does solve the immediate problem, but invariably skips all hidden items, not just the hidden junction points that cause the access-denied errors.
2) If you absolutely need to use the -Force for some reason, you could programmatically recurse each subdirectory, skipping junction points. This article describes the mechanism to identify junction points. A skeleton of this in a .ps1 script file might look like:
Param( [Parameter(Mandatory=$true)][string]$startLocation )
$errorActionPreference = "Stop"
function ProcessDirectory( $dir )
{
Write-Host ("Working on " + $dir.FullName)
# Work on the files in this folder here
$filesToProcess = ( gci | where { ($_.PsIsContainer -eq 0) } ) # and file matches the requested pattern
# process files
$subdirs = gci $dir.FullName -force | where {($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq 0 -and ($_.PsIsContainer -eq 1) -and (![string]::IsNullOrEmpty($_.FullName))}
foreach( $subdir in $subdirs )
{
# Write-Host( $subdir.Name + ", " + $subdir.FullName )
if ( $subdir -ne $null )
{
ProcessDirectory -dir $subdir
}
}
}
$dirs = get-childitem $startLocation -force
$dirs | foreach { ProcessDirectory -dir $_ }
mcating's helpful answer explains the problem well.
The quick fix he suggests is to omit -Force, which works, because PowerShell ignores hidden items unless -Force is used, and these system-defined junction points do have the Hidden attribute (alongside the ReparsePoint and System attributes).
If you do need -Force in order to process hidden items in general and only want to ignore these system-defined junction points, you can use Get-ChildItem's -Attributes parameter as follows:
Get-ChildItem -Force -Recurse -Attributes !Hidden, !System, !ReparsePoint
The -Attributes value excludes all items that have all of the following attributes set: Hidden, System, ReparsePoint, which is true of all system-defined junction points.
While it is technically possible to create your own junction points (or symbolic links) with these attributes, this is unlikely to occur in practice.

(Powershell) Loop to delete files from an FTP Location

Good morning!
I have made it to the last (and rather pivotal) stage in my script, which is looping to delete files from a directory. I'm not going to pretend I'm knowledgeable at Powershell (far from it), so I'm sort-of chopping up blocks of code I find on the net, improvising and hoping it works.
I'm hoping someone can decipher what I'm trying to do here and see what I'm doing wrong!
# Clear FTP Directory
$DelLoop=1
$server = "www.newsbase.com"
$dir = "/usr/local/tomcat/webapps/newsbasearchive/monitors/asiaelec/"
"open $server
user Canttell Youthis
binary
cd $dir
" +(
For ($DelLoop=1; $DelLoop -le 5; 5)
{
$FileList[$DelLoop] | %{ "delete ""$_""`n" }
$DelLoop++
})| ftp -i -in
I know that the 'Open Connection' portion works, it's just the loop. It just keeps complaining about misplaced operators, and when I fix those, it doesn't throw up any errors - but it doesn't do anything either.
I spent the best part of 4 hours researching this yesterday, and I'm hoping one of you guys can help me.
Thanks in advance!
ADDENDUM:
Here is more of the code, as requested:
# Clear existing .htm file to avoid duplication
Get-ChildItem -path ".\" -recurse -include index.jsp | ForEach-Object {
Clear-Content "index.jsp"
}
# Set first part of .JSP Body
$HTMLPart1="</br><tr><td colspan=9 align=center><p style=""font-family:Arial"">Here are the links to the last 3 AsiaElec PDFs:</br><ul>"
# Recurse through directory, looking for 3 most recent .PDF files 3 times
$Directory="C:\PDFs"
$HTMLLinePrefix="<li><a style=""font-family:Arial""href="""
$HTMLLineSuffix="</a></li>"
$HTMLLine=#(1,2,3,4)
$Loop=1
$PDF=#(1,2,3,4)
Get-ChildItem -path $Directory -recurse -include *.pdf | sort-object -Property LastWriteTime -Descending | select-object -First 3 | ForEach-Object {
$PDF[$Loop]=$_.name
$HTMLLine[$Loop]=$HTMLLinePrefix + $_.name + """>" + $_.name + $HTMLLineSuffix
$Loop++
}
# Final .JSP File Assembly
Get-Content "header.html" >> "index.jsp"
$HTMLPart1 >> "index.jsp"
$LineParse=""
$Loop2=1
For ($Loop2=1; $Loop2 -le 3; 3)
{
$HTMLLine[$Loop2] >> "index.jsp"
$Loop2++
}
Get-Content "tail.html" >> "index.jsp"
# Prepare File List
$FileList=#(1,2,3,4,5)
$FileList[2]=$PDF[2]
$FileList[3]=$PDF[3]
$FileList[4]="index.jsp"
# Clear FTP Directory
$DelLoop=1
$server = "www.newsbase.com"
$dir = "/usr/local/tomcat/webapps/newsbasearchive/monitors/asiaelec/"
"open $server
user derek bland1ne
binary
cd $dir
" +(
For ($DelLoop=1; $DelLoop -le 5; 5)
{
$FileList[$DelLoop] | %{ "delete ""$_""`n" }
$DelLoop++
})| ftp -i -in
This isn't all of it, but I believe it contains all the relevant info.
Your $dir path looks like you're on a unix system so this may be a little different, but all you need to do is change your final loop a little bit:
For ($DelLoop=1; $DelLoop -le 5; $DelLoop++)
{
$FileList[$DelLoop] | % { rm $FileList[$DelLoop] }
}
This is assuming that $FileList contains the files you want to delete and not only (what I'm guessing are dummy) numbers. I also suggest that you download the Module that #Graimer mentions and then put it in WindowsPowerShell > Modules > %ModuleFolder% > %Module.psm1% and import it from your profile.
You can then just use PS> Remove-FTPItem -Path "/myFolder" -Recurse to remove your FTP stuff. Making your life easier.
Tweaking the solution to this post may also help Upload files with FTP using PowerShell
e.g:
Using $ftp.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile to delete the file,
and $response = $ftp.GetResponse() to find out if things went smoothly.
EDIT
Wrote this function after doing a little bit of research from here http://social.msdn.microsoft.com/forums/en-US/netfxnetcom/thread/17a3abbc-6144-433b-aadd-1f776c042bd5 and adapting the code from the Accepted Answer in the above link as well as the module #Graimer talked about.
function deleteFTPSide
{
Param(
[String] $ftpUserName = "muUserName",
[String] $ftpDomain = "ftp.place.com", # Normal domains begin with "ftp" here
[String] $ftpPassword = "myPassword",
[String] $ftpPort = 21, # Leave as the default FTP port
[String] $fileToDelete = "folder.domain.com/subfolder/file.txt"
)
# Create the direct path to the file you want to delete
[String] $ftpPath = "ftp://"+"$ftpUserName"+":"+"$ftpPassword#$ftpDomain"+":"+"$ftpPort/$fileToDelete"
# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create($ftpPath)
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile
$ftp.Credentials = new-object System.Net.NetworkCredential($ftpUserName,$ftpPassword)
$ftp.UseBinary = $true
$ftp.UsePassive = $true
$response = [System.Net.FtpWebResponse]$ftp.GetResponse()
$response.Close()
}
While, admittedly, not one of the most elegant solutions written, I've tested it and it works at deleting a specified file off an FTP server.