PowerShell script - Converting PDFs to TIFs using Ghostscript - powershell

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

Related

For loop with list not working as expected Powershell

I'm trying to create a powershell script which checks a log file for lines of text and if the line exists restarts a service and resets/archives the log. I got it working before with 1 "checkstring" if you will, but I've been struggling to get it to work with a list of strings. Could anyone help me figure out where I'm going wrong?
This is the code I'm currently using:
$serviceName = "MySQL80"
$file = "test.txt"
$pwd = "C:\tmp\"
$checkStrings = New-Object System.Collections.ArrayList
# Add amount of checkstrings
$checkStrings.add("Unhandled error. Error message: Error retrieving response.")
$checkStrings.add("Unhandled error. Error message: Error retrieving response. Second")
$logName = "ServiceCheck.log"
$backupFolder = "Archive"
$logString = (Get-Date).ToString("ddMMyyyyHHmmss"), " - The service has been reset and the log moved to backup" -Join ""
Set-Location -Path $pwd
if(Test-Path -Path $file) {
if(Test-Path -Path $backupFolder) {
} else {
New-Item -Path $pwd -Name $backupFolder -ItemType "director"
}
foreach ($element in $checkStrings) {
$containsWord = $fileContent | %{$_ -match $element}
if ($containsWord -contains $true) {
Restart-Service -Name $serviceName
$backupPath = $pwd, "\", $backupFolder, "\", $date, ".log" -join ""
$currentFile = $pwd, "\", $file -join ""
Copy-Item $currentFile -Destination $backupPath
Get-Content $currentFile | select-string -pattern $checkString -notmatch | Out-File $currentFile
if(Test-Path -Path $logName) {
Add-Content $logName $logString
} else {
$logString | Out-File -FilePath $logName
}
}
}
}

Unable to run batch file from powershell script when it is a scheduled task

