I have pieced this script together that unpacks rar files and sends an email when it has completed. I have been trying to understand how to parse the file name and use it as the subject line but come up short every time. I am very new to Powershell and would appreciate any help in understanding how to achieve this, here is the script.
##Unrar files in selected folder
cls
$parent = "\\NASBOX\Incoming\"
$unrarred = "\\NASBOX\unrared\"
$files = @()
$unrarpath = "C:\Users\NASbox\Documents\UnRAR.exe"
# Check unrar.exe default path.
if ((Test-Path -Path $unrarpath) -ne $true){
write-host "Unrar.exe not present in default unrar folder. Please verify"
break
}
# Recurse trough all folders, filter on .rar
Gci $parent -Recurse -Filter "*.rar" | % {
$files = $files + $_.FullName
}
# Start extract, using call parameter "&"
foreach ($f in $files) {
& "$unrarpath" x -y $f $unrarred
# In case of - delete rar parent folder
$folder = Split-Path -Path $f -Parent
if ($LASTEXITCODE -eq "0"){
Remove-item -Path $folder -Recurse
$email = 'xxxxxx@gmail.com'
$SMTPServer = 'smtp.gmail.com'
$SMTPPort = '587'
$Password = 'xxxxxxxxxxx'
$subject = 'Have just Unpacked a file'
$data = 'a download was unpacked '
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($email, $Password);
$smtp.Send($email, $subject, $data);
}
}
Hi Shane, have you tried simply including $_.FullName in the subject line? Example:
$subject = "Have just Unpacked a file $($_.FullName)"
Be sure to replace the outside single quotes with double quotes, as single quotes will interpret the text literally instead of as a variable. Also, the $($…) syntax is required because you’re referencing a property of the object inside a string. Just calling $.FullName without the extra $() will not work inside a string. You could also encase the file name in quotes like '$($.FullName)', which will still work because the outside quotes are double quotes.
$files now contain an array of ‘System.IO.FileInfo’ objects. So when you loop through those objects with ‘foreach ($f in $files)’ the $f variable will hold a single ‘System.IO.FileInfo’ object, with properties you can access:
$f.FullName # the full path of the file.
$f.Name # the file name
$f.Directory # The directory the file is in
Hi Guys, Thanks very much to all of you. Three examples of three ways to attack the problem and each works. I have learned more here in a few minutes than the whole time I have been playing with Powershell. Thanks for explaining what each code snippet does,it helps me understand how syntax changes the way the code works.