Trying to write to a log file assigned to a variable in PowerShell, like so-
Code:
$Time = Get-Date
$FileTimeStamp = (Get-Date -f MM-dd-yyyy_HH.mm.ss)
$ErrorLog | out-file $(".\Logs\" + $FileTimeStamp + "_PushLog.log") -append
"Script started at $Time" | out-file $ErrorLog -append
Compile error-
Out-File : Cannot bind argument to parameter 'FilePath' because it is null.
At C:\OSM\Scripts\FilePush\FilePush.ps1:56 char:37
+ "Script started at $Time" | out-file <<<< $ErrorLog -append
+ CategoryInfo : InvalidData: ( [Out-File], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileCommand
What am I doing wrong? Am I getting there? It's now correctly writing one file instead of two, but the log doesn't contain the string "Session started at $Time".
Code:
$Time = Get-Date
$FileTimeStamp = (Get-Date -f HH.mm.ss_MM-dd-yyyy)
$ErrorLog = out-file $(".\Logs\" + $FileTimeStamp + "_PushLog.log") -append
$ErrorLog = [io.path]::GetFileName("$ErrorLog.FullName")
"Session started at $Time" | out-file $ErrorLog -append
The whole point of what I'm trying to do is create a variable for an error file that I can reference when I want to output text to it. I only want log each time the script runs, but that seems to be an issue when I;'m appending the time to the file name. How do I work past this?
Bob answered the question but really didn't help provide a solution, so I'll add an answer.
The issue is that when you try to define your $ErrorLog variable you're overthinking it. You just need to create a string that defines where the file is located, not have all the Out-File and -Append on that line.
$Time = Get-Date
$FileTimeStamp = (Get-Date -f MM-dd-yyyy_HH.mm.ss)
$ErrorLog = ".\Logs\$FileTimeStamp_PushLog.log"
"Script started at $Time" | out-file $ErrorLog -append
You haven't defined $ErrorLog.
Related
I'm trying to run a powershell script on a shared mailbox (Exchange). when I run the script on my personal mailbox it works, altough when I change it to the share one I only get error messages.
$outlook = new-object -comobject outlook.application
$logfile = $PSScriptRoot + "\email.log"
$namespace = $outlook.GetNameSpace('MAPI')
$folder = $namespace.Folders.Item('shared.mailbox#company.com').Folders.Item('Inbox')
$folder_2 = $namespace.Folders.Item('shared.mailbox#company.com').Folders.Item('Deleted Items')
$date_check = (get-date).AddDays(-1) | Get-Date -UFormat "%m-%d-%Y"
$date_check_deleted_items = (get-date).AddDays(-2) | Get-Date -UFormat "%m-%d-%Y"
$emailToDelete = $folder.items | Where-Object { $_.ReceivedTime -lt $date_check; }
$emptyDeletedItems = $folder_2.items | Where-Object { $_.ReceivedTime -lt $date_check_deleted_items; }
Get-Date | Out-File $logfile -Append
"Amount of emails being deleted:" | Out-File $logfile -Append
$emailToDelete.Count | Out-File $logfile -Append
"Subject of Emails in the Inbox folder:" | Out-File $logfile -Append
$emailToDelete.subject | Out-File $logfile -Append
"Amount of emails being deleted from deleted items:" | Out-File $logfile -Append
$emptyDeletedItems.Count | Out-File $logfile -Append
"Subject of Emails in the Deleted Items folder folder:" | Out-File $logfile -Append
$emptyDeletedItems.subject | Out-File $logfile -Append
write-host "Emails received before" $date_check "(MM/dd/YYYY) will be deleted"
write-host "deleting emails in 5"
Start-Sleep -s 1
write-host "deleting emails in 4"
Start-Sleep -s 1
write-host "deleting emails in 3"
Start-Sleep -s 1
write-host "deleting emails in 2"
Start-Sleep -s 1
write-host "deleting emails in 1"
Start-Sleep -s 1
write-host "deleting" $emailToDelete.Count "emails"
#$EmailToDelete.Delete()
write-host $emptyDeletedItems.count "Emails to be deleted from the deleted items folder"
write-host "Emails received before" $date_check_deleted_items "(MM/dd/YYYY) will be deleted from that folder"
$emptyDeletedItems.Delete()
write-host $emailToDelete.count "Emails are deleted from the Inbox folder and" $emptyDeletedItems.count "Emails are deleted from the Deleted Items folder, application will close in 5 seconds"
Start-Sleep -s 5
I'm receiving the following errors:
The attempted operation failed. An object could not be found.
At C:\Users\username\Desktop\emails.ps1:7 char:1
+ $folder = $namespace.Folders.Item('shared.mailbox#company.com').Fold ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
The attempted operation failed. An object could not be found.
At C:\Users\username\Desktop\emails.ps1:9 char:1
+ $folder_2 = $namespace.Folders.Item('shared.mailbox#company.com').Fo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
Could you help me what am I doing wrong?
I'm trying to run a powershell script on a shared mailbox (Exchange)
Not exactly so. You are trying to automate Outlook with a shared mailbox. And the account is configured locally in Outlook. It seems you can't access it form a shared location.
Another aspect is that Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.
Read more about that in the Considerations for server-side Automation of Office article.
I am trying to write ALL the output to a logfile, and I seem to be doing something wrong. I also need the output on the screen.
Here is what I have so far:
# Log file time stamp:
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
# Log file name:
$LogFile = "EXPORTLOG_"+$LogTime+".log"
$database = "DB"
$schema = "dbo"
$table = "TableName"
foreach($line in Get-Content .\Alltables.txt) {
if($line -match $regex){
$bcp = "bcp $($database).$($schema).$($line) out $line.dat -T -c"
Invoke-Expression $bcp | Out-File $LogFile -Append -Force
}
}
When I want to write out the command to the logfile so I know which table is processed, I get an error:
Here is the code:
# Log file time stamp:
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
# Log file name:
$LogFile = "EXPORTLOG_"+$LogTime+".log"
$database = "DB"
$schema = "dbo"
$table = "TableName"
foreach($line in Get-Content .\Alltables.txt) {
if($line -match $regex){
$bcp = "bcp $($database).$($schema).$($line) out $line.dat -T -c" | Out-File $LogFile -Append -Force
Invoke-Expression $bcp | Out-File $LogFile -Append -Force
}
}
And the error:
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is null.
At C:\Temp\AFLAC\export.ps1:16 char:21
+ Invoke-Expression $bcp | Out-File $LogFile -Append -Force
+ ~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand
I am obviously not very good with Powershell and I please need your advise on how I should code this the best possible way.
Maybe the above way is completely wrong, I do appreciate your guidance.
Thank you
Try modifying your code to something like this:
foreach($line in Get-Content .\Alltables.txt) {
if($line -match $regex) {
$bcp_command = "bcp $database" + '.' + $schema '.' + $line + ' out ' + $line + '.dat -T -c')
Tee-Object -FilePath $LogFile -InputObject $bcp_command -Append
$bcp_results = Invoke-Expression $bcp_command
Tee-Object -FilePath $LogFile -InputObject $bcp_results -Append
}
}
In powershell if I run Get_Date by itself it will give me the correct date. But in my script when I run
"$computer" + "_Already_Had_Software_" + "(Get-Date)" | Out-File -FilePath "\\server\Install\Office2010\RemoteInstallfile.txt" -Append
It does not show the date but just says
_Already_Had_Software_Get-Date
Instead of showing the actual date.
Will someone please tell me where I may be going wrong?
You should be using "$(Get-Date)". Your string forgot the $ that tells powershell to execute it.
Alternates:
"${computer}_Already_Had_Software_$(Get-Date)"
"$computer" + "_Already_Had_Software_" + (Get-Date)
({0}_Already_Had_Software_{1} -f $computer, (Get-Date))
[String]::Join('_', ($computer, 'Already_Had_Software', (Get-Date)))
Use this :
$date = Get-Date -Format "yyyy-MM-dd --- hh-mm-ss-fff tt Zone K" | Out-String
"$computer" + "_Already_Had_Software_" + "$date" | Out-File -FilePath "\\server\Install\Office2010\RemoteInstallfile.txt" -Append
I am very new to PowerShell scripting. I am trying to overwrite an existing file with date and time in it's file name.
Here is what i'm using.
$LogName = "Security"
$EventID = 4725
$Date = ((get-date).addDays(-1))
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('MM-dd-yyyy_hh.mm.ss')
get-eventlog $LogName $EventID -after $Date | Export-CSV $Path -notypeinformation | Out-File -Filepath $Path -Append
However, upon running, it returns with an error that says
Out-File : The process cannot access the file because it is being used by another process
I hope you guys can help me with this. Thanks!
Try using ConvertTo-Csv not Export-CSV.
Get-EventLog $LogName $EventID -after $Date | ConvertTo-Csv -NoTypeInformation | Out-File -Filepath $Path -Append
The error is down to the fact that your trying to read and write to a file ($path) at the same time.
This will stop Export-CSV creating a file before you append to the same file, cutting out the error.
What am I missing here?
I'm getting this error:
ERROR converting File
E:\DocuTA\TIFs\06fef98e-e1c5-405e-93ea-c684ee7a856d.tif
nvoke-Expression : You must provide a value expression on the
right-hand side of the '-' operator. At E:\DocuTA\ConvPDFtoTIF.ps1:31
char:26 + $ret = invoke-expression <<<< -command $cmdline +
CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException +
FullyQualifiedErrorId :
ExpectedValueExpression,Microsoft.PowerShell.Commands.InvokeExpressionCommand
when running this script:
#recursively crawls the directory tree and converts pdf files to tif files
#compresses the images to a smaller file size.
$Now = get-date
$Days = "14"
$LastWrite = $Now.AddDays(-$Days)
$srcfolder = "E:\DocuTA\PDFs\"
$destfolder = "E:\DocuTA\TIFs\"
$convert = "& C:\Program Files (x86)\gs\gs9.16\bin\gswin32c.exe"
$filter = "*.pdf"
$dest_ext = "tif"
$arg1 = #(" -dNOPAUSE -dQUIET -r300x300 -sDEVICE=tiffg4 -dBATCH ")
$lfpath = "E:\DocuTA\Logs\"
$logfile = new-item -type file -name "PDF2TIFLog$(get-date -uformat '%Y%m%d%H%M%S').log" -path "$lfpath"
$elogfile = "E:\DocuTA\Logs\PDF2TIFErrorLog.log"
#-------------------------------------------------------------------
$count = 0
Write-Output "`nStarting ... ($Now)" | Out-File -Append $logfile
Try
{
foreach ($srcitem in $(Get-ChildItem $srcfolder -Include $filter -Recurse | Where-Object {$_.LastWriteTime -gt "$LastWrite"}))
{
$count++
$srcname = $srcitem.FullName
$partial = $srcitem.FullName.Substring($srcfolder.Length)
$destname = $destfolder+$partial
$destname = [System.IO.Path]::ChangeExtension($destname,$dest_ext)
$destpath = [System.IO.Path]::GetDirectoryName($destname)
$cmdline = "'"+$convert+"'"+"'"+$srcname+"'"+$arg1+ "'"+$destname+"'"
Write-Output "[$count] $cmdline" | Out-File -Append $logfile
$ret = invoke-expression -command $cmdline
Write-Output "[$count] OUTPUT: $ret" | Out-File -Append $logfile
Write-Output "[$count] processed file." | Out-File -Append $logfile
}
}
Catch
{
$Now | out-file -Append $elogfile
write-output "ERROR converting File $destname" | out-file -Append $elogfile
Write-Output $Error[0] | out-file -Append $elogfile
}
Finally
{
Write-Output "Finished processing files. Total: $count`n" | Out-File -Append $logfile
}
Looks like PowerShell doesn't like using - for switches, try using # instead