I am trying to run a batch file from a powershell script that is a scheduled task. The script sets up a filewatcher and in the action block it calls a batch file using start-process. If I run the action block as a script it works correctly. If I run the whole powershell script from Visual Studio Code, it works correctly. When I schedule the script as a task, the batch file doesn't run. The task is set to run under my account, I am a local administrator and I run it with highest privileges. Get-Executionpolicy returns Remotesigned. The task action block starts powershell with the parameters '-noexit -file "C:\Users\wheckle\Documents\CTA\Projects\Test Automation\windowsTest\watcher\newwatcher.ps1" -ExecutionPolicy Bypass.
I use the -Wait option on the start-process cmdlet. It waits from Visual Studio Code; but, it doesn't wait for the command to finish as a task.
$systemBase = "C:\Users\auser\Documents\CTA\Projects\Test Automation\windowsTest\"
$driverFile = $systemBase + "Generate\Driver\chromedriver.exe"
$logfileName = "TestAutomation.log"
$requestFile = "TestRequest.txt"
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path= ($systemBase+"dropfile")
$watcher.EnableRaisingEvents = $true
$watcher.IncludeSubdirectories = $true
$action =
{
if ($event.SourceEventArgs.ChangeType -eq 'Created') {
$appFile = ($event.SourceEventArgs.FullPath | split-path -Parent | split-path -Leaf)
$dropBase = $systemBase + "dropfile\" + $appFile +"\"
# check for log file
if (!(Test-Path -Path ($systemBase + $logfileName) -PathType "Leaf")) {
new-item -Path ($systemBase + $logfileName) -ItemType "File"
}
# Log Starting Project
"Now Starting the Job for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff") | Out-File -FilePath ($systemBase + $logfileName) -Append
Get-ExecutionPolicy | Out-File -FilePath ($systemBase + $logfileName) -Append
# Check for group and email files
if ((Test-Path -Path ($dropBase + $requestFile) -PathType "Leaf")) {
"Executing for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff") | Out-File -FilePath ($systemBase + $logfileName) -Append
# Create execution directory for job
if (!(Test-Path -Path ($systemBase + "Results\" + $appFile))) {
$resultsDir = new-item -Path ($systemBase+ "Results\" +$appFile) -ItemType "directory"
} else {
$resultsDir = Get-Item -Path ($systemBase+ "Results\" +$appFile)
}
"Creating project dir for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff") | Out-File -FilePath ($systemBase + $logfileName) -Append
#Create directory for job
$projectDir = new-item -Path ($resultsDir.FullName+"\"+(Get-Date -format "MM-dd-yyyy-HH-mm.fff")) -ItemType "directory"
#Copy jar file into executable
$jarFile = $systemBase + "Generate\" +$appfile+"\JarFile"
$jarFiles = Get-ChildItem -Path $jarFile
if (( $null -eq $jarFiles) -or ($jarFiles.count -eq 0)) {
(Get-Date -format "MM-dd-yyyy HH:mm ")+ "Exiting because of missing jar file for " + $appFile | Out-File -FilePath ($systemBase + $logfileName) -Append
Return 0
}
Copy-Item -Path $jarFiles[0].FullName -Destination $projectDir
# Create bat file
$batFile = New-Item -Path $projectDir.FullName -Name "run-automation.bat" -ItemType "file"
#create execute line
$batString = '"%JAVA_HOME%\bin\java" -jar "'+$projectDir + "\" + $jarFiles[0].Name+'" '
$batString += Get-Content -Path ($dropBase + $requestFile) -TotalCount 1
#add additional lines
$batDir = $systemBase + "Generate\" + $appFile +"\batfile"
if (Test-Path -Path ($batDir)) {
if (Test-Path -Path ($batDir+"preBat.txt")) {
Get-Content -Path ($batDir+"preBat.txt") | Set-Content -Path $batFile.FullName
}
$batString | Out-File -FilePath $batFile.FullName -Append
if (Test-Path -Path ($batDir+"preBat.txt")) {
Get-Content -Path ($batDir+"postBat.txt") | Add-Content -Path $batFile.FullName
}
} else {
$batString | Out-File -FilePath $batFile.FullName
}
# add config directory
$configDir = New-Item -Path $projectDir -Name "config" -ItemType "directory"
Copy-Item -Path $driverFile -Destination $configDir.FullName
Copy-Item -Path ($systemBase+"Generate\"+$appFile+"\config\*") -Destination $configDir.FullName
$emailStr = "toEmail="
Write-Host
if (Test-Path -Path ($configDir.FullName+"\testconfig.properties")) {
$emailStr += (Get-Content -Path ($dropBase+$requestFile) -TotalCount 2)[-1]
$emailStr | Add-Content -Path ($configDir.FullName+"\testconfig.properties")
} else {
$emailStr += (Get-Content -Path ($dropBase+$requestFile) -TotalCount 2)[-1]
$emailStr | Set-Content -Path ($configDir.FullName+"\testconfig.properties")
}
Set-Location $projectDir
$exeResults = new-item -Path $projectDir.FullName -Name "ExcutionResults.txt" -ItemType "file"
"Starting Batch Process for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff")+ " file "+ $batFile.FullName| Out-File -FilePath ($systemBase + $logfileName) -Append
Start-Process -FilePath $batFile.FullName -Wait -NoNewWindow | Out-File -FilePath $exeResults.FullName
"Ended Batch Process for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff") | Out-File -FilePath ($systemBase + $logfileName) -Append
Remove-Item -Path ($dropBase + $requestFile)
} else {
"Invalid file for "+$appFile + " at "+ (Get-Date -format "MM-dd-yyyy-HH-mm.fff") | Out-File -FilePath ($systemBase + $logfileName) -Append
}
}
}
Register-ObjectEvent -InputObject $watcher -EventName Created -Action $action -SourceIdentifier FSCreate1

move multiple local folder and their content to remote server through sftp protocol with powershell

I want to move specific files from a local directory to a folder of a remote server.
The files are generated in folders inside the main directory.
The names of the folders are the actual dates and inside them there are files.
In some cases the names of the files are the same but they are in separate folders.
For example:
\main\
\201809271020\a20180927.txt
\201809271120\a20180927.txt
\201809271220\a20180927.txt
I have to move all of the folders and files under the main folder to the remote location.
I've tried it with WinSCP powershell module, but it works on files only. I couldn't move folders with it.
Any helps appreciated.
Regards
wolfnlight
Ok, I create a script, I hope it will not so bad. :)
[xml]$config = Get-Content "C:\Script\config.xml" -ErrorAction Stop
[string]$serverName = $config.Configuration.HostName
[string]$UserName = $config.Configuration.UserName
[string]$localPath = $config.Configuration.LocalPath
[string]$remotePath = $config.Configuration.RemotePath
[string]$logFile = $config.Configuration.LogFile
[string]$SshHostKeyFingerprint = $config.Configuration.SshHostKeyFingerprint
[string]$SshPrivateKeyPath = $config.Configuration.SshPrivateKeyPath
[string]$wildcard = $config.Configuration.WildCard
Import-Module -Name "C:\Program Files (x86)\WindowsPowerShell\Modules\WinSCP" -Force
############# functions for log ##########################################
function InfoToLog {
return "$(get-date -Format "yyyy.MM.dd HH:mm:ss") - [INFO] - "
}
function WarningToLog {
return "$(get-date -Format "yyyy.MM.dd HH:mm:ss") - [WARNING] - "
}
function ErrorToLog {
return "$(get-date -Format "yyyy.MM.dd HH:mm:ss") - [ERROR] - "
}
############ Uploader ####################################################
function Data-Uploader {
param (
$i = 0
)
foreach ($localFile in $localFiles) {
$localDirName = $localFiles[$i].FullName.Substring(38,15)
$localDir = $localPath + $localDirName
$remoteDir = $remotePath + $localDirName
$GetLocalDir = Get-ChildItem -Path $localDir -Recurse -Include "export.end" -ErrorAction Stop
if (($GetLocalDir)) {
# target directory query
if (!(Test-WinSCPPath $session -Path $remoteDir)) {
$(InfoToLog) + $remoteDir + " not exist...creating" | Out-File $logFile -Append
New-WinSCPItem -WinSCPSession $session -Path $remoteDir -ItemType "directory" -Verbose -ErrorAction Stop
$(InfoToLog) + $remoteDir + " created" | Out-File $logFile -Append
}
else {
$(InfoToLog) + $remoteDir + " exists!" | Out-File $logFile -Append
}
$localFileName = $localFiles[$i].FullName
$remotefileName = $localFiles[$i].Name
# put files from local directory to remote directory - same name
if ($localFileName -like "*$localDir*") {
$localFile = "FileName: " + $localFile.Name + " - CreationTime: " + $localFile.CreationTime.GetDateTimeFormats('u') + "- Length(kB): " + $localFile.Length
$(InfoToLog) + $localFile | Out-File $logFile -Append
$(InfoToLog) + "Transfering $remotefileName ..." | Out-File $logFile -Append
Send-WinSCPItem -TransferOptions $TransferOptions `
-WinSCPSession $session `
-LocalPath "$localDir\$wildcard" `
-RemotePath $remoteDir -ErrorAction Stop -Verbose
$(InfoToLog) + "$remotefileName transfered." | Out-File $logFile -Append
$(InfoToLog) + "Archiving files..." | Out-File $logFile -Append
Move-Item -Path $localDir -Destination "C:\Script\Archive\" -Force -ErrorAction Stop -Verbose
$(InfoToLog) + "Archiving completed." | Out-File $logFile -Append
}
else {
$(InfoToLog) + "No file for transfer." | Out-File $logFile -Append
}
}
else {
$(WarningToLog) + "$localFile - waiting for export ended!" | Out-File $logFile -Append
}
$i++
}
}
################# process ######################################
try {
$(InfoToLog) + "Data_Uploader - version 1.2 - Starting script..." | Out-File $logFile -Append
# set user
$MyCredential = New-Object System.Management.Automation.PSCredential ($UserName, (new-object System.Security.SecureString))
# set session
$sessionOption = New-WinSCPSessionOption -Credential $MyCredential -HostName $serverName -Protocol sftp -SshHostKeyFingerprint $SshHostKeyFingerprint -SshPrivateKeyPath $SshPrivateKeyPath
$TransferOptions = New-WinSCPTransferOption -FileMask $wildcard -TransferMode Binary
# connecting
$session = New-WinSCPSession -SessionOption $sessionOption -ErrorAction Stop -SessionLogPath "C:\Script\MUK\Log\Muk_Uploader_session.log"
# session available
if ($session.Opened -eq $true) {
$(InfoToLog) + "Connected to $servername..." | Out-File $logFile -Append
# get local files
$localFiles = Get-ChildItem -Path $localPath -Recurse -ErrorAction Stop -Verbose -Attributes !Directory -Exclude "riport.end"
# existing files in local dir
if ($localFiles.Count -gt 0) {
$(InfoToLog) + $localFiles.Count +" files in $localPath :" | Out-File $logFile -Append
# upload files
Data-Uploader
}
else {
$(InfoToLog) + "No files in $localPath" | Out-File $logFile -Append
}
}
else {
$(ErrorToLog) + "$($_.Exception.Message)" | Out-File $logFile -Append
}
} # try
catch {
Write-Host -ForegroundColor Green "Error: $($_.Exception.Message)"
$(ErrorToLog) + "Message: $($_.Exception.Message)" | Out-File $logFile -Append
# session close
Remove-WinSCPSession -WinSCPSession $session -ErrorAction Stop
}
finally {
$(InfoToLog) + "End script!" | Out-File $logFile -Append
"$(get-date -Format "yyyy.MM.dd HH:mm:ss") - ***************************************************************************************************" | Out-File $logFile -Append
# session close
Remove-WinSCPSession -WinSCPSession $session -ErrorAction Stop
}
Any suggestions?

Powershell - Output to screen AND logfile

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
}
}

Run string from command line with parameters and switches using powershell

I have a powershell script that copies a file to a remote computer, and I need to execute it from a command line and with arguments/parameters.
Here is what I have...and I can't get it to work:
Get-Content C:/temp/list.txt |
ForEach-Object {
Try {
$source = "\\server\folder\my application 1.2.1.EXE"
$destination = "\\" + $_ + "\C$\temp\"
New-Item -Path $destination -ItemType Directory -Force
Copy-Item -path $source -Destination $destination -force | Out-Null
& "$_ +"\C:\temp\my application 1.2.1.EXE" Location=07 /s" ##| Out-Null
$status = "Success"
}
Catch {
$status = "Failed"
}
"$_, $status" | out-file -filepath c:\temp\restult1.csv -Append -Encoding ascii
}
I resolved it.
Get-Content C:/temp/list.txt |
ForEach-Object {
Try {
$source = "\\server\folder\my application 1.2.1.EXE"
$destination = "\\" + $_ + "\C$\temp\"
New-Item -Path $destination -ItemType Directory -Force
Copy-Item -path $source -Destination $destination -force | Out-Null
Invoke-Command -ComputerName $_ -ScriptBlock {
& cmd.exe /c "C:\temp\my application 1.2.1.EXE" Location=07 /s ##| Out-Null
}
$file = $destination + "my application 1.2.1.EXE"
Remove-Item $file -Force
$status = "Success"
}
Catch {
$status = "Failed"
}
"$_, $status" | out-file -filepath c:\temp\restult1.csv -Append -Encoding ascii
}