Jenkins and powershell. Download file - powershell

I have a script in Powershell and want to run this on many servers.
It's running from Jenkins via a Powershell step, the input param $env:servers
Simple example:
$SrvPassword = ConvertTo-SecureString -String "$($ENV:SlavePassword)" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("$ENV:SlaveUser", $SrvPassword)
Invoke-Command -Computername $env:servers -ScriptBlock {
$client = New-Object System.Net.WebClient
$client.DownloadFile("\\server1.domain.ru\123\123.zip","C:\123.zip")
} -Credential $cred
But when I build it with parametrs, i got error:
[firstDeploy] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\ADMINI~1\AppData\Local\Temp\jenkins6658148949844825772.ps1'"
Exception calling "DownloadFile" with "2" argument(s): "Access to the path '\\server1.domain.ru\123\123.zip' is denied."
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
+ PSComputerName : server2.domain.ru
When i do this without jenkins all work fine. Share full access. What's wrong?

Related

How to use SSISDeploy command in powershell script

I'm running SSISDeploy command (documentation is here) in my CMD:
SSISDeploy.exe -s:"download\Integration Services.ispac" -d:catalog;/SSISDB/TEST/DEVOPS;"TEST03,1234" -at:win
all working good, and now I need to run it thought powershell script (against windows server 2019 slave), so I tried this syntax:
$SSISDeploy = Start-Process -FilePath SSISDeploy.exe -ArgumentList '/source:"download\Integration Services.ispac"',"/destination:catalog;${Target};"${Env}"" -at:win -wait -PassThru -Credential $cred -RedirectStandardOutput ssisstdout.txt -RedirectStandardError ssisstderr.txt
but it fails with exception:
Start-Process : A positional parameter cannot be found that accepts argument 'TEST03,1234'.
+ ... SISDeploy = Start-Process -FilePath SSISDeploy.exe -ArgumentList '/so ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand
Can you suggest what's wrong with the syntax?
$StartProcessProps = #{
FilePath = 'SSISDeploy.exe'
ArgumentList = '-s:"download\Integration Services.ispac" -d:catalog;{0};{1} -at:win' -f $Target, $Env
Wait = $true
PassThru = $true
Credential = $cred
RedirectStandardOutput = 'ssisstdout.txt'
RedirectStandardError = 'ssisstderr.txt'
}
$SSISDeploy = Start-Process #StartProcessProp

Creating user policy Powershell MicrosoftTeams session error

