Issues with running script without credentials dialog box - powershell

I'm trying to run through a powershell script that creates a computername and places that computer in the right OU in AD. The only issue is I need to enter credentials for this to happen, but I want to do it without having to enter the credentials into the powershell credential dialog box.
I used the System.Management.Automation.PSCredential, but that is was apparently was giving me the dialog box.
$secpasswd = ConvertTo-SecureString 'xxxxxx' -AsPlainText -Force
$mycreds = New-Object System.Managemnet.Automation.PSCredential("xxxx", $secpasswd)
Trying to the use the code above without a dialog box popping up
New-Object : Cannot find type [System.Managemnet.Automation.PSCredential]: verify that the assembly containing this type is loaded.
At line:2 char:12
+ $mycreds = New-Object System.Managemnet.Automation.PSCredential("xxxx ...
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

You made a typo on "Managemnet". It should be -
$mycreds = New-Object System.Management.Automation.PSCredential("xxxx", $secpasswd)

It appears you made a typo in your code: Managemnet should be Management, as in System.Management.Automation. That is why your error is being thrown.
However, there is no need to use the full definition for PSCredential. Use the following instead:
$secpasswd = ConvertTo-SecureString 'xxxxxx' -AsPlainText -Force
$mycreds = New-Object PSCredential("xxxx", $secpasswd)
This does not show a dialog box.

Related

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?

ExecuteCrmOrganizationRequest fails with PublishThemeRequest

I'm trying to write a powershell script to publish a theme in my on-premise installation of Dynamics CRM.
According to this page it should be really straight forward, I create an object of type PublishThemeRequest which derives from OrganizationRequest and call the method ExecuteCrmOrganizationRequest.
This is the code I'm running:
Import-Module Microsoft.Xrm.Data.Powershell
Add-PSSnapin Microsoft.Xrm.Tooling.Connector
$orgName = "<my organization name>";
$serverUrl = "http://server_url";
$Cred = Get-Credential -UserName "<my username>" -Message "Please Enter admin credentials for CRM"
$conn = Get-CrmConnection -Credential $Cred -OrganizationName $orgName -ServerUrl $serverUrl
$req = New-Object Microsoft.Crm.Sdk.Messages.PublishThemeRequest
$req.Target = New-CrmEntityReference -EntityLogicalName "theme" -Id "DB80D57A-6410-4D11-B784-0093122802AC"
$result = [Microsoft.Crm.Sdk.Messages.PublishThemeResponse]$conn.ExecuteCrmOrganizationRequest($req, $null)
This is what I get when I execute the code above:
Cannot convert argument "req", with value: "Microsoft.Crm.Sdk.Messages.PublishThemeRequest", for "ExecuteCrmOrganizationRequest" to type
"Microsoft.Xrm.Sdk.OrganizationRequest": "Cannot convert the "Microsoft.Crm.Sdk.Messages.PublishThemeRequest" value of type
"Microsoft.Crm.Sdk.Messages.PublishThemeRequest" to type "Microsoft.Xrm.Sdk.OrganizationRequest"."
At C:\Users\xxxxxxxxxx\Desktop\PublishTheme.ps1:21 char:1
+ $result = [Microsoft.Crm.Sdk.Messages.PublishThemeResponse]$conn.Exec ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
I have been reading the documentation and other websites for a couple of hours now but seem to have hit a wall.
Any ideas of what my problem might be?

Jenkins and powershell. Download file

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?

Creating Azure SQL Database Server connection context New-AzureSqlDatabaseServerContext

I am trying to create an Azure SQL Database connection context e.g.
$cred = Get-Credential
$ctx = New-AzureSqlDatabaseServerContext -ServerName “mydatabasename” -credential $cred
or
$pwd = ConvertTo-SecureString "[password1234]" -AsPlainText -Force;
$cred1 = New-Object System.Management.Automation.PSCredential -ArgumentList "databaseadmin", $pwd
New-AzureSqlDatabaseServerContext -ServerName "myservername" -Credential $cred1
And the response is:
New-AzureSqlDatabaseServerContext : Object reference not set to an instance of an object.
At line:2 char:8
+ $ctx = New-AzureSqlDatabaseServerContext -ServerName “myservername” - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureSqlDatabaseServerContext], NullReferenceException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet.NewAzureSqlDatabaseServerContext
I've been through the docs and google searches but to no avail.
https://msdn.microsoft.com/en-us/library/dn546736.aspx
http://sqlmag.com/powershell/manage-azure-sql-databases-powershell
Thanks
Pavel
I recently ran into this issue in a PS runbook. After doing some searching, I found a solution that worked for me. Hopefully it will help you.
The error message isn't particularly helpful (big surprise), but the null object being referenced is the Azure subscription; I'm assuming the exception bubbles up from within the cmdlet rather than being thrown by your own code. By adding these three lines to my code:
$cert = Get-AutomationCertificate -Name $automationCertificateName;
Set-AzureSubscription -SubscriptionName $subName -Certificate $cert -SubscriptionId $subID;
Select-AzureSubscription -Current $subName;
I was able to get past the exception. Above, $automationCertificateName is a variable asset that I added to the automation account. See https://github.com/Microsoft/sql-server-samples/tree/master/samples/manage/azure-automation-automated-export for details about how to set that up.
Here is how I successfully created connection context:
$sqlServerUser = "test-user"
$sqlServerUserPassword = "P#$$w0rd"
$sqlServerName = "mysqlserver"
$sqlCred = New-Object System.Management.Automation.PSCredential($sqlServerUser, ($sqlServerUserPassword | ConvertTo-SecureString -asPlainText -Force))
$sqlContext = New-AzureSqlDatabaseServerContext -ServerName $sqlServerName -Credential $sqlCred
Please see this for more details.

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