PowerShell: passing parameters - powershell

I run the script from the file in Jenkins. Command:
psexec -i -s cmd.exe /c echo . | powershell.exe -file "c:\Program Files (x86)\Applications\Jenkins\jobs\Deploy\workspace\Deploy\script.ps1"
How can I pass a value for the "build" variable?
Please, help me
Thanks

You would simply follow the path with your arguments. Such as:
psexec -i -s cmd.exe /c echo . | powershell.exe -file "c:\Program Files (x86)\Applications\Jenkins\jobs\Deploy\workspace\Deploy\script.ps1" '-build 1.0'
You can see the command line syntax for PowerShell.exe here. It shows:
PowerShell[.exe]
[-File <FilePath> [<Args>]]
If that does not work for you, you can try and dot source the script in a -command scriptblock, such as:
psexec -i -s cmd.exe /c echo . | powershell.exe -command {. "c:\Program Files (x86)\Applications\Jenkins\jobs\Deploy\workspace\Deploy\script.ps1" -build 1}

I made mistake in the script. I forgot to insert the following code:
Param(
[int32]$build=0
)
As TheMadTechnician said, the command to run the script is:
psexec -i -s cmd.exe /c echo . | powershell.exe -file "c:\Program Files (x86)\Applications\Jenkins\jobs\Deploy\workspace\Deploy\script.ps1" -build %BUILD_NUMBER%

Related

How to open Powershell with cmd and use a .ps1 file

I try to open a ps1 powershell file thats updates a gitrepo
i have tryed
powershell -ExecutionPolicy Bypass -Command "& '%USERPROFILE%\folder1\update.ps1'
this is working but when it comes to a requirements.txt promt writes error of not found that file i think powershell is not inside this folder directly so it cant find that file what is needed
if i make this
cd %USERPROFILE%\ & REM First change to the batch file folder
echo Points as at = %time% %date%> updatebing_log.txt & REM create a simple logfile with time and end result of the batch run
echo ============================folder1=========================== >> updatebing_log.txt
cd folder1\
start powershell
cd %USERPROFILE%\folder1
powershell -ExecutionPolicy Bypass -Command "& '%USERPROFILE%\folder1\update.ps1'
echo Waiting seconds
timeout /t 10 /nobreak > NUL
it is working
but it opens a cmd (bash file) promt and a powershell then it cd to folder
powershell do nothing then
inside cmd i see that the ps1 file is executed and alsow works with the requirements.txt
As per my comment. Here's what your code is doing. Thus the response you're seeing.
# Run this in cmd.exe
cd %USERPROFILE%\ & REM First change to the batch file folder
echo Points as at = %time% %date%> updatebing_log.txt & REM create a simple logfile with time and end result of the batch run
echo ============================folder1=========================== >> updatebing_log.txt
cd folder1\
# Start a PowerShell interactive session
start powershell
cd %USERPROFILE%\folder1
# Start a new PowerShell session from cmd.exe and run this code
powershell -ExecutionPolicy Bypass -Command "& "$env:USERPROFILE\folder1\update.ps1" # note the profile change I made for you.
# Run this in cmd.exe on Powerhell exit
echo Waiting seconds
timeout /t 10 /nobreak > NUL
If that is not the flow you were after, then you need to rethink this.
i made this at work it looks likke it works but dont know i try to show the working directory but it want show it only shows were the ps1 call file is
i made a test.bat
powershell -ExecutionPolicy Bypass -Command "& '%USERPROFILE%\Brewd\updatebrewdall.ps1'"
and updatecall.ps1
cd "folder1\"
powershell -ExecutionPolicy Bypass -Command "& '.\update.ps1'"
Start-Sleep -Seconds 10
# now back to previous directory
cd ..\
cd "folder2\"
"$([Environment]::CurrentDirectory)\$ComputerName"
powershell -ExecutionPolicy Bypass -Command "& '.\update.ps1'"
Start-Sleep -Seconds 10
# now back to previous directory
cd ..\
cd "folder3\"
"$([Environment]::CurrentDirectory)\$ComputerName"
powershell -ExecutionPolicy Bypass -Command "& '.\update.ps1'"
Start-Sleep -Seconds 10

Invoke-Expression executing external program and shell script

