Trouble Trying to Hide Email From Address List Using PowerShell - powershell

I am trying to run a simple command to hide an email account from the address list using PowerShell. Here is my code so far.
cls
$EmployeeEmail = "user#example.com"
#Need to hide the Mailbox from address list
$MethodName = "Hide Email Account"
$username = "staff"
$password = "accounts"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://Exchmbca1.example.local/PowerShell/ -Authentication Kerberos -Credential $cred
Import-PSSession $Session
Set-Mailbox -Identity $EmployeeEmail -HiddenFromAddressListsEnabled $true
Remove-PSSession $Session
However, when I run this command I receive the following error message:
The operation couldn't be performed because object 'user#example.com' couldn't be found on 'servername.example'.
I have tried changing the value of the -Identity I pass to the Set-Mailbox cmdlet with 'DOMAIN\username' as well and I receive the same error. I know the account exists because I can do a search using Get-ADUser and find the account with the SAMAccountName. Any help would be much appreciated. Thanks!

Related

Hide specific emails From Address Lists

I try to hide specific emails From Address Lists in 365.
Import-Module MSOnline
$TenantUname = "****"
$TenantPass = cat "C:\****.key" | ConvertTo-SecureString
$TenantCredentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $TenantUname, $TenantPass
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $TenantCredentials -Authentication Basic -AllowRedirection
Import-PSSession $Session -AllowClobber
Connect-MsolService -Credential $TenantCredentials
ForEach ($mailbox in (Import-Csv c:\email.csv))
{
Set-Mailbox -Identity $mailbox.Identity -HiddenFromAddressListsEnabled $True
}
In my CSV file identity is the emails of users.
But from some reason, this is not work
I will be very happy to help.

Remote execution on Exchange server failed

I want to remote enable the email-address-policy for a single mailbox on a exchange server (2010).
I can do this:
$samaccountname = $args[0] # gets sam from command line
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName Set-Mailbox
Get-Mailbox -Identity $samaccountname | Set-Mailbox -EmailAddressPolicyEnabled $True
Remove-PSSession $Session
It works if I open a powershell as administrator on the Orchestrator server. Then it executes the command on the exchange server as it should.
But the script does not work if Orchestrator tries to execute it. I do not know what settings Orchestrator uses when executing it. But I have a similar script, which is working with Orchestrator.
$samaccountname = $args[0] # gets sam from command line
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName enable-mailbox
$username_param = $samaccountname
$emailalias_param = $samaccountname
Invoke-Command -ArgumentList $username_param,$emailalias_param –session $Session -scriptblock {
param($username_exc, $alias_exc)
Enable-Mailbox -Identity $username_exc -Alias $alias_exc -DomainController 'xyzdc01.zfpdom.zfp'
}
Remove-PSSession $Session
This script makes a new mailbox. It is working.
Can anyone show me a solution for the first script? I am totally new in powershell so I can't figure it out. Maybe someone can change my first script to do it with this Invoke-Command scriptblock. I am sure, then it will work.
Thank you.
Greetings
Replace the commands inside the invoke-command, and the variables accordingly. Also, add the get-mailbox commandlet to the session. I am not able to try it, though, so I added the -verbose and -whatif switches as a failsafe. Note that if the samaccountname variable is empty, the Set-Mailbox will run on all mailboxes. The script can be tested standalone before running it in the Orchestrator.
$samaccountname = $args[0] # gets sam from command line
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName Set-Mailbox,Get-Mailbox
Invoke-Command -ArgumentList $samaccountname –session $Session -scriptblock {
param($username_exc)
Get-Mailbox -Identity $username_exc| Set-Mailbox -EmailAddressPolicyEnabled $True -verbose -whatif # remove the -whatif to perform changes
}
Remove-PSSession $Session
Another working solution I have found out:
#Parameter Laden
$samaccountname = $args[0] # $samaccountname wird übergeben
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName Set-Mailbox,Get-Mailbox
Get-Mailbox -Identity $samaccountname | Set-Mailbox -EmailAddressPolicyEnabled $True
Remove-PSSession $Session

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

