Can't start script on remote server from shared resources - batch-file

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.)

Related

Getting an error when trying to execute powershell code via a SQL Agent job

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:

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.

WinSCP Script upload recursivelly all files matching a mask to the same folder

I have a text file that I am calling from a batch file and it is not putting files recursively in the FTP site. The folder structure has subfolders which contain the files I want to copy among many other files. The put files only copy C:\storage only. After reading the documentation and trying other method is still not copying files recursively. (no folders to be copied with the RDF from subfolders)
The folder structure is random on different PC:
C:\storage\78286.S-92A.920024*.RDF
C:\Storage\folder1\78286.S-92A.920024*.RDF
C:\Storage\storage2\folder2\78286.S-92A.920024*.RDF
There are many RDF files, but the wildcard I am interested is the one you can see above. Basically I want to select all the *.RDF (as wildcard above from all the subfolders), but do not want the subfolders to be copied to the remote.
Please see code below.
option batch continue
option confirm off
option reconnecttime 900
open ftp://companyuser:!password#ftpsite.com/
lcd "C:\storage"
put "C:\storage\78286.S-92A.920024*.RDF" "/"
put "C:\storage\*\78286.S-92A.920024*.RDF" "/"
close
exit
It's not easy to do such custom processing with WinSCP scripting only.
But with WinSCP .NET assembly from a PowerShell script, it's not difficult:
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Ftp
HostName = "ftp.example.com"
UserName = "username"
Password = "password"
}
$session = New-Object WinSCP.Session
Write-Host "Connecting ..."
$session.Open($sessionOptions)
$localPath = "C:\storage"
$remotePath = "/"
$wildcard = "78286.S-92A.920024*.RDF"
$localFiles = Get-ChildItem -Include $wildcard -Recurse -Path $localPath
foreach ($localFile in $localFiles)
{
Write-Host "Uploading $($localFile.FullName)..."
$session.PutFiles($localFile.FullName, $remotePath).Check()
}
Just extract a contents of WinSCP .NET assembly package along with the script (say flatupload.ps1) and run it like:
powershell -ExecutionPolicy Bypass -File flatupload.ps1
The code is partly based on WinSCP example Recursively move files in directory tree to/from SFTP/FTP server while preserving source directory structure.
See also WinSCP forum question Ignore folder structure when copying the files.
Have look at doc on https://winscp.net/eng/docs/commandline
You can use command-line winscp.com
Your script seems good, it should need to be called with winscp.com
For ftp client on Linux, mput/mget(multiple file operation), command is available but it is not available with WinScp.
You can try some work around like first create folder using mkdir command (with winscp.com) and then use synchronize option with winscp.exe to update folder content.

no error or result when trying to use PowerShell execute a .bat file on a remote PC

I have read many examples of how to run a .bat file on a remote PC and the one I need is based on the PowerShell invoke-command:
invoke-command -computername RemotePC -scriptblock {start-process c:\things\Thing.bat}
When I run that line of PowerShell it does not run the .bat file on the remote pc and returns no error. Any help please.
I have found that this works:
invoke-command -computername RemotePC -scriptblock {& "c:\things\Thing.bat"}
Start-Process isn't intended to be used to start scripts but instead to start processes, e.g. real exectuables.
You have some alternatives though (one you allready found):
Using the Dot sourcing {. "C:\things\thing.bat"}
Using the Call operator {& "C:\things\thing.bat"}
Differences between both operations (ref.: Source-Powershell-SS64):
Dot sourcing runs a function or script within the current scope.
unlike the call operator (&) which will run a function or script, but
it is not added to the current scope.

PowerShell Output

So, I am fairly new to PowerShell and need to create a script to rename the computers in our office. That portion of the script works. The part I am having trouble with is the output.
I have this set in task scheduler, but when it runs I do not see if the rename was successful. Below is my script and below that is what goes into the text file.
start-transcript -path C:\Users\abhagwandin.SENECA\Desktop\RenameResults.txt
$CSV = Import-Csv "C:\Users\abhagwandin.SENECA\Desktop\Computer Desktop Names Test.csv" -Header OldName, NewName
Foreach ($name in $CSV)
{
write-output $name
netdom renamecomputer $name.OldName /newname: $name.NewName /userd: admin /passwordd: pass /usero: admin /passwordo: pass /reboot /force
}
stop-transcript
-------------------------------------------------------------------------------
**********************
Windows PowerShell Transcript Start
Start time: 20150520154216
Username :
Machine : (Microsoft Windows NT 6.1.7601 Service Pack 1)
**********************
Transcript started, output file is C:\Users\abhagwandin.SENECA\Desktop\RenameRe
sults.txt
OldName NewName
------- -------
JFLAHNYCD1 JFLAHERTY
**********************
Windows PowerShell Transcript End
End time: 20150520154218
**********************
You know that renaming a computer through a cmdline command in powershell instead of using the built in cmdlets can give problems with the output if you don't parse the output (and preferably create a new object for it)?
Why don't you use rename-computer or the rename() method of the win32_computersystem wmi class? Both can be used remotely so you don't even have to schedule tasks that way.
Just create an input file with the current name and the desired names and use a loop to process them.

Resources