I'm trying to get the root folder of a connected android device with powershell, when I try the standard command for this in the cmd it just works as expected and returns the path.
CMD
adb -s <DeviceId> shell echo $EXTERNAL_STORAGE
When I try to replicate this command in powershell I get nothing not even an error.
PowerShell
Invoke-Expression -Command "adb -s <DeviceId> shell echo $EXTERNAL_STORAGE" | Out-String
I've searched for some solutions and have found a way to make it work in powershell but I was wondering if their is an other way to get the same result without calling cmd.exe in powershell
Working PowerShell but seems doggy
(cmd.exe /c adb -s $Id shell echo `$EXTERNAL_STORAGE) | Out-String
Just specify the command as-is.
$Result = & adb -s $Id shell echo `$EXTERNAL_STORAGE
Write-Host $Result
Maybe:
$Result = & adb "-s $Id shell echo `$EXTERNAL_STORAGE" | Out-String

Why does command work in Windows CMD and not PowerShell?

I have a script that saves an executable and a .ps1 to a list of remote computers.
It then runs the executable on each computer.
I have to call the executable with a .ps1 because of the way it is set up when running silently.
I noticed that one of my commands runs quickly from the command line but seems to hang up in my script. Is there any reason why this would happen?
The command is:
psexec -s #C:\myscript\computers.txt cmd /c "Powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass && PowerShell -noninteractive -file "C:\Install.ps1""
Here is my entire script:
cls #clear screen
function CopyFiles {
# Get .exe from source and place at destination workstation
$source2="\\mainserver\program.exe"
$destination2="\\$line\c$\program.exe" # place .exe on C:\ directory of worstation
Copy-Item -Recurse -Filter *.* -path $source2 -destination $destination2 -Force
# Get .bat from source and place at destination workstation
$source3="\\fileserver\Install.ps1"
$destination3="\\$line\c$\Install.ps1" # place .bat on C:\ directory of worstation
Copy-Item -Recurse -Filter *.* -path $source3 -destination $destination3 -Force
}
$a = Get-Content "C:\myscript\computers.txt"
foreach($line in $a)
{
"These options must run in numbered order."
" "
" "
"1. Copy installer to remote computer(s)."
"2. Remove application from remote computer(s)."
"3. Install application from remote computer(s)."
"4. Quit."
" "
"Type number and press Enter."
$UI = Read-Host -Prompt ' '
If ($UI -eq 1) {
CopyFiles
} ELSEIF ($UI -eq 2) {
psexec #C:\myscript\computers.txt -c "\\fileserver\Remove.bat"
} ELSEIF ($UI -eq 3) {
psexec -s #C:\myscript\computers.txt cmd /c "Powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass && PowerShell -noninteractive -file "C:\Install.ps1""
} ELSEIF ($UI -eq 4) {
"Good Bye"
}
}
The root cause is because PowerShell has a more standard rule to parse parameters which is different from cmd. In PowerShell if a parameter starts with a quote then it'll also end with the quote. However in cmd the parameter continues if there are no separator (like space or tab) after the quote. That means "powershell someargs "another"" is 2 parameters in PowerShell but only 1 in cmd. Try echoing the command from PowerShell and you'll see that right away
PS D:\> echo psexec -s #C:\myscript\computers.txt cmd /c "Powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass && PowerShell -noninteractive -file "C:\Install.ps1""
psexec
-s
#C:\myscript\computers.txt
cmd
/c
Powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass && PowerShell -noninteractive -file
C:\Install.ps1
C:\Install.ps1 is split to a different argument, compared to cmd where it's recognized as one:
D:\>type testparam.bat
#echo off
:loop
if [%1]==[] exit /b
echo [%1]
shift
goto :loop
D:\>testparam.bat psexec -s #C:\myscript\computers.txt cmd /c "ps -ExecutionPolicy Bypass AND ps -noninteractive -file "C:\Install.txt""
[psexec]
[-s]
[#C:\myscript\computers.txt]
[cmd]
[/c]
["ps -ExecutionPolicy Bypass AND ps -noninteractive -file "C:\Install.txt""]
As you can see the middle quotes aren't nested quotes and are leaved as-is to the command, then cmd /c will have another weird behavior: stripping the first and last quote and run the remaining things as one command
PowerShell also strips double quotes but only the outer one of each parameter and before passing to the command
Now to fix that you have to include double quote in the parameter by using either of these
psexec -s #C:\myscript\computers.txt cmd /c "Powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass && PowerShell -noninteractive -file ""C:\Install.ps1"""
psexec -s #C:\myscript\computers.txt cmd /c "Powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass && PowerShell -noninteractive -file `"C:\Install.ps1`""
psexec -s #C:\myscript\computers.txt cmd /c '"Powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass && PowerShell -noninteractive -file "C:\Install.ps1"'
psexec -s #C:\myscript\computers.txt cmd /c --% "Powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass && PowerShell -noninteractive -file "C:\Install.ps1""
Or if the file path doesn't have any spaces you can simply remove them which will work in both cmd and PowerShell
psexec -s #C:\myscript\computers.txt cmd /c "Powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass && PowerShell -noninteractive -file C:\Install.ps1"
In fact if the path contain spaces like "C:\some dir\Install.ps1" then your command will fail in both cmd and PowerShell because now cmd also splits the part after the space to a new argument. Try this and see
psexec -s #C:\myscript\computers.txt cmd /c "Powershell Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass && PowerShell -noninteractive -file "C:\some dir\Install.ps1""

Which symbol is escape character in cmd?

I have this code:
powershell -command "& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }"
it's for download file.
When I execute it in cmd on remote server - everything is ok.
But when I want to execute this code from my computer on remote server using paexec, I have some troubles with escape characters.
Command in my CMD:
psexec.exe \\remoteServer.0.1 -u username -p password -dbg -lo D:\PsExec.log cmd /c "powershell -command "& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }""
I try to use ^ symbol, but the same error;
Code using ^ symbol for double-quotes:
psexec.exe \\remoteServer.0.1 -u username -p password -dbg -lo D:\PsExec.log cmd /c "powershell -command ^"& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }^""
Also, I tried to use \ (like in PHP) for escape, but have the same result.
Help with this or give advice how I can remotely download a file using the command line.
Unfortunately CMD uses different escape characters depending on what is escaped and where. There is no single one escape character that would be used everywhere.
In most cases the next character is escaped by prepending it with a caret (^), e.g. in for /f loops:
for /f "tokens=1" %%a in ('type file.txt ^| find "something"') do ...
But sometimes characters are escaped by doubling them, e.g. percent characters (%) in batch scripts:
#echo off
echo %%DATE%%=%DATE%
Sometimes you may even need need to put in other escape characters (like backslashes) because you need to escape something not for CMD, but for the command the string is being passed to:
mountvol | findstr /r \\\\
Your particular scenario shouldn't require additional quotes or escaping, though. Just run the PowerShell commandline directly, without cmd /c:
paexec.exe \\remoteServer.0.1 -u username -p password powershell -command "&{...}"
Is it possible to use powershell the complete way? If so, you could try the following:
New-PsDrive -Name X -Root \\127.0.0.1\c$ -PsProvider FileSystem -Credential (Get-Credential)
Copy-Item -Path X:\RequestedFile.txt -Destination C:\Temp
Remove-PsDrive -Name X
If your destination is a http address you could perform following actions:
Invoke-WebRequest -Uri http://some.uri -Method Get -OutFile C:\temp\myfile -Credential (Get-Credential)
Hope that helps
Instead Of this:
psexec.exe \\remoteServer.0.1 -u username -p password -dbg -lo D:\PsExec.log cmd /c "powershell -command "& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }""
DO this:
psexec.exe \\remoteServer.0.1 -u 'username' -p 'password' powershell.exe -Command "& {(New-Object System.Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file')}"
This should do your work.
Hope it helps.

Running a PS1 script using a batch file (.bat)

Currently the following is my path for launching the VMware vSphere PowerCLI command prompt. I wish to run my sample.ps1 script automatically using a batch file. How can I incoporate sample.ps1 into this path and create a batch file?
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -psc "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" -noe -c ". \"C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1\""
If you are working with PowerShell 2.0, you can use the -file parameter of PowerShell.exe
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -psc "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" -noe -file "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"
If you are working with PowerShell 1.0, you can use -command parameter this way
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -psc "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" -noe -command "& 'C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1'"
echo off
Title,Report Script &color 9e
for /f "usebackq delims=$" %%a in (`cd`) do (
set SCRIPTDIR=%%a
)
(Set ScriptFile=%SCRIPTDIR%\Report.ps1)
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -psc "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" -c ". \"C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1\";%ScriptFile%"
You can use this to launch arbitrary .ps1 scripts via .bat files by calling the bat file like your ps1. Then extract the name of file in batch and call powershell with it.
For a ready to use solution, use the following Gist: https://gist.github.com/JonasGroeger/10417237
I saw this code in another page, I test it in a W2012 R2 and it runs.
I hope it work:
C:\>powershell "C:\>1\file.ps1"