SQL Server job can't run PowerShell because "scripts execution disabled" - sql-server

I upgraded a Windows Server 2012 to 2019, but kept the SQL Server (110)
My sql agent jobs stopped working, the ones using PowerShell commands.
I get the error message
A job step received an error at line 1 in a PowerShell script.
The corresponding line is 'import-module SQLPS -DisableNameChecking'.
Correct the script and reschedule the job.
The error information returned by PowerShell is:
'File C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules\SQLPS\Sqlps.ps1
cannot be loaded because the execution of scripts is disabled on this system.
Please see "get-help about_signing" for more details.
The Sqlps.ps1 IS signed with a valid signature, and I even temporarily tried to Set-ExecutionPolicy Unrestricted , but that didn't help either. (All suggested by chatgpt ;-) )
My script should download a file from an url and place it in c:\tmp
EDIT:
Solved, I set the script execution policy to "Allow local scripts and remote signed scripts" in group policy for computer; it was pereviously "Not Configured"

If the effective execution policy is Restricted, even signed scripts won't help you.
What matters is what the effective execution policy is for the user identity that your services / scheduled tasks run as, which you can control as follows:
Ad hoc, in a given PowerShell CLI call (powershell.exe [-Command] ... / powershell.exe -File ...), precede the (possibly implied) -Command / -File parameter with an -ExecutionPolicy argument, e.g. - if you fully trust the script (eventually) getting invoked - -ExecutionPolicy Bypass
Persistently, via a machine-wide execution policy (requires elevation (administrative privileges)):
Via Set-ExecutionPolicy -Scope AllUsers
Via GPO policies (which override persistent Set-ExecutionPolicy configurations).
See this answer for additional information.

Related

How can I call the Twilio CLI from a SQL Server job step?

I have the Twilio CLI installed on my system and I changed my script execution policy to allow it to run. I'm trying to call twilio api:core:messages:create from within a database job powershell step running as me. The command works flawlessly from a powershell window but in the SQL Server job I'm getting:
'The term 'twilio' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.'
Any suggestions? What am I missing?
To further clarify as per Dale: I have created a SQL Server Agent Job using the the SQL Server Agent and it has one step as Type Powershell with this code:
twilio api:core:messages:create --from "+1XXXXXXXXXX" --to "+1XXXXXXXXXXXX" --body "Twilio Test"
The statement works fine when run in Powershell directly, but gives the above error when the job is triggered.
Thanks!
SQL Server agent job uses SQLPS.exe, instead of actual powershell installed in the machine.
You need to call the Powershell using command prompt, as specified in the below image. Reference article

Powershell deploying to Powerbi report server malfunction when logged off the server

I have a SQL Agent job invoking SSIS package - Powershell script that behaves differently depending on whether the service account running the job as is logged on the remote server or logged off the server.
The Symptom
SQL Agent job runs as a proxy account associated with a service account.
Succeeding case:
When the service account is logged in the server(remote desktop), the SQL agent job succeeds and the script actually does the job.
Problematic case:
However when the service account is logged off the server(remote desktop), the SQL agent job succeeds (no error) but the script actually doesn't complete the job (or partially run, if you like)
In the below script, the copying part is done, but uploading part is not done.
The Script
The powershell script runs perfectly fine when run manually on the server itself.
It copies files from a network drive and then load them into the on-prem Power BI reporting server.
The stripped down version of the script which replicates the issue is as below:
#Copying Files
$exe = "robocopy.exe"
$roboflags = "/NFL /NDL /NJH /NJS /nc /ns /np"
$destdir = "e:\import\spfiles"
$srcdir = '"\\xxxxxxxx"'
Remove-Item "e:\import\spfiles\*.*"
& $exe $srcdir $destdir
#Uploading File to the reporting server
$localfile = e:\import\spfiles\test.jpg
$rsfolder ="/Test Folder"
$session = New-RsRestSession -ReportPortalUri http://serverhostname/reports
Write-RsRestCatalogItem -WebSession $session -Path $localfile -RsFolder $rsfolder -Overwrite
The Service Account
The service account is AD based and has Administrator privileges in the server where the script runs (For the sake of investigation), and has the permissions required for a service account at the domain controller level. 
Log on as a service (SeServiceLogonRight)
Replace a process-level token (SeAssignPrimaryTokenPrivilege) 
Bypass traverse checking(SeChangeNotifyPrivilege) 
Adjust memory quotas for a process(SeIncreaseQuotaPrivilege)
Permission to start SQL Writer
Permission to read the Event Log service
Permission to read the Remote Procedure Call service
This service account (and the proxy account associated with it) works fine with most of our database related SQL agent jobs, but this particular job dealing with Reporting Server. So I assumed this could be something to do with Reporting server. 
Can anyone advise on how to resolve this problem or even suggest some action items for further investigation?
I need to run this script as a scheduled job without having to log on to the server remotely.

