Copying files to a remote server in powershell - powershell

I am configuring a Jenkins job and Jenkins slave is installed in a windows server(A). I want to copy project build output folder to another windows server(B).
I can execute a batch file manually on Server A, with following content.
powershell -executionpolicy remotesigned -Command Copy-Item "C:\Jenkins\workspace\DEV_Build\DEPLOY\UAT\build" -Destination "\\SYDUATAPP01\E$\build" -recurse
However, when I execute this batch file through Jenkins I get a error "Access Denied"
Access is denied
+ CategoryInfo : NotSpecified: (:) [Copy-Item], UnauthorizedAcces
sException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.Pow
erShell.Commands.CopyItemCommand
Appreciate your help..... If it is not possible via powershell, I would like to know what other alternatives I have to copy files in my Jenkins job

As admin, check if you have the -executionpolicy set as intended
powershell get-executionpolicy
if not then as admin, run:
powershell set-executionpolicy remotesigned -force
Then I am not 100% sure why you want to run this as a batch file, but instead just save it as a .ps1 file.
Copy-Item -Path "C:\Jenkins\workspace\DEV_Build\DEPLOY\UAT\build" -Destination "\\SYDUATAPP01\E$\build" -recurse
where you can also use -Force -PassThru -Verbose
If you still want to run it as batch file, then just run
powershell Copy-Item -Path "C:\Jenkins\workspace\DEV_Build\DEPLOY\UAT\build" -Destination "\\\SYDUATAPP01\E$\build" -recurse
EDIT To run your script as admin, you can copy this into the very top of your script. It basically just creates a VBS file that launches the batch as admin. Initially it will popup the UAC prompt, but it is a once of deal, from there it will run the script as admin each time.
#echo off
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' NEQ '0' (
echo Checking privileges.
goto UPrompt
) else ( goto Admin )
:UPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\Admin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\Admin.vbs"
"%temp%\Admin.vbs"
exit /B
:Admin
if exist "%temp%\getadmin.vbs" ( del "%temp%\Admin.vbs" )
pushd "%CD%"
CD /D "%~dp0"
:----------------- Copy the rest of your Batch below this line------

#Gergard, Thank you very much for your help. I tried putting the provided bit of code to run as admin. However, nothing worked. Execution policy was remotesigned.
Finally below steps solved my problem;
I installed Powershell plugin(1.3) on my windows remote slave. Powershell 1.3, executed with "ByPass" policy
And added a step from powershell to copy item.
Copy-Item "source path" -Destination "\destination path" -recurse
Above steps didn't solve the issue and still complained as unauthorized.
Then I configured jenkins remote slave process -> properties -> run as admin account.
This solved the issue and now I am able to copy files successfully.

Related

Batch file to run PowerShell Script Only Works Once

