Import pfx file with sn.exe using powershell - powershell

I am trying to install pfx file automatically every time the Azure Pipeline runs. Below is the powershell script i am trying to implement. I need it to provide the password automatically:
Set-Location "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools"
Start-Process -FilePath "sn.exe" -ArgumentList "-d",$container
Start-Sleep 2
Start-Process -FilePath ".\sn.exe" -ArgumentList "-i","c:\cert_2013.pfx",$container -NoNewWindow
Start-Sleep 2
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait("$($CerPass){ENTER}")
Start-Sleep 2
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
When the pipeline runs the ps1 file it is erroring out at SendWait("$($CerPass){ENTER}") Step. Below is the exact error message:
Enter the password for the PKCS#12 key file:
Could not read password for PKCS#12 blob in c:\cert_2013.pfx --
Console input may not be redirected for password entry.
Exception calling "SendWait" with "1" argument(s): "Access is denied"
At line:1 char:1
+ & 'C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe' -NoLogo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Exception calli...cess is denied":String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
At C:\PowerShellScript\CertReInstall.ps1:18 char:46
+ [System.Windows.Forms.SendKeys]::SendWait("$($CerPass){ENTER}")
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : Win32Exception
[error]Non-Zero exit code: '1' for ComputerName: 'PQAFCTC1'
[error]Atleast one remote job failed. Consult logs for more details. ErrorCodes(s): 'RemoteDeployer_NonZeroExitCode'
[section]Finishing: Run PowerShell on Target Machines
I need it to be automatically send the password to the file when installing. When i run the ps1 file directly on the server it works fine, but I need this script to be part of pipeline task (azure devops pipeline).
Any help would be greatly appreciated.
Thank you!

Related

Powershell invoking DTUTIL error

I'm currently in the process of building a deployment process in octopus deploy and as part of that I want to use DTUTIL to create folders and load SSIS packages to our server.
This text "C:\Program Files (x86)\Microsoft SQL Server\130\DTS\Binn\dtutil.exe" /SourceServer [servername] /FC SQL;\;[foldername], with appropriate server and folder names, which works in DOS.
Here is the rub, if I use the same code in Powershell I get an error:
$Command ="`"C:\Program Files (x86)\Microsoft SQL Server\130\DTS\Binn\dtutil.exe`" /SourceServer MYSERVER /FC SQL;\;Folder1";
invoke-Expression $Command;
invoke-expression : At line:1 char:73
+ ... Files (x86)\Microsoft SQL Server\130\DTS\Binn\dtutil.exe" /SourceSe ...
+ ~
You must provide a value expression following the '/' operator.
At line:1 char:73
+ ... \Microsoft SQL Server\130\DTS\Binn\dtutil.exe" /SourceServer MYSERVER ...
+ ~~~~~~~~~~~~
Unexpected token 'SourceServer' in expression or statement.
At line:1 char:1
+ invoke-expression $Command
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : ExpectedValueExpression,Microsoft.PowerShell.Commands.InvokeExpressionCommand
Has anyone got any idea how to remedy this?
Anthony
You can execute the EXE using the & operator:
& "C:\Program Files (x86)\Microsoft SQL Server\130\DTS\Binn\dtutil.exe" /SourceServer MYSERVER /FC SQL;\;Folder1
Also, the above Invoke-Expression command failed in the same way when I ran it in PowerShell directly, this doesn't appear to be an issue with running the PowerShell within Octopus.

Install .cer certificate in "Trusted Devices" folder via PowerShell

I need to install .cer certificate into "Trusted Devices" folder because I have PowerShell script which automatically installs software and only thing that is blocks the hole script is windows which asks about trustworthy of the dongle driver.
I use this cmdlet inside Vagrant
vagrant.exe powershell -c "Import-Certificate -Filepath C:\vagrant\Microcosm.cer -CertStoreLocation Cert:\Local Computer\TrustedDevices"
Here is error message output
vagrant.exe : The following WinRM command responded with a non-zero exit status.
At line:1 char:2
+ vagrant.exe powershell -c "Import-Certificate -Filepath C:\vagrant\Microcosm.ce ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (The following W...ro exit status.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Vagrant assumes that this means the command failed!
Import-Certificate -Filepath C:\vagrant\Microcosm.cer -CertStoreLocation Cert:\Local Computer\TrustedDevices
Stdout from the command:
Stderr from the command:
#< CLIXML
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><S S="Error">Import-Certificate : A positional parameter cannot be found that accepts argument 'Computer\Trust
edDevices'._x000D__x000A_</S><S S="Error">At line:1 char:40_x000D__x000A_</S><S S="Error">+ ... lyContinue';Import-Certificate -Filepath C:\vagrant\Microcosm.cer -Ce ..._x000D__x000A_</S><S
S="Error">+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~_x000D__x000A_</S><S S="Error"> + CategoryInfo : InvalidArgument: (:) [Import-Certificate], P
arameterBindingException_x000D__x000A_</S><S S="Error"> + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.CertificateServices.Commands.ImportCertificateComm _x000D__x000A_</
S><S S="Error"> and_x000D__x000A_</S><S S="Error"> _x000D__x000A_</S></Objs>
Cert:\Local Computer\TrustedDevices has a space in it. Try this with escaped quotes around your path:
vagrant.exe powershell -c "Import-Certificate -Filepath C:\vagrant\Microcosm.cer -CertStoreLocation `"Cert:\Local Computer\TrustedDevices`""