execute a batch file on remote machine

I'm trying to execute a batch file(shutdown.bat and startup.bat of tomcat 7) on a remote machine(Windows server 2008) using PSTools but didn't got any luck till now.
Below are the steps I used
c:\>psexec \\129.12.3.1 -u Admin -p admin90 C:\>Hyp\tom7_50080\bin\shutdown.bat
and on my cmd i got
PsExec v2.0 - Execute processes remotely
Copyright (C) 2001-2013 Mark Russinovich
Sysinternals - www.sysinternals.com
PsExec could not start cmd on 129.12.3.1:
There are currently no logon servers available to service the logon request.
Can anyone help with the above output and with the batch file for executing the shutdown and startup batch file on remote machine.
Is PS Tools only option to execute any service/batch file on remote machine or we could use any other utility provided by MS.
In you example, #David Candy pointed out even you had the connection go thru, it would not work as you have 'c:>hyp\' instead of C:\hyp\tom7_*
You seem to be using IP, but the message you got seems to be name resolution related, so not sure what's happening there. Maybe you should upgrade to the latest PsExec version.
If you want to use PowerShell you would use Invoke-Command -ComputerName {NameOfPC} -ScriptBlock {C:\Hyp\tom7_50080\bin\shutdown.bat}
If you want to execute a program on another server, you can use a stored procedure on that server to invoke the command, and call that stored procedure from the local mcahine.
You could also create a web service on the remote server that invoked the command you want to execute.
In either case, be very careful that you don't open a security hole by either allowing more users to execute commands through the mechanism you implement, or by some user to execute commands other than the one you intend.

Powershell User Issue Through SQL Server Agent

I am currently trying to run a Powershell script through SQL Server Agent, which completes its task without error if I run it through Powershell ISE on the desktop. The simple script is below (it's only being used for testing):
$test = "G:\test.txt"
if (Test-Path $testFile)
{
Remove-Item $test
}
When I run this through SQL Server Agent, it produces a successful output - no errors whatsoever, but does show that it's being run as a different user in the job history log, for instance domain\localmachine, whereas when I run the script through Powershell ISE, it shows domain\you.
As a note, I can't confirm this manually because what I tried to do was run the below script both locally and through SQL Server Agent in a job to see the output, but the job failed (and thus why I suspect it's a user issue). Therefore, I'm trusting SQL Server Agent as to the domain\locallmachine is running the job (the reason it won't delete the file).
([Environment]::UserDomainName + "\" + [Environment]::UserName) | out-file pssaved.txt
"$env:userdomain\$env:username" | out-file -append pssaved.txt
[Security.Principal.WindowsIdentity]::GetCurrent().Name | out-file -append pssaved.txt
## Locally this produces domain\you
## On SQL Server Agent, I receive the error: The error information returned by PowerShell is: 'SQL Server PowerShell provider error: Path SQLSERVER:\pssaved.txt does not exist. Please specify a valid path.'
Is there a way, through SQL Server Agent to run a job as my domain user, for instance domain\you instead of the domain\localmachine (at least, this would eliminate this possibility of an error)?
You can use a proxy for this. Check it out.

Using custom cmdlet from SQL Server

I want to execute a Powershell script from SQL Server's maintenance plan. This is fine and perfectly possible, but what if I want to use a custom cmdlet? Can this still work from the Powershell script SQL Server job step (in this case, I need to use the SCVMM cmdlet).
No this won't work from SQL Agent PowerShell job step because SQL Agent uses sqlps, the SQL Server minishell. Since the minishell does not support adding cmdlets either via add-pssnapin or import-module, there is no way to add the SCVMM cmdlets.
Instead use a CmdExec (Operating System) job step and specify regular PowerShell. For example (not sure of commands to add SCVMM cmdlets)
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.EXE -command "add-pssnapin SCVMM;invoke-someCmd"
or put the commands in a script file and call the script:
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.EXE -file"C:\Scripts\Invoke-SCVMM.ps1"

Resources