Connect-AzureAD PowerShell in Azure Function fails - powershell

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;

Related

"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

You must call the Connect-MsolService cmdlet before calling any other cmdlets

I have powershell script that connects to the Msol service .When i tried to run the script it works locally(powershell commandline Vscode) but when i try to run script via Active batch it is giving me error "You must call the Connect-MsolService cmdlet before calling any other cmdlets" .
$secpasswd = ConvertTo-SecureString "" -AsPlainText -Force
$EXOCred= New-Object System.Management.Automation.PSCredential ("",$secpasswd)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $EXOCred -Authentication Basic -AllowRedirection
Import-PSSession $Session -AllowClobber
$secpasswd = ConvertTo-SecureString "" -AsPlainText -Force
$MSOCred= New-Object System.Management.Automation.PSCredential ("",$secpasswd)
Connect-MsolService -Credential $MSOCred
$RoleObject = Get-MsolRole | Where-Object{$_.Name -match $roles}
$members= Get-MsolRoleMember -RoleObjectId $RoleObject.ObjectId
Can anyone help as i am getting error when executing the script in Active Batch

Get-CsUserSession StartDate parameter error & credentials without being prompt for a password

EDIT:
I want to retrieve session data from a specific account using
PowerShell. According to this documentation:
https://learn.microsoft.com/en-us/powershell/module/skype/get-csusersession?view=skype-ps
Get-CsUserSession command is able to do this. I am using this
command according to the upper's link example
Get-CsUserSession -User account#companyX.onmicrosoft.com -StartDate "6/1/2018 07:00 PM"
and then I am getting the following error:
A parameter cannot be found that matches parameter name 'StartDate'.
+ CategoryInfo : InvalidArgument: (:) [Get-CsUserSession], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.Rtc.Management.Hosted.Data.GetCsUserSessionCmdlet
+ PSComputerName : admin1e.online.lync.com
What is wrong with that and what is the correct declaration?
I am making a connection to Skype for business service with the following script:
$credential = Get-Credential
Import-Module MSOnline
Connect-MsolService -Credential
$credential Import-Module SkypeOnlineConnector
$lyncSession = New-CsOnlineSession -Credential
$credential Import-PSSession $lyncSession
What I would like to do is to set using a particular static account and password from the PowerShell script (using some sort of declaration variable strings), instead of running this command and have to type the credentials in a separate window. Meaning that I want to avoid using $credential = Get-Credential command. Is this possible?
As stated in documentation you linked (only at the top paragraph though), you have to use StartTime not StartDate. The error you receive is the typical symptom that you either has a typo in parameter name or this parameter doesn't exist for that function.
I'll request to change the example in the docs a bit later, seems like someone who wrote them were mixing up with another cmdlet.
Edit: to store credentials you can export your password like this:
"P#ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File C:\Users\username\password2.txt
And then import like this:
$password = Get-Content -Path "C:\Users\USUARIOPC\password2.txt" | ConvertTo-SecureString -String $password
$credential = New-Object System.Management.Automation.PsCredential("yourlogin#domain.com", $password)
In the meantime, I tried the following query. Probably is not too safe to use a password in a script but for us who want to do it like this is a nice solution.
$username = "account1#companyX.onmicrosoft.com"
$password = "abcdefg"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$credential = $cred
Import-Module MSOnline
Connect-MsolService -Credential $credential
Import-Module SkypeOnlineConnector
$SFBSession = New-CsOnlineSession -Credential $credential
Import-PSSession $SFBSession

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

Run an Application form Powershell with Credentials

I am using the Invoke-Item command to start an application. When I run it, it prompts for username and password. I want to auto fill that through PowerShell, can this be achieved?
You can you the [-Credential <PSCredential>] parameter with a PSCredential object to do this:
# Edit your creds here
$user = "Domain\Username"
$password = ConvertTo-SecureString "MyPassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($user, $password)
Invoke-Item "Your Application" -Credential $mycreds