When I try to create a user policy for my active directory I get this error:
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is
not null or empty, and then try the command again.
At C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\2.3.1\net472\SfBORemotePowershellModule.psm1:22959 char:38
+ ... -Session (Get-PSImplicitRemotingSession -CommandName 'New-CsApplic ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
The code that I'm using is this:
Import-Module MicrosoftTeams
# Get the credentials
$password = ConvertTo-SecureString -AsPlainText -Force -String "password"
$credentials = New-Object System.Management.Automation.PsCredential("email", $password)
# Connect to Microsoft Teams
Connect-MicrosoftTeams -Credential $credentials
New-CsApplicationAccessPolicy -Identity Random -AppIds "appid" -Description "Users"
Grant-CsApplicationAccessPolicy -PolicyName Random -Identity "userObjectId"
I know that the command New-CsApplicationAccessPolicy is creating the error but my guess is that it's caused by the command Connect-MicrosoftTeams because from what I can understand is that Connect-MicrosoftTeams creates a session.
Is there a way to set the session via a parameter or is this something you need to do outside this method?

Method invocation error when using PSCredential in Powershell

I will start by saying that I have successfully tested this script when running locally on my laptop against a remote dev server.
However, when I have migrated the script to our TFS server, I am now encountering the below (sanitized) error message.
2019-06-10T18:46:05.8256626Z Generating script.
2019-06-10T18:46:05.8257313Z Formatted command: . 'E:\***.ps1' -username "***" -password "***" -servername "***" -ScriptPath "***" -SourcePath "***" -DestinationPath "***" -CleanupFlag "***"
2019-06-10T18:46:06.0290179Z ##[command]"C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'E:\***.ps1'"
2019-06-10T18:46:06.7520864Z Method invocation failed because [System.Management.Automation.PSCredential] does not contain a method named 'new'.
2019-06-10T18:46:06.7521292Z At E:\***.ps1:5 char:1
2019-06-10T18:46:06.7521480Z + $CredentialSec = [System.Management.Automation.PSCredential]::new($username,$PWsec)
2019-06-10T18:46:06.7523016Z + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2019-06-10T18:46:06.7523588Z + CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException
2019-06-10T18:46:06.7524614Z + FullyQualifiedErrorId : MethodNotFound
2019-06-10T18:46:06.7525361Z
2019-06-10T18:46:06.8602349Z ##[error]PowerShell exited with code '1'.
The script is attempting to Invoke-Command (to run a different script) on a remote system. It appears to be messing up at the section where it creates a credential from the username and encrypted password.
This is the code that I'm attempting to execute:
param($username, $password, $servername, $ScriptPath, $SourcePath, $DestinationPath, $CleanupFlag)
$PWsec = ConvertTo-SecureString -String $password -AsPlainText -Force
$CredentialSec = [System.Management.Automation.PSCredential]::new($username,$PWsec)
Invoke-Command -ComputerName $servername -Credential $CredentialSec -FilePath $ScriptPath -ArgumentList $SourcePath, $DestinationPath, $CleanupFlag
Per mcclayton's suggestion in the comments... because the new server is running an older version of Powershell, it worked when I changed from this format:
$CredentialSec = [System.Management.Automation.PSCredential]::new($username,$PWsec)
To this format:
$CredentialSec = New-Object System.Management.Automation.PSCredential($username,$PWsec)

Adding Shared Printer to Remote Computer via Powershell

I am unable to run an invoke-command script to install printers on a remote machine. My code works locally, but as soon as I pipe it into Invoke-command, i get errors.
Local:
$Printer = "\\server1\printer1"
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($Printer)
And this adds the printer just fine. I can do this same command on the remote computer with no issues. But when i tried to execute the command remotely I have the issues.
Remote:
$compname = "computer"
$Printer = "\\server1\printer1"
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer')}
Which returns the error "The printer name is invalid"
So I tried to see what the shell was sending to the remote computer with the following code, and everything in the write output looks good, but I still get errors:
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer'); write-host "(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer')"}
Output:
Exception calling "AddWindowsPrinterConnection" with "1" argument(s): "The printer name is invalid. (Exception from
HRESULT: 0x80070709)"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : computer
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('\\server1\printer1')
Edit 1/5/2015
So I've tried Paul's code with a number of different entries to the argumentlist. All have not worked so far. i think the first 3 are closer to an answer.
-ArgumentList ""\\server1\printer1""
-ArgumentList ""'\\server1\printer1'""
-ArgumentList "\"\\server1\printer1""
Results in:
Invoke-Command : A positional parameter cannot be found that accepts argument '\\server1\printer1'.
At line:1 char:1
+ Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Ne ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
-ArgumentList "'\\server1\printer1'"
-ArgumentList \'"\\server1\printer1"'
-ArgumentList \""\\server1\printer1""
-ArgumentList \"\\server1\printer1"
Result in:
Exception calling "AddWindowsPrinterConnection" with "1" argument(s): "The printer name is invalid. (Exception from
HRESULT: 0x80070709)"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : sso-mxl327082y
Try this:
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($args[0]); write-host "(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($($args[0]))"} -ArgumentList "\\server1\printer1"
I think it´s because your $printer variable is placed between single quotes, variables between single quotes are not interpreted by powershell. So the printername your function probably gets is "$printer".
In case you wonder it is printed out correctly in your write-host statement because here the single quotes are inside a string.
you need to use $Using:yourvar to pass variables to the scriptblock
$compname = "computer"
$Printer = "\\server1\printer1"
Invoke-Command -ComputerName $CompName -Scriptblock
{
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($Using:$Printer)
}
I think it's because of the so called 'double hop problem', where your authentication isn't transfered to the next remote computer which is sharing the printer.
I tried to solve similar problem using add-printer and following this article double hop problem solution.
However, although it works with get-childitem etc. it doesn't work with add-printer cmdlet.

Powershell - Secure String for Passwords and SFTP

I am trying to implement a way to use a stored secure string so that my SFTP password is not visiable in the script. For example, I'd like to generate a variable $password that could be used instead. I found the following examples online but I can't get them to work unfortunately. I've done something similar in the past but can find my notes or links to the website that explained how to complete the task.
read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
Here is my script. Here is a link to the snapin if anyone is interested. http://www.k-tools.nl/index.php/sftp-in-powershell/
#Add the SFTP snap-in
Add-PSSnapin KTools.PowerShell.SFTP
#Define some variables
$sftpHost = "ftp.domain.com"
$userName = "user"
$userPassword = "password"
$localFile = "C:\bin\emp1.xlsx"
#Open the SFTP connection
$sftp = Open-SFTPServer -serverAddress $sftpHost -userName $userName -userPassword $userPassword
#Upload the local file to the root folder on the SFTP server
$sftp.Put($localFile)
#Close the SFTP connection
$sftp.Close()
Again, thanks for everyones help!
UPDATE
I tried this:
$pass = cat c:\bin\ftpcreds.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "usertest1",$pass
$sftpHost = "ftp.domain.com"
$userName = $mycred.username
$userPassword = $mycred.password
$sftp = Open-SFTPServer -serverAddress $sftpHost -userName $userName -userPassword $userPassword
$sftp.Put($localFile)
$sftp.Close()
And get this error:
Method invocation failed because [Tamir.SharpSsh.jsch.JSchException] doesn't contain a method named 'Put'.
At C:\bin\SFTP Upload Samples.ps1:21 char:1
+ $sftp.Put($localFile)
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [Tamir.SharpSsh.jsch.JSchException] doesn't contain a method named 'Close'.
At C:\bin\SFTP Upload Samples.ps1:36 char:1
+ $sftp.Close()
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Any suggestions?
Thanks!
If your SFTP is wanting to use a decrypted version of your secured password then you'll want to extract it from your $mycred by:
$userpassword = $mycred.getnetworkcredential().password.tostring()