Powershell scripts will not work with Jenkins plugin on Windows

I'm writing some pretty simple scripts in Powershell 32-bit and they are working fine.
For instance, I want to open internet explorer to a webpage and start typing in keys. The following code works fine when I run it in powershell ISE.
Add-Type –AssemblyName System.Windows.Forms
$url = "http://WebAddress"
$ie = New-Object -com "InternetExplorer.Application"
$ie.Navigate($url)
sleep 30
[System.Windows.Forms.SendKeys]::SendWait("{2}{tab}{H}{E}{L}{L}{O}")
I have downloaded a Windows PowerShell plugin and have executed the same code through it and received the following errors:
Building on master in workspace C:\Program Files\Jenkins\workspace\Jenkins Test
[Jenkins Test] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\WINDOWS\TEMP\hudson257018662776252417.ps1'"
New-Object : Creating an instance of the COM component with CLSID {0002DF01-000
0-0000-C000-000000000046} from the IClassFactory failed due to the following er
ror: 80004005.
At C:\WINDOWS\TEMP\hudson257018662776252417.ps1:4 char:17
+ $ie = New-Object <<<< -com "InternetExplorer.Application"
+ CategoryInfo : ResourceUnavailable: (:) [New-Object], COMExcept
ion
+ FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Comman
ds.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\WINDOWS\TEMP\hudson257018662776252417.ps1:5 char:13
+ $ie.Navigate <<<< ($url)
+ CategoryInfo : InvalidOperation: (Navigate:String) [], RuntimeE
xception
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "SendWait" with "1" argument(s): "Access is denied"
At C:\WINDOWS\TEMP\hudson257018662776252417.ps1:9 char:42
+ [System.Windows.Forms.SendKeys]::SendWait <<<< ("{2}{tab}{H}{E}{L}{L}{O}")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Is there a reason why my code will not work through Jenkins like it does in Powershell? I tried some simple echo scripts which worked fine, but any more complex and it throws an error.
You may need to set execution policy once: https://technet.microsoft.com/library/hh849812.aspx
Set-ExecutionPolicy Unrestricted
Run PowerShell as admin and run that command. There may be security concerns using Unrestricted. But if it works, read the link above and find the policy that works best in your context. Options are (copy/pasted from the link):
Restricted. Does not load configuration files or run scripts. Restricted is the default execution policy.
AllSigned. Requires that all scripts and configuration files be signed by a trusted publisher, including scripts that you write on
the local computer.
RemoteSigned. Requires that all scripts and configuration files downloaded from the Internet be signed by a trusted publisher.
Unrestricted. Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the Internet,
you are prompted for permission before it runs.
Bypass. Nothing is blocked and there are no warnings or prompts.
Undefined. Removes the currently assigned execution policy from the current scope. This parameter will not remove an execution policy
that is set in a Group Policy scope.