Execute remote PS command properly

I'm trying to change passwords on more than 1000 hosts running windows server 2008/2012. They assigned to different domains, so I connect to them via their IP, all of them have PowerShell remoting open.
Stuck at my script implementation. For now I just want to connect to single host and change the password of the user or admin whatever.
Here is the code I use
$username = "UserWhose Password I want to change"
$password = ConvertTo-SecureString "users old password" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
$serverNameOrIp = "host ip address here"
$s = New-PSSession -ComputerName $serverNameOrIp -Authentication default -Credential $cred
#invoke the scriptblock remotely
$sb = {
"[ADSI]`$Admin=`"WinNT://$env:COMPUTERNAME/$env:USERNAME`""
"`$Admin.SetPassword(`"Users new password`")"
}
Invoke-Command -Session $s -ScriptBlock $sb
Remove-PSSession $s
Now, the console output I get:
PS C:\> ./script
[ADSI]$Admin="WinNT://WIN-TA49U0TR9GT/Administrator"
$Admin.SetPassword("Users new password")
PS C:\>
"WinNT://WIN-TA49U0TR9GT/Administrator" belongs to remote host, my local computername and a username are different.
I'm not getting any error or proper output here. The password isn't changing. If I try to run these commands manually on any host - it works.
Any suggestions? Maybe a working solutions?
You define the commands you want to run on the remote host as strings inside a scriptblock. When you invoke the scriptblock on the remote host it does what PowerShell does with all bare strings: echo them.
Remove the outer quoting and escaping and the code should work as you expect:
$sb = {
[ADSI]$Admin = "WinNT://$env:COMPUTERNAME/$env:USERNAME"
$Admin.SetPassword("Users new password")
}
The scriptblock already prevents variables from being expanded in the current context.
Posting complete working script, that accept console arguments, connect to specified host and change the user password.
ARGS = IP USERNAME OLDPASS NEWPASS
Hope this will help somebody
$serverNameOrIp = $args[0]
$username = $args[1]
$password = ConvertTo-SecureString -String $args[2] -AsPlainText -Force
$newPassword = $args[3]
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
$s = New-PSSession -ComputerName $serverNameOrIp -Authentication default -Credential $cred
$sb = {
param($newPassword)
[ADSI]$Admin = "WinNT://$env:COMPUTERNAME/$env:USERNAME"
$Admin.SetPassword($newPassword)
}
Invoke-Command -Session $s -ScriptBlock $sb -args $newPassword
Remove-PSSession $s

Hardcode password into powershells "New-PSSession"

I have a script to get and set user's Windows environment variables on other computers for a given user. Is it possible to hard code the password for this user so that I don't have to type it every time I run the script?
My script looks something like this:
$s5 = New-PSSession -computername testauto2, testauto3 -Credential
Domain\testautouser
invoke-command -session $s5[0] -scriptblock {[Environment]::GetEnvironmentVariable("TestBrowser", "user")}
Yep - you can totally do this as long as you are comfortable with the security implications (a PW in a file somewhere)...
Here's an example:
$pw = convertto-securestring -AsPlainText -Force -String <insert pw here>
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "Domain\User",$pw
$session = new-pssession -computername <computer> -credential $cred
I've used this approach in similar situations. It's certainly not perfect, but it makes me much less nervous than hardcoding a password in a file. I read and store the password during the first run, then read from the DPAPI-encrypted file afterward. I generally run scripts from a shared location on an internal network, and store the encrypted password file in a private folder on my local machine.
$user = "Domain\testautouser"
$passwdFile = "$env:USERPROFILE\myscript-$user"
if ((Test-Path $passwdFile) -eq $false) {
$cred = new-object system.management.automation.pscredential $user,
(read-host -assecurestring -prompt "Enter a password:")
$cred.Password | ConvertFrom-SecureString | Set-Content $passwdFile
}
else {
$cred = new-object system.management.automation.pscredential $user,
(Get-Content $passwdFile | ConvertTo-SecureString)
}