I have a pretty simple powershell script (to convert .xlsx files to .xls) like below:
$files = Get-ChildItem "C:\MyFolder\*.xlsx"
foreach ($file in $files) {
$Filepath = Get-Item -Path $file
$NewFilepath = Join-Path -path $Filepath.directory.fullname -ChildPath
"$($Filepath.basename).xls"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false #or false
$Excel.displayalerts = $false
$Workbook = $Excel.Workbooks.Open("$Filepath".fullname,
[Type]::Missing,$true)
$Workbook.SaveAs("$NewFilepath",56)
#https://technet.microsoft.com/en-us/library/ff730962.aspx
$Workbook.Close()
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
Remove-Variable Excel
Remove-Item $Filepath
}
If I run this script from powershell directly it works just as expected. I mean for each .xlsx file it creates a new .xls file and removes given .xlsx file.
But when I invoke it by SQL Agent all the .xlsx files are simply removed with no creation corresponding .xls files.
SQL Job step
Type: Powershell
Run as: SQL Server Agent service account (checked folder permissioned and is full control)
Command: powershell -File "C:\MyScripts\MyConvertToXls.ps1"
The job does not fail. But when I go to the step execution details I can see the following message:
Message
Executed as user: ServiceAccount. ...rors did not stop the script:
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'.
Correct the script and reschedule the job.
The error information returned by PowerShell is: 'Sorry, we couldn't find .
Is it possible it was moved, renamed or deleted? '
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'.
Correct the script and reschedule the job.
The error information returned by PowerShell is:
'At C:\MyScripts\MyConvertToXls.ps1:16 char:1 + $Workbook = $Excel.Workbooks.Open("$Filepath".fullname,[Type]::Missin ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], COMException '
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'.
Correct the script and reschedule the job.
The error information returned by PowerShell is: ' + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException '
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'.
Correct the script and reschedule the job. The error information returned by PowerShell is: ' '
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'.
Correct the script and reschedule the job.
The error information returned by PowerShell is: 'You cannot call a method on a null-valued expression. '
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'.
Correct the script and reschedule the job.
The error information returned by PowerShell is: 'At C:\MyScripts\MyConvertToXls.ps1:18 char:1 '
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'.
Correct the script and reschedule the job. The error information returned by PowerShell is: '+ $Workbook.SaveAs("$NewFilepath",56) '
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'.
Correct the script and reschedule the job.
The error information returned by PowerShell is: '+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ '
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'. Correct the script and reschedule the job.
The error information returned by PowerShell is: ' + CategoryInfo : InvalidOperation: (:) [], RuntimeException '
A job step received an error at line 1 in a PowerShell script. The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'.
Correct the script and reschedule the job. The error information returned by PowerShell is: ' + FullyQualifiedErrorId : InvokeMethodOnNull '
A job step received an error at line 1 in a PowerShell script. The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"'.
Correct the script and reschedule the job. The error information returned by PowerShell is: ' '
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'powershell -File "C:\MyScripts\MyConvertToXls.ps1"... Process Exit Code 0. The step succeeded.
A PowerShell job step type expects a script but it looks like you are specifying the OS command powershell -File "C:\MyScripts\MyConvertToXls.ps1" to invoke the script.
Try a Operating System (CmdExec) job step type to invoke the command. Alternatively, paste the script into the PowerShell job step instead of running the external script.
I had same error, and found this solution.
You need to create folder Desktop
C:\Windows\System32\config\systemprofile\Desktop for 32 bit machine
C:\Windows\SysWOW64\config\systemprofile\Desktop for 64 bit machine
It's amaizing but it works
Related
I tried with "Powershell" option and commands (both don't work):
Get-Item "*.csv" | Out-File "d:\tracking\$(get-date -f yyyyMMdd-hhmmss).txt"
"Get-Item """*.csv""" | Out-File """d:\tracking\$(get-date -f yyyyMMdd-hhmmss).txt""""
And tried with "CmdExec" option and command (it doesn't work):
powershell.exe -Command "Get-Item """*.csv""" | Out-File """d:\tracking\$(get-date -f yyyyMMdd-hhmmss).txt""""
But the last command runs ok on a separate cmd.exe window
and the following also runs ok inside the powershell:
Get-Item "*.csv" | Out-File "d:\tracking\$(get-date -f yyyyMMdd-hhmmss).txt"
They create a text file eg. "20220607-112233.txt" containing the directory listing of CSV files
However I can't get this command to work from within the Job Step
The step finishes with "Unable to run. Syntax error"
Ok, I found a solution:
I created a batch (.bat file) with the code inside block 2:
powershell.exe -Command "Get-Item """*.csv""" | Out-File """d:\tracking\$(get-date -f yyyyMMdd-HHmmss).txt""""
(I only changed the hh for HH, for 24 hours based time)
Then, I configured the Job Step to run the bat file (setting the option "cmdExec")
That's all
I don't know what was going on, directory permissions were ok, the command of code block #2 above even works if I execute it with xp_cmdshell
Used Sqlcmd function on PowerShell script for multiple SQL scripts execution to get the result as ssms output but through sqlcmd it's not throwing the error message or not able to write catch method if any SQL script has an error, please guide me how I can capture the error if any script has an error.
using Invoke-Sqlcmd command I am not able to capture the script execution output as SSMS has given after execution of any update or insert statement like "1 Rows affected" ,so I need to use sqlcmd command to execute the sql scripts and now all the scripts records are captured but on Invoke-sqlcmd command if any error in the sql scripts its going to the catch block and showing the error but when I am using SQLCMD if there is any error in SQL script it will not go to catch block it statys in the try block and continue .
So please help now how I can capture and move it to catch block or I can capture the error as I have done before using Invoke-SQLCMD command.
this is a continuation of this link :
Not getting ouput after successful execution of the SQL scripts through powershell
Here is my code block and it's not going to catch block :
Try
{
#$result = "Sqlcmd.exe -S $InstanceNAme -d $dbname -Q ""Insert into [DUR2_A].[dbo].[emp_info] values(1,'Ram','Kolkata')"""
#Invoke-Expression $result | Out-File filesystem::$ScriptOutPutpath$scriptfilesc$out
sqlcmd -S $InstanceNAme -i $scriptfiles1 -o $ScriptOutPutpath$scriptfilesc$out -m1
Move-Item filesystem::$scriptfiles1 filesystem::$Scriptbackuppath
}
catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
echo "Error for $scriptfilesc - $($_.Exception.Message)" | Out-File filesystem::$error_log$scriptfilesc$errorout
Send-MailMessage -from test#test.com -To IO-SD.GP.test#test.com -SmtpServer mailrelay.test.com -Subject "DUR Error" -Body "Script $scriptfilesc has not been executed becasue of Error Message $ErrorMessage.Kindly check the attachd script and error message" -Attachments filesystem::$error_log$scriptfilesc$errorout,filesystem::$scriptfiles1
Move-Item filesystem::$scriptfiles1 filesystem::$Scriptbackuppath
}
I've setup a SQL Server 2016 agent job that has 2 steps that is executed by the same service account, Step 1 executes an SSIS package that writes 2 files out to a share. Step 2 executes embedded powershell code that combines these 2 files into a single file and creates a file on that same share where the 2 files were created by SSIS. When I execute the job, Step 1, the SSIS package completes successfully and creates the 2 files on this share. But when Step 2 executes I get the error below. Just a point of info, when I run this script locally from my windows 10 box, I have no issues.
I guess my question is, if SSIS can execute successfully with the same service account can this be a permissions issue for powershell scripts? I'm not a server admin so if this is a stupid questions please forgive my ignorance. Any help/direction anyone can provide would be appreciated.
Message
Executed as user: XXX\sqlsvc02. The job script encountered the following errors. These errors did not stop the script: A job step received an error at line 12 in a PowerShell script. The corresponding line is 'Get-Content $pathCounts, $pathDetails | Set-Content $outFile'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Cannot find path '\xxx\shared\MonthlyReports\BoundPoliciesAddedAtFaultEndorsementWithin10Days_Counts.csv' because it does not exist. ' A job step received an error at line 12 in a PowerShell script. The corresponding line is 'Get-Content $pathCounts, $pathDetails | Set-Content $outFile'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Cannot find path '\xxx\shared\MonthlyReports\BoundPoliciesAddedAtFaultEndorsementWithin10Days_Details.csv' because it does not exist. '. Process Exit Code 0. The step succeeded.
Here is my powershell script:
# Define variables
$path = '\\xxx\shared\MonthlyReports'
$pathCounts = Join-Path -Path $path -ChildPath 'BoundPoliciesAddedAtFaultEndorsementWithin10Days_Counts.csv'
$pathDetails = Join-Path -Path $path -ChildPath 'BoundPoliciesAddedAtFaultEndorsementWithin10Days_Details.csv'
$date = Get-Date
$dateStr = $date.ToString("yyyyMM")
# Define combined file name
$outFile = Join-Path $path -ChildPath("BoundPoliciesAddedAtFaultEndorsementsWithin10Days_" + $dateStr + ".csv")
# Execute combine files code
Get-Content $pathCounts, $pathDetails | Set-Content $outFile
Here is an image of what Step #2 looks like:
On SQL Server 2016 I have setup a job that executes a powershell script that resides on a remote app server. When I execute the powershell script via the app server using the Powershell ISE app my script works without issue. When I had setup the job and enter this command:
powershell.exe -ExecutionPolicy Bypass -file "\\serverapp1\c$\coverageverifier_scripts\SFTP_CoverageVerifier.ps1" in Step 1.
When I look at the VIEW HISTORY I see the error below but I cannot figure out why the script now cannot load the file or assembly.
Any help/direction would be appreciated. Here is the error:
The job script encountered the following errors. These errors did not stop the script: A job step received an error at line 1 in a PowerShell script. The corresponding line is 'powershell.exe -ExecutionPolicy Bypass -File "\empqaapp1\c$\coverageverifier_scripts\SFTP_CoverageVerifier.ps1"'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Add-Type : Could not load file or assembly '
Here is my powershell script as well:
# Load WinSCP .NET assembly
#Add-Type -Path "WinSCPnet.dll"
Add-Type -Path (Join-Path $PSScriptRoot "WinSCPnet.dll")
# Declare variables
$date = Get-Date
$dateStr = $date.ToString("yyyyMMdd")
# Define $filePath
$filePath = "C:\coverageverifier_scripts\TEST_cvgver.20190121.0101"
# Write-Output $filePath
# Set up session options for VERISK TEST/ACCEPTANCE SFTP SERVER
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "secureftpa.iso.com"
UserName = "account"
Password = "pw"
SshHostKeyFingerprint = "ssh-rsa 1111 xxx/xxxxxxxxx+3wuWNIkMY5GGgRObJisCPM9c9l7yw="
}
$session = New-Object WinSCP.Session
$session.ExecutablePath = "C:\WinSCP\WinSCP.exe"
try
{
# Connect
$session.Open($sessionOptions)
# Transfer files
$session.PutFiles($filePath,"/").Check()
}
finally
{
$session.Dispose()
Your Add-Type call does not include the path to the WinSCPnet.dll.
If you have the WinSCPnet.dll in the same folder as your PowerShell script, use this syntax:
Add-Type -Path (Join-Path $PSScriptRoot "WinSCPnet.dll")
Or use a full path.
See also Loading assembly section in WinSCP .NET assembly article on Using WinSCP .NET Assembly from PowerShell.
I try to run this PowerShell script to get counter.
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[String]
$DatabaseName
)
$ErrorActionPreference = "Stop"
$VerbosePreference = "Continue"
cls
Write-Output "Collecting counters..."
Write-Output "Press Ctrl+C to exit."
$counters = #("\Processor(_Total)\% Processor Time", "\LogicalDisk(C:)\Disk Reads/sec", "\LogicalDisk(C:)\Disk Writes/sec",
"\LogicalDisk(C:)\Disk Read Bytes/sec", "\LogicalDisk(C:)\Disk Write Bytes/sec", "\SQLServer:Databases($DatabaseName)\Log Bytes Flushed/sec")
Get-Counter -Counter $counters -SampleInterval 1 -MaxSamples 3600 |
Export-Counter -FileFormat csv -Path "C:\sql-perfmon-log.csv" -Force
But I got error when ran the script.
Error on the screen.
I found out that error occur in "\SQLServer:Databases($DatabaseName)\Log Bytes Flushed/sec"
Can somebody prompt me How I can enter a specific instance probably with credentials?
I see you're trying to run a powershell script from a command prompt.
Make sure you're doing this on the machine your SQL databases are hosted on.
You need to either open powershell administratively on your computer, or if you already have an administrative command prompt open, type "powershell" into it.
You can either paste all the code into your current host after specifying a string for $DatabaseName or just dot-source . the script and pass $DatabaseName as a parameter into the script.
If you're not sure what any of that means, take a look at
https://technet.microsoft.com/en-us/library/dn425048.aspx for more information on getting started with using powershell.