Powershell run exe as different user - powershell

I have the following commands in a powershell script (within Jenkins):
$Command = "C:\Program Files\Microsoft SQL Server\150\DAC\bin\SqlPackage.exe"
$Parms = "/Action:Script /sf:DB.dacpac /Profile:publish.xml"
$Prms = $Parms.Split(" ")
& "$Command" $Prms
How can I run the SqlPackage.exe as another user?
PS: It is within Jenkins so I can't run the ps1 file or SqlPackage.exe using runas windows dialog.
EDIT:
I think I am very close, so far I have the following script.
$sb = [scriptblock]::create("& ""SqlPackage.exe"" ""/Action:Script /sf:DB.dacpac /Profile:publish.xml /TargetServerName:localdb /op:Publish.sql""")
$Secure_Password = ConvertTo-SecureString -String $parPassword -AsPlainText -Force
$Credential = New-Object -Type PSCredential($parUserId,$Secure_Password)
$Session = New-PSSession -ComputerName ServerName -Credential $Credential
Invoke-Command -Session $Session -ScriptBlock $sb
I am getting the following error:
*** Argument 'Action' has an invalid value: 'Script
/sf:DB.dacpac /Profile:publish.xml
/TargetServerName:localdb /op:Publish.sql'

instead of creating session, use start-process. I would recommend providing complete path to the dacpac file with SourceFile switch along with the Profile switch
$Command = "C:\Program Files\Microsoft SQL Server\150\DAC\bin\SqlPackage.exe"
$Parms = "/Action:Script /sf:DB.dacpac /Profile:publish.xml"
$Secure_Password = ConvertTo-SecureString -String $parPassword -AsPlainText -Force
$Credential = New-Object -Type PSCredential($parUserId,$Secure_Password)
Start-Process -Credentials $credential -FilePath $command -ArgumentList $Parms

Related

Powershell - Within Powershell ISE run multiple line script in Powershell

I have a script that runs in Powershell ISE but there is a part of that script that has to run in regular Powershell. The script that needs to run in Powershell has multiple lines.
When I try running the script like this:
<#
Some code runs up here
#>
$script = {
$PW = "Password1";
$PW = $PW | ConvertTo-SecureString -AsPlainText -Force;
Add-SQLAssessmentTask -ManagementGroup "SOME_ID_NUMBER" -SQLServerName $env:computername -WorkingDirectory C:\Temp\SQL -ScheduledTaskUsername domain\user -ScheduledTaskPassword $PW -Verbose;
}
$command = $script.ToString()
#Start-Process powershell -argumentlist $command
Start-Process powershell -argumentlist $script
I get the follow error:
When I run the script like this:
<#
Some code runs up here
#>
$arguments = "$PW = ""Password1""","$PW = $PW | ConvertTo-SecureString -AsPlainText -Force","Add-SQLAssessmentTask -ManagementGroup ""SOME_ID_NUMBER"" -SQLServerName $env:computername -WorkingDirectory C:\Temp\SQL -ScheduledTaskUsername domain\user -ScheduledTaskPassword $PW -Verbose"
Start-Process powershell -argumentlist $arguments
I get this error:
If I run each line in regular Powershell, one at a time, it works fine.
Any suggestions?
$Arguments is supposed to be a script block separated by semi-colons if you want to run multiple commands.
$arguments = {"$PW = ""Password1""";"$PW = $PW | ConvertTo-SecureString -AsPlainText -Force";"Add-SQLAssessmentTask -ManagementGroup ""SOME_ID_NUMBER"" -SQLServerName $env:computername -WorkingDirectory C:\Temp\SQL -ScheduledTaskUsername domain\user -ScheduledTaskPassword $PW -Verbose" }
Start-Process powershell -argumentlist $arguments

Powershell script in declarative jenkins pipeline

