Powershell script in declarative jenkins pipeline - powershell

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

Related

Connect-AzureAD PowerShell in Azure Function fails

Not related to Connect-azureAD powershell in azure function
I have a simple Azure function (HTTP trigger) written in PowerShell.
$user = 'user#domain.com';
$pass = 'password';
Import-Module AzureAD -UseWindowsPowerShell;
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force;
$cred = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd);
Connect-AzureAD -Credential $cred;
Disconnect-AzureAD;
Get-PSSession | Remove-PSSession;
The first time it runs, it works. If I hit it again, it throws an exception "Exception calling "GetSteppablePipeline" with "1" argument(s): "The parameter is incorrect." If I call it again after an hour, it works again (1 time), then it fails again with the same error.
Any ideas?
Thank you!
I have tested in my environment.
Please use the below code :
$user = 'user#domain.com';
$secpasswd = 'password' | ConvertTo-SecureString -AsPlainText -Force;
Import-Module AzureAD -UseWindowsPowerShell;
$cred = New-Object Management.Automation.PSCredential ($user, $secpasswd);
Connect-AzureAD -Credential $cred;
Disconnect-AzureAD;

Start powershell script with credentials of other user isn't working

I try to run script with higher permissions using -credential argument
When I try to do it using this part of code it shows that error which basically means that The name of the directory is incorrect. Both script (that one that contain start-process and the change_permissions.ps1 are in the same folder which is \\srv1\Projekty\nowy_folder.
Without -credential argument script works completely fine.
Here's whole script:
#gui
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form_start = New-Object System.Windows.Forms.Form
$form_start.Text = 'Tworzenie projektu'
$form_start.Size = New-Object System.Drawing.Size(340,175)
$form_start.StartPosition = 'CenterScreen'
$permission_button = New-Object System.Windows.Forms.Button
$permission_button.Location = New-Object System.Drawing.Point(95,25)
$permission_button.Size = New-Object System.Drawing.Size(135,23)
$permission_button.Text = 'Przydziel uprawnienia'
$permission_button.add_Click({
$username = "DOMAIN\USER"
$password = "PASSWORD"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
# Invoke-Command -FilePath "\\srv1\nowy_folder\change_permissions.ps1" -Credential $credentials
Start-Process powershell -argumentlist '.\change_permissions.ps1' -workingdirectory "S:" #-Credential ($credentials)
# Using UNC instead of .\change_permissions.ps1 isn't working
})
$form_start.Controls.Add($permission_button)
#Code below is basically the same but runs other script which also isn't running properly
$create_folders_button = New-Object System.Windows.Forms.Button
$create_folders_button.Location = New-Object System.Drawing.Point(110,75)
$create_folders_button.Size = New-Object System.Drawing.Size(100,23)
$create_folders_button.Text = 'Utwórz katalogi'
$create_folders_button.add_Click({
$username = "DOMAIN\USER"
$password = "PASSWORD"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process powershell -argument "C:\Projekty\nowy_folder\make_project_folder_with_subfolders.ps1" -Credential ($credentials)
# $form_start.close()
})
$form_start.Controls.Add($create_folders_button)
$form_start.Topmost = $true
$form_start.ShowDialog()
As you may noticed I tried the invoke-command as well. While using the invoke-command another error shows up:
Do you have any solution to my problem?
Regarding such approach
Invoke-Command -FilePath c:\scripts\test.ps1 -ComputerName Server01
The FilePath parameter specifies a script that is located on the local computer. The script runs on the remote computer and the results are returned to the local computer.
if your file is locally saved, then you can try:
Invoke-Command -FilePath $localPath -computername srv1 -Credential $credentials
or you can use full path with such approach:
Invoke-Command -computername srv1 -scriptblock { \\srv1\nowy_folder\change_permissions.ps1} -Credential $credentials
or you can use direct path
Invoke-Command -computername srv1 -scriptblock { c:\scripts\change_permissions.ps1} -Credential $credentials

"Start-Process : This command cannot be run due to the error: Access is denied." when specifying credentials?

Good morning :S.
I can enter into a PSSession and execute cmdlets just fine, however, as soon as I specify an account to use, it just throws back an access is denied error. I've even tested with the same account and password that established the PSSession. This works locally just fine.
I am trying to integrate this into an SCCM application, so there isn't a whole lot of wiggle room.
EDIT: I put an easier code that doesn't work either below:
$username = 'DOMAIN\Username'
$password = 'P#ssword'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process Notepad.exe -Credential $credential
#Execute variable
$myCommand = "'C:\Program Files (x86)\PGP Corporation\PGP Desktop\pgpwde' --status --disk 0"
#Credential Variables
$username = 'DOMAIN\USERNAME'
$Password = ConvertTo-SecureString -String 'P#ssword' -Force -AsPlainText
$credential = New-Object System.Management.Automation.PsCredential -ArgumentList $username, $Password
#Expression Variable
$expression = #"
try
{
& $myCommand | Out-File `C:\test.txt -Force
}
catch
{
`$_.Exception.Message | Out-File `C:\ERROR.txt -Force
}
"#
#Execute
Start-Process powershell.exe -ArgumentList "-c $expression" -Credential $credential

Powershell run exe as different user

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

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