cmd agent job shows success but does nothing to the file - sql-server

I have a powershell script that launches an Excel macro to refresh pivot tables and data sources, it works fine when run manually or from cmd.
when run from Sql Agent job it succeeds without performing the Excel refresh.
I call the script with this command in the job step:
powershell -command "&'C:\rapport_declaratif\REFRESH_3.ps1'"
I tried calling it with powershell, with cmd, with xp_cmdshell but nothing seems to work.
I even called it differently, for exp when I call it with this command:
cmd.exe /c "C:\rapport_declaratif\REFRESH_3.ps1"
it runs forever.
I also googled and found that I have to create this folder:
C:\Windows\SysWOW64\config\systemprofile\DeskTop
I did and it didn't solve the problem.
Below is my powershell script:
# Open Excel file
$excel = new-object -comobject excel.application
$filePath = "C:\rapport_declaratif\Rapport_Declaratif.xlsm"
$workbook = $excel.Workbooks.Open($FilePath)
$excel.Visible = $true
$excel.DisplayAlerts = $false
$worksheet = $workbook.worksheets.item(1)
#Write-Host "Running macro in excel to refresh data."#
$excel.Run("Refresh_ALL")
Start-Sleep -s 30
#Write-Host "data refreshed."#
$workbook.save()
# Write-Host "saved."#
$workbook.close()
$excel.quit()
#Write-Host "Closed Excel"#

Related

Sendkeys emulating WIN+ALT+4

I'm trying with no success to emulate the WIN+ALT+4 in a batch file:
powershell -c "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys('(^{ESCAPE})%{4}')
The command above was my last attempt.

Problem executing REMOTE powershell script using WinSCP via SQL Server Agent Job

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.

Can't start script on remote server from shared resources

I'm trying to write a script in Power Shell to connect to a remote server and execute a .bat file. Since I wanted to do this for more than one server I thought I could place the .bat file on another server which shares ist resources and call it from there, but that does not work. When I place the .bat file in my temp folder and execute it via the script it works. However trying to execute it from the shared resources does not. Why is that?
Note: I can manually start the process via the Task-Manager that starts the .bat file in the shared resources and it works.
script:
$CompName = "myotherserver"
$cred = get-credential
$process = get-wmiobject -query "SELECT * FROM Meta_Class WHERE __Class = 'Win32_Process'" -namespace "root\cimv2" -computername $CompName -credential $cred
$results = $process.Create( "cmd.exe `/c \\mysharedresc\temp\started.bat" )
started.bat:
echo started > c:\temp\started.txt
If you need more annotations or Information please ask for it.
Edit: Working means for me it creates the started.txt in C:\temp. Not working means it does not (but in this case there is no error given.)

PowerShell Get Counter of SQL Server

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.

Powershell passing named parameters from file

i have a problem that is troubling my mind.
I want to automatically execute powershell scripts with named arguments but within another powershell script (that will act as a script deamon).
For example:
One of the scripts that get called has this parameters
param(
[int]$version,
[string]$user,
[string]$pass,
[string]$domain,
)
The powershell script deamon now loads the file and arguments like this
$argumentsFromScript = [System.IO.File]::ReadAllText("C:\params.txt") $job = Start-Job { & "ps1file" $arguments}
The params.txt contains the data like this
-versionInfo 2012 -user admin -pass admin -domain Workgrup
But when i try to execute this code obviously the whole $argumentsFromScript variable will be seen as parameter 1 (version) and i end up with an error, that "-versionInfo 2012 -user admin -pass admin -domain Workgrup" cannot be converted to Int32...
Do you guys have any idea how i can accomplish this task?
The Powershell deamon does not know anything about the parameters. He just needs to execute scripts with given named parameters. The params.txt is just an example. Any other file (csv,ps1,xml,etc) would be fine, i just want to automatically get the named parameters passed to the script.
Thank you in advance for any help or advice..
Try this:
#'
param ([string]$logname,[int]$newest)
get-eventlog -LogName $logname -Newest $newest
'# | sc c:\testfiles\testscript.ps1
'-logname:application -newest:10' | sc c:\testfiles\params.txt
$script = 'c:\testfiles\testscript.ps1'
$arguments = 'c:\testfiles\params.txt'
$sb = [scriptblock]::Create("$script $(get-content $argumentlist)")
Start-Job -ScriptBlock $sb
I guess you want this:
$ps1 = (Resolve-Path .\YourScript.ps1).ProviderPath
$parms = (Resolve-Path .\YourNamedParameters.txt).ProviderPath
$job = sajb -ScriptBlock {
param($ps1,$parms)
iex "$ps1 $parms"
} -ArgumentList #(
$ps1,
[string](gc $parms)
)
# if you wanna see the outcome
rcjb $job -Wait

Resources