自动化Connect-AzureAD Powershell

时间:2017-11-29 08:30:25

标签: powershell azure-active-directory azure-ad-powershell-v2

我使用连接到AzureAD的powershell创建了一个脚本,并且使用以下方法正常工作:

Connect-AzureAD -TenantId $TenantId

登录窗口会弹出,我可以成功连接。但是,我需要将脚本设置为自动运行,因此我发现此代码可以执行此操作:

# Set Configs
$TenantId = "<tenant id>"
$AzureUser = "<user>" 
$AzurePass = Get-Content "cred.txt" | ConvertTo-SecureString

# Connect to Azure AD
$AzureCred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $AzureUser, $AzurePass
Connect-AzureAD -TenantId $TenantId -Credential $AzureCred

但我似乎无法让它发挥作用。我使用以下命令生成我的cred.txt文件:

Read-Host -assecurestring | convertfrom-securestring | out-file C:\cred.txt

当我运行它时,我收到以下错误:

  

Connect-AzureAD:发生了一个或多个错误:字符集   ContentType中提供的内容无效。无法将内容读取为字符串   使用无效的字符集。在行:9 char:1   + Connect-AzureAD -TenantId $ TenantId -Credential $ AzureCred   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~       + CategoryInfo:AuthenticationError:(:) [Connect-AzureAD],AadAuthenticationFailedException       + FullyQualifiedErrorId:Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
  Connect-AzureAD:发生了一个或多个错误。在行:9 char:1   + Connect-AzureAD -TenantId $ TenantId -Credential $ AzureCred   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~       + CategoryInfo:AuthenticationError:(:) [Connect-AzureAD],AggregateException       + FullyQualifiedErrorId:Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
  Connect-AzureAD:ContentType中提供的字符集是   无效。无法使用无效字符集将内容读取为字符串。   在行:9 char:1   + Connect-AzureAD -TenantId $ TenantId -Credential $ AzureCred   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~       + CategoryInfo:AuthenticationError:(:) [Connect-AzureAD],InvalidOperationException       + FullyQualifiedErrorId:Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
  Connect-AzureAD:'“utf-8”'不是受支持的编码名称。对于   有关定义自定义编码的信息,请参阅文档   Encoding.RegisterProvider方法。参数名称:name在行:9   焦炭:1   + Connect-AzureAD -TenantId $ TenantId -Credential $ AzureCred   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~       + CategoryInfo:AuthenticationError:(:) [Connect-AzureAD],ArgumentException       + FullyQualifiedErrorId:Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
  Connect-AzureAD:发生了一个或多个错误:字符集   ContentType中提供的内容无效。无法将内容读取为字符串   使用无效的字符集。在行:9 char:1   + Connect-AzureAD -TenantId $ TenantId -Credential $ AzureCred   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~       + CategoryInfo:NotSpecified:(:) [Connect-AzureAD],AadAuthenticationFailedException       + FullyQualifiedErrorId:Microsoft.Open.Azure.AD.CommonLibrary.AadAuthenticationFailedException,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD

我使用相同的脚本登录了另一个租户,但它运行正常。对于拥有联邦的租户而言,这是行不通的。除了关闭联合之外,还有其他解决方法吗?

1 个答案:

答案 0 :(得分:0)

我不确定为什么最初的脚本不适用于我们的租户。我的猜测是由于联邦。我实现了一个解决方案并尝试使用服务主体,而不是遵循这篇文章:

Connecting a session as a service principal