I am using environment credential to get the username and password. When I echo them they are printed perfectly as ****.
The next comes the powershell commands, when I run them separately, all the commands works perfectly. But through Jenkins pipeline it throws me the following error:
groovy.lang.MissingPropertyException: No such property: psw for class: groovy.lang.Binding
Can anyone explain is this correct way to incorporate powershell in Jenkins pipeline?
environment {
CREDENTIAL = credentials('Test')
}
stage('Deployment') {
steps {
echo "$CREDENTIAL_USR"
echo "$CREDENTIAL_PSW"
powershell """($psw = ConvertTo-SecureString -String $CREDENTIAL_PSW -AsPlainText -Force)"""
powershell """($mySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CREDENTIAL_USR, $psw -Verbose)"""
powershell """(Set-Item WSMan:/localhost/Client/TrustedHosts -Value "*" -Force)"""
powershell """($session = New-PSSession -ComputerName "192.111.111.111" -Credential $mySecureCreds)"""
In case someone is here, and still trying to figure out what is the issue. I will share the solution that worked for me.
Use escaping before variable "$" sign in multi-line string.
powershell ("""
\$psw = ConvertTo-SecureString -String \$CREDENTIAL_PSW -AsPlainText -Force
\$mySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList \$CREDENTIAL_USR, \$psw -Verbose
Set-Item WSMan:/localhost/Client/TrustedHosts -Value "*" -Force
\$session = New-PSSession -ComputerName "192.111.111.111" -Credential \$mySecureCreds
""")
You can easily run multiline powershell commands in jenkins pipeline like this. Example, if you want to login to azure using service principal, you'll do something like below:
powershell '''
$pass = ConvertTo-SecureString your_client_secret -AsPlainText –Force
$cred = New-Object -TypeName pscredential –ArgumentList your_client_id, $pass
Login-AzureRmAccount -Credential $cred -ServicePrincipal –TenantId your_tenant_id
-vaultName "eusdevmbe2keyvault" -name "normalizedcontainername").SecretValueText
'''
Check here for reference https://jenkins.io/blog/2017/07/26/powershell-pipeline/
At the moment you're running each line in its own powershell process, so the results of the line before are not available to the next command.
I think you just need to move the script into a multi-line string:
powershell ("""
$psw = ConvertTo-SecureString -String $CREDENTIAL_PSW -AsPlainText -Force
$mySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CREDENTIAL_USR, $psw -Verbose
Set-Item WSMan:/localhost/Client/TrustedHosts -Value "*" -Force
$session = New-PSSession -ComputerName "192.111.111.111" -Credential $mySecureCreds
""")

Can't copy files using xcopy when running batch file with powershell from remote

I'm trying to run a batch file to copy files from a remote computer (A) to a local Computer (B) - The two computers are in a workgroup and have full access to one another. I'm running the batch file with PowerShell script from the remote computer (A).
The batch file contain this command:
XCOPY \\buildagent01\C$\agent\_work\2\a\Bin\JobServer \\Automation\C$\QA\VLast\Backend\WinServices\JobServer
If I run this XCOPY command from the remote or local computer directly in the command prompt - the files are being copied, If I use powershell to run the batch file (Version.bat) that contains this command - 0 files are being copied...
this is how the PowerShell looks like:
#Predefine necessary information
$Username = "aaaa"
$Password = "*****"
$ComputerName = "Automation"
$Script = {\\Automation\C$\QA\Version.bat $args[0] $args[1] $args[2] $args[3] $args[4]}
$Binaries_Directory_Path = "\\buildagent01\C$\agent\_work\2\a\Bin\JobServer"
$QA_Fold = "\\Automation\C$\QA"
$Exclude = "\\Automation\C$\QA\Exclude.txt"
$Deployed_version_sufix = "1"
$BackupFoldPrefix = "BackupTo"
$Backup_Fold = $BackupFoldPrefix+$Deployed_version_sufix
#Create credential object
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord
#Create session object with this
$Session = New-PSSession -ComputerName $ComputerName -credential $Cred
#Invoke-Command
$Job = Invoke-Command -Session $Session -Scriptblock $Script -ArgumentList $Binaries_Directory_Path,$QA_Fold,$Backup_Fold,$Exclude,$Deployed_version_sufix
echo $Job
#Close Session
Remove-PSSession -Session $Session

Executing powershell remotely issue

Hi when i try to do some code:
$Username = 'us'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
powershell.exe -command "Invoke-Command -ComputerName server.com -scriptblock {pathCopyAndUnzip.ps1} -Credential $Cred"
This prompt me for a password but when i try to run this command like here (without powershell.exe):
Invoke-Command -ComputerName server.com -scriptblock {pathCopyAndUnzip.ps1} -Credential $Cred
it works without prompt. Do you know how to resolve that? I need to use option 1 because this command is runned from TFS build definition file like here:
<Exec Command="powershell.exe -command "Invoke-Command -ComputerName $(Server) -scriptblock {path} -Credential $Cred"" Condition="'$(RunTests)' == 'True'"/>
You could put your script into it's own file and then call that from TFS rather inline code.
C:\folder\script.ps1:
Param(
[string]$Username,
[string]$Password,
[string]$OtherParam,
)
$Password = $Password | ConvertTo-SecureString -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$Password
Invoke-Command -ComputerName server.com -FilePath "C:\folder\CopyAndUnzip.ps1 -Something $OtherParam" -Credential $Cred
Then call it like so:
<Exec Command="powershell.exe -command "C:\folder\script.ps1 -username user10 -password P#55w0rd -OtherParam Whatever" Condition="'$(RunTests)' == 'True'"/>
You could try to pipe the commands to powershell.exe like this:
'$Username = "us"; $Password = "password"; $pass = ConvertTo-SecureString -AsPlainText $Password -Force; $Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass; Invoke-Command -ComputerName server.com -scriptblock {pathCopyAndUnzip.ps1} -Credential $Cred' | powershell.exe -command -
<Exec Command="$(PsExecPath) -accepteula \\$(Server) cmd /C powershell -File FILEPATH " Condition="'$(RunTests)' == 'True'"/>
I used old good psExec :) Everything is work now.

Simple Powershell script doesn't work when compiled or run as a script

I have a simple snippet I can run no problems within the powershell console. When I compile it to an EXE, or even a ps1 and run it, it doesn't find the reg value, no idea why.
Here is the code:
$User = "Training\Administrator"
$PWord = ConvertTo-SecureString -String "P#ssWord" -AsPlainText -Force
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$creds = $Credentials
enter-pssession –computername Win7Client –credential $creds
Start-Sleep -s 2
Set-itemproperty “HKLM:\SOFTWARE\Citrix\Metaframe Password Manager\Extensions\SyncManager\Syncs\DefaultSync\Servers” -name Server1 -value \\DFSI\CPMStore
Return
I would change the last lines to:
$Pssn = new-psssession –computername Win7Client –credential $creds
invoke-command -Session $Pssn -scriptblock {Set-itemproperty “HKLM:\SOFTWARE\Citrix\Metaframe Password Manager\Extensions\SyncManager\Syncs\DefaultSync\Servers” -name Server1 -value \\DFSI\CPMStore }
Return
Hope this helps,
Luc