Reputation: 27
My powershell script runs fine in powershell command line but throws the following error when run from Sql Agent :
Executed as user: DOMAIN\svcSQLDefaultPROD. A job step received an error at line 21 in a PowerShell script. The corresponding line is ' Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Cannot perform operation because operation "ReportWrongProviderType" is invalid. Remove operation "ReportWrongProviderType", or investigate why it is not valid. '. Process Exit Code -1. The step failed.
This is my powershell script which I have added in Sql Agent job step as Type powershell
. I have also tried to run the job step as type CmdExe
but my command prompt does not work/does not export the csv files from command line too (like powershell does export the csv from powershell command line):
# Log file path
$logFile = "C:\RNA\ExportRNAData.log"
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"$timestamp - Script started" | Out-File -FilePath $logFile -Append
# Define SQL Server connection details
$sqlServerInstance = "SourceServerName"
$databaseName = "DBName1"
$storedProcedure = "[DBName2].[dbo].[GenExportFile_tstHK]"
# Define the output folder
$outputFolder = "\\RemoteServerName\Export"
try {
# Retrieve the list of Branch values from the SQL Server table
$branches = Invoke-Sqlcmd -Query "SELECT Branch FROM Sites" -ServerInstance $sqlServerInstance -Database $databaseName
# Iterate through each Branch value
foreach ($branch in $branches) {
$areaID = $branch.Branch
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$outputFile = "$outputFolder\PowershellHK_2_$areaID`_$timestamp.csv"
# Execute the stored procedure with the current AreaID
Invoke-Sqlcmd -Query "EXEC $storedProcedure @AreaID='$areaID'" -ServerInstance $sqlServerInstance |
Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8BOM -UseQuotes AsNeeded
"$timestamp - Results for AreaID '$areaID' exported to $outputFile" | Out-File -FilePath $logFile -Append
}
} catch {
"$timestamp - Error: $_" | Out-File -FilePath $logFile -Append
}
"$timestamp - Script completed" | Out-File -FilePath $logFile -Append
# set permissions
# Set-ExecutionPolicy RemoteSigned -Scope Process
The SQL Agent service account has been granted full permissions to the remote server folder as well as local server folder
Also, I have just installed Powershell 7 to use -UseQuotes Asneeded
functionality which was not available in the older version (Powershell 4). I think SQL Agent is using the previous version of powershell as it unable to recognize -Usequotes Asneeded
just like PS4 did not recognise this keyword. How can I make SQL Agent use the latest version of Powershell (PS7)
No logs are created in the log file too as the job does not run at all.
Please help
Upvotes: 0
Views: 31