Remote Powershell Access denied for certain dll's execution for Sharepoint 2013

I am attempting to automate a sharepoint 2013 deployment via remote powershell from the build server. Everything executes as expected except when having anything to do with some class in sharepoint dll's such as (Microsoft.SharePoint.Publishing, Microsoft.SharePoint.Publishing.Navigation.WebNavigationSettings)
If I run the same script locally under the same credentials it runs fine.
I have considered the below:
The user has full admin right on both machines
Disabled UAC on the remote server
Followed the required Remote Powershell steps in thig post (http://social.technet.microsoft.com/Forums/sharepoint/en-US/09b60466-5432-48c9-aedd-1af343e957de/user-cannot-be-found-when-using-invokecommand-newspsite-on-sharepoint)
I set powershell to run as admin by defualt via the registry (New-Item -Path "Registry::HKEY_CLASSES_ROOT\Microsoft.PowershellScript.1\Shell\runas\command" -Force -Name '' -Value '"c:\windows\system32\windowspowershell\v1.0\powershell.exe" -noexit "%1"')
Script Code:
#Set the radio buttons value
$settings = New-Object Microsoft.SharePoint.Publishing.Navigation.WebNavigationSettings (,$rootWeb)
$settings.GlobalNavigation.Source = [Microsoft.SharePoint.Publishing.Navigation.StandardNavigationSource]::PortalProvider
#Set the radio buttons value
$settings.CurrentNavigation.Source = [Microsoft.SharePoint.Publishing.Navigation.StandardNavigationSource]::PortalProvider
write-host "I am here.........................."
$settings.Update()
#Set the Publishing Web
$SPPubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($rootWeb)
#Global Navigation Settings
$SPPubWeb.Navigation.InheritGlobal = $false
$SPPubWeb.Navigation.GlobalIncludePages = $false
The Remote Powershell output is as below:
I am here..........................
Exception calling "Update" with "0" argument(s): "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : UnauthorizedAccessException
+ PSComputerName : Contoso-DEVSP
Exception setting "GlobalIncludePages": "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
+ PSComputerName : Contoso-DEVSP
Many thanks in advance
You need to check CredSSP authentication. Remote PowerShell execution with SharePoint fails as the second hop translates the credentials to system credentials. If the task involves querying or updating DB server, it will fail as SYSTEM account will not have access the remote PowerShell on SQL Server. You need to enable CredSSP.
Check this blog post I wrote a while ago. This is not specific to SharePoint but it should apply to your scenario as well.
http://www.ravichaganti.com/blog/?p=1230

Powershell: Running a .msc applet as another user

I'm currently writing a powershell script that asks for a single set of admin credentials, and uses those to run relevant applications, pulled from a network-hosted CSV. When I try to run
Start-Process $tools[$userInput-1].path.toString() -credential $credential
(where $tools is returning "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc") I get the error below
Start-Process : This command cannot be executed because the input "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc" is an Invalid Application. Give a valid application and Run your command again.
At line:1 char:14
+ Start-Process <<<< "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc" -credential
Get-Credential
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
If I need to, I'll just write a .bat file and run that, but I'd rather avoid that whenever possible.
And the reason I'm not using Invoke-Item is because it can't take -Credential, even if the man file says otherwise.
.msc is a saved console file, the host of which is mmc, so to start this from powershell you could use syntax similar to the following:
$mmcPath = "C:\Windows\System32\mmc.exe"
$mscPath = "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc"
Start-Process -FilePath $mmcPath -ArgumentList $mscPath