So I'm trying to create a batch file to run a PowerShell script while bypassing the execution policy. Oddly, it worked a single time, but without me editing anything, it will not run again. I've created other files thinking maybe my file somehow got corrupted, but nothing... Any chance someone sees anything blatantly wrong with this?
#echo off
Powershell.exe -Command "& {Start-Process Powershell.exe -ArgumentList '-ExecutionPolicy Bypass -File %~dp0File.ps1' -Verb RunAs}"
PAUSE
The *.ps1 file works by itself if I click through the prompts. Also, if I manually set the execution policy in PowerShell to Bypass, this batch file still does not work. This is not a process I usually need to take, so I'm curious if anyone sees anything wrong with how this is written?
If this is just to run your script, what I personally do is create a shortcut of the script and then modify the Target of the shortcut:
Target: Powershell.exe -ExecutionPolicy Bypass -File "C:\scriptpath\script.ps1"
If you want your script to be executed as Administrator you can add this to the top of the main script:
$myInvoke="-file `"$($MyInvocation.ScriptName)`""
Start-Process "$PSHome\powershell.exe" -Verb Runas -ArgumentList $myInvoke -EA 'Stop'
If the shortcut will always be in the same folder as your script you can also leave Start In blank and change the path for Powershell.exe -ExecutionPolicy Bypass -File ".\script.ps1" by doing so if you copy the entire folder to a different location, the shortcut will still work.

File not visible in Explorer after copy via self elevated powershell script

I used Running a command as Administrator using PowerShell? to self-elevate my powershell script to copy a file and schedule a job on Windows 10 machines:
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
But the copy process:
Copy-Item -Path (c:\example\powershellw.exe') -Destination 'c:\windows\system32\WindowsPowerShell\v1.0'
Works in my local machine but on the remote machines (different privileges) not:
a. It DOES copy the file BUT
b. the file is only readable by commandline "dir" and NOT visibile in Windows Explorer and not in task scheduler leading to "file not found" in task scheduler even when run with admin privileges (https://superuser.com/questions/1382965/powershell-cant-see-all-files-in-a-directory)
The file has just A and not different attribs, it has access from system, users, administrator but still its not visible in explorer. When I start a powershell session as admin manually and run this line, the file becomes visible ...
So what is the difference between manually running the line on an elevated powershell prompt versus running the script auto with the self-elevated line ?

The argument 'install-sshed.ps1' to the -File parameter does not exist | powershell

I am adding key to windows 7 x64 using powershell
So far i have tried the below command using powershell
powershell -executionpolicy bypass -file install-sshed.ps1
I got error like this:
The argument 'install-sshed.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter
What i am doing wrong?
It seems like your PowerShell session is started in a different folder than your PowerShell script. Try to add the full path to your PowerShell script:
powershell -executionpolicy bypass -file "c:\scripts\install-sshed.ps1"
Alternatively, change to the directory where the *.ps1 file is located first:
cd c:\scripts
powershell -executionpolicy bypass -file install-sshed.ps1
In addition to the above answer, I'd like to add that you can also use relative paths.
For instance, to run from current directory
powershell -execution policy unrestricted -file ".\test.ps1"
Or to run from nested folder:
powershell -execution policy unrestricted -file ".\config\test.ps1"
I will also recommend to add the following parameter: -noprofile
This will make sure no user profiles will be loaded, it is a best practice to do that when running scripts.
You can find an interesting read here
Additionaly to other answers.
It might be you've downloaded OpenSSH-Win32_Symbols.zip or OpenSSH-Win64_Symbols.zip
- these are NOT required binaries.
You might try to download OpenSSH-Win32.zip or OpenSSH-Win64.zip version respectively.
Also it suggested that you should cd into C:\Program Files\OpenSSH but archive is in a subfolder and I had to extract it to the parent OpenSSH folder.
Extra: common issue with permissions described here by asterikx, you might find useful to reinstall openssh following these steps if something is not working properly (assuming the downloaded archive is located at D:\Downlaods):
powershell.exe -ExecutionPolicy Bypass -File 'C:\Program Files\OpenSSH\uninstall-sshd.ps1'
del 'C:\Program Files\OpenSSH\'
Expand-Archive D:\Downloads\OpenSSH-Win64.zip -DestinationPath 'C:\Program Files\OpenSSH'
copy 'C:\Program Files\OpenSSH\OpenSSH-Win64\*' 'C:\Program Files\OpenSSH\'
del 'C:\Program Files\OpenSSH\OpenSSH-Win64\'
powershell.exe -ExecutionPolicy Bypass -File 'C:\Program Files\OpenSSH\install-sshd.ps1'
powershell.exe -ExecutionPolicy Bypass -File 'C:\Program Files\OpenSSH\install-sshd.ps1'
powershell.exe -ExecutionPolicy Bypass -File 'C:\Program Files\OpenSSH\FixHostFilePermissions.ps1'
powershell.exe -ExecutionPolicy Bypass -File 'C:\Program Files\OpenSSH\FixUserFilePermissions.ps1'
Set-Service sshd -StartupType Automatic
Set-Service ssh-agent -StartupType Automatic

Powershell remote execution not writing log on remote machine

I am currently stuck with an installation issue using a powershell script. I can run the script without any problem on Host B from command line. But when I attempt to launch it remotely, the script is not able to create the log file (which I monitor to see when I need to send the password to the command line). The error is at very bottom...
I launch the installer from Host A (see commands below). It remotely executes the powershell script cognosInstall.ps1 on Host B. The script code is at bottom. It begins to copy files over and kick-off the installation, but for some reason it has a problem with creating the log file. I check local directory on HostB and do not find the file either.
Host A (data collector): Triggers remote execution of powershell script which installs IBM Cognos.
$s=new-pssession -computername HostB -credential $creds
invoke-command -session $s {$filename=Split-Path c:\temp\auto-install\*stats*.iso -leaf -resolve;echo $filename;}
invoke-command -session $s {c:\temp\auto-install\cognosInstall.ps1 $filename;}
Host B (Cognos is being installed on):
#Open a command window
invoke-item C:\Windows\System32\cmd.exe
start-sleep -s 2
# Write output of install command to file
select-window cmd |send-keys "c:\temp\cognos-install\cognos_install.bat c:\temp\cognos-install\cognos_mssql.ini C:\temp\IBM_Cognos_10.1.1_and_FP1 > c:\temp\Cognos_Install_log 2>&1 {ENTER}"
#check file for password prompt
do {
Start-Sleep -s 8;
write-output "Waiting for Password Prompt"
}
until (Select-string -Path c:\temp\Cognos_Install_Log -pattern Password )
select-window cmd |send-keys "Passwd123{ENTER}"
Error I am getting:
Install starts to run..... then hits this issue.....
Copying install config file to cognos-install directory
C:\temp\auto-install\cognos_mssql.ini
1 File(s) copied
Beginning of Cognos Install - wait for completion
Waiting for Password Prompt
Cannot find path 'C:\temp\Cognos_Install_Log' because it does not exist.
+ CategoryInfo : ObjectNotFound: (C:\temp\Cognos_Install_Log:Stri
ng) [Select-String], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.Selec
tStringCommand

Why can't I get the Jenkins Powershell plugin to work?

Why can't I get the Jenkins "Powershell plugin" to work?
I can run a powershell script on Jenkins using a "Execute windows batch command" build step with the following command:
powershell -ExecutionPolicy ByPass -File script.ps1
But I am unable to run a powershell script with the Jenkins "Powershell plugin" using the "Windows Powershell" build step and this command, because of a Windows Execution policy not set error disallowing it to run:
script.ps1
Does anyone know the proper arg to give the Jenkins "Powershell Plugin" for it to succesfully run a script? Otherwise, I will just use the batch script work-around.
The correct thing to do is to set an execution policy on your machine (a one-time action), at which point you won't need to bypass it every time, and the Jenkins plugin should "just work". Are you unable to?
A reasonable starting setting would be RemoteSigned, which will allow you to execute local scripts fine but would still disallow scripts downloaded from the internet.
From an elevated PowerShell prompt, you would run:
Set-ExecutionPolicy RemoteSigned
See also: http://technet.microsoft.com/library/hh849812.aspx
UPDATE: excerpt from Help on applying policy and how it's supposed to behave:
If you set the execution policy for the local computer (the default)
or the current user, the change is saved in the registry and remains
effective until you change it again.
Of course, if your machine is on a Domain, then Group Policy could revert this.
For a reboot-proof solution, put this single line
powershell Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force
in a batch file in the All Users Startup folder, which on Windows 7 is C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
(or you can get there by clicking Start -> All Programs, right-click Startup and click Open All Users)
This is how I got Jenkins executing PS scripts on a domain machine subject to Group Policy, without having to involve the sys admin guys ;-)
After experimentation, I realized that since Jenkins is running as a service as the System user, then the powershell scope is different than the scope used by my terminal services login session.
This script works for me and seems to properly set the registry keys so that the setting is persistent across reboots and new logins.
# SetExecutionPolicyToRemoteSigned.ps1
# Need to run this after every server reboot.
Write-Output "Setting local Powershell policy to RemoteSigned"
Write-Output ""
Set-ExecutionPolicy -scope CurrentUser Undefined -Force
#Set-ExecutionPolicy -scope Process Undefined -Force
Set-ExecutionPolicy -scope LocalMachine Undefined -Force
Set-ExecutionPolicy -scope CurrentUser RemoteSigned -Force
#Set-ExecutionPolicy -scope Process RemoteSigned -Force
Set-ExecutionPolicy -scope LocalMachine RemoteSigned -Force
Write-Output "Finished."
Get-ExecutionPolicy -list
Start-Sleep -s 10