Cannot validate argument on parameter 'SourceMailbox' - powershell

Set-ExecutionPolicy RemoteSigned
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking
$group = Read-Host 'What is the Group Mailbox Name?'
$shared = Read-Host 'What is the Shared Mailbox Name?'
$deletedGroup=get-mailbox -SoftDeletedMailbox -GroupMailbox -Filter {name -like "$group*"}
$targetuser=get-mailbox -Identity "$shared"
New-MailboxRestoreRequest -SourceMailbox $deletedGroup.DistinguishedName -TargetMailbox $targetuser.DistinguishedName -AllowLegacyDNMismatch -Verbose
Get-MailboxRestoreRequest
I get the following error returned:
Cannot validate argument on parameter 'SourceMailbox'. The argument is null. Provide a valid value for the argument, and then try running the command again.
+ CategoryInfo : InvalidData: (:) [New-MailboxRestoreRequest], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,New-MailboxRestoreRequest
+ PSComputerName : outlook.office365.com

Related

Microsoft Powershell script running problem

I try to run following script:
Get-ExecutionPolicy
$UserCredential = Get-Credential
Create session to: https://outlook.office365.com/powershell-liveid/ with following:
$Session = New-PSSession -ConfigurationName Microsoft.Exchange
-ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential
-Authentication Basic -AllowRedirection
After I run the last script, it returns with following error:
"New-PSSession : [outlook.office365.com] Connecting to remote server outlook.office365.com failed with the following err
or message : Adgang nægtet. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:12
+ $Session = New-PSSession -ConfigurationName Microsoft.Exchange -Conne ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed"
If you're just trying to connect to Exchange the module ExchangeOnlineManagement , you can use this:
$creds = (Get-Credential)
Connect-ExchangeOnline -UserPrincipalName $creds.UserName
I've also had success using this:
$creds = (Get-Credential)
$exoSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $creds -Authentication Basic -AllowRedirection
Import-PSSession $exoSession -DisableNameChecking

Get-Credentials error in PowerShell 'Cannot find an Overload for "PSCredential"'

I'm new to PowerShell. I am trying to make it so I can setup a new computer connecting to the network to allow me to do certain tasks. When I run this:
$domain = "mydomain.com"
$mycred = get-credential
$credential = New-Object System.Management.Automation.PSCredential("$($domain)\$($mycred.Username)","$($mycred.Password)")
$compName = Read-Host -Prompt "Enter new computer name"
Add-Computer -DomainName $domain -newname $compName -Credential $credential -Restart
Pause
I get the error:
New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At C:\Users\entername\Downloads\1-JoinDomainCred.ps1:7 char:15
... redential = New-Object System.Management.Automation.PSCredential("$($ ...
CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Where am I going wrong?
Get-Credential aready returns a proper credentials object. Just use that:
$mycred = Get-Credential; Add-Computer ... -Credential $mycred
PowerShell is not C#, pass the arguments as an array without the ():
$credential = New-Object System.Management.Automation.PSCredential "$($domain)\$($mycred.Username)",$mycred.Password

Powershell core to powershell

I'm running an Ubuntu EC2 instance with Pwsh installed to remote execute AD commands on one of our servers. 2sd hop is set-up correctly and i'm able to run AD commands but when executing my script i get the following error (Scripts works fine directly on the 2sd hop machine):
The search filter cannot be recognized
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
+ PSComputerName : corpmaint02
#!/usr/bin/pwsh
$employeeEmail = 'myemail#contoso.com'
$session = New-PSSession -ComputerName corpmaint02 -ConfigurationName corpmaint02 -Credential contoso\myadminaccount
Invoke-Command -Session $session -ArgumentList $employeeEmail -ScriptBlock{
Get-ADUser -Filter "EmailAddress -eq '$employeeEmail'" -Properties EmailAddress | Disable-ADAccount
Write-Host $employeeEmail has been 'disabled.'
}
Remove-PSSession -ID $session.ID
[GC]::Collect()
Any help would be appreciated.
Update: new code:
#!/usr/bin/pwsh
$cred=Get-Credential domain\myadmin
$employeeEmail = 'myemail#contoso.com'
Invoke-Command -ComputerName corpmaint02 -Credential $cred -ConfigurationName corpmaint02 -Authentication Negotiate -ArgumentList $employeeEmail -$
Get-ADUser -Filter "EmailAddress -eq '$($Args[0])'" -Properties EmailAddress | Disable-ADAccount -verbose
Write-Host $employeeEmail has been 'disabled.'
}
I modified my code as follow and it works expect for the lack of permissions to disable the account which odd because my admin account has rights to do so.
Insufficient access rights to perform the operation
+ CategoryInfo : NotSpecified: (CN=xxxxx\domain,DC=com:ADUser) [Disable-ADAccount], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8344,Microsoft.ActiveDirectory.Management.Commands.DisableADAccount
+ PSComputerName : corpmaint02
New code to elevate:
#!/usr/bin/pwsh
$cred=Get-Credential domain\myadmin
$employeeEmail = 'user1#contoso.com'
Invoke-Command -ComputerName corpmaint02 -Credential $cred -ConfigurationName corpmaint02 -Authentication Negotiate -ArgumentList $employeeEmail,$cred -ScriptBlock{
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}
Get-ADUser -Filter "EmailAddress -eq '$($Args[0])'" -Properties EmailAddress | Disable-ADAccount -verbose -Credential $Args[1]
}
Write-Host $employeeEmail 'has been disabled.'
Invoke-Command isn't running with elevated rights, so you can retrieve data but not make changes.
https://ss64.com/ps/syntax-elevate.html
If you use Invoke-Command to run a script or command on a remote computer, then it will not run elevated even if the local session is. This is because any prompt for elevation will happen on the remote machine in a non-interactive session and so will fail.
You can try self elevating in the Invoke-Command scriptblock (from the link above)
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
# Relaunch as an elevated process:
Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
exit
}
# Now running elevated so launch the script:
& "d:\long path name\script name.ps1" "Long Argument 1" "Long Argument 2"

Problem with enter-pssession: "A positional parameter cannot be found that accepts argument"

I'm trying to set up PS Remoting/Win-RM and have the following:
$primary = 'server1'
$user = $env:UserName
$admUser = Get-Credential -UserName "domain\adm-$user" -Message 'Enter your *ADMIN* password:'
Enter-PSSession -ComputerName $primary -Credential $admUser {
hostname
}
However, this is returning the following error (I've tested this from a console and it works, so there's something wrong with my script):
Windows PowerShell credential request.
Enter your *ADMIN* password:
Password for user domain\adm-user1: ***************
Enter-PSSession : A positional parameter cannot be found that accepts argument '
hostname
'.
At line:5 char:1
+ Enter-PSSession -ComputerName $primary -Credential $admUser {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Enter-PSSession], ParameterBindingException
+ FullyQualifiedErrorId :PositionalParameterNotFound,Microsoft.PowerShell.Commands.EnterPSSessionCommand
What am I doing wrong? Thanks in advance!
Enter-PSSession opens a console connection to a remote system.
If you want to run a command on a remote system, you'd want to use Invoke-Command.
Also, you 100% always need to pass scriptblocks into some parameter (minus some edge cases where it's accepted by default). In this case, we need to use -Scriptblock.
Example:
Invoke-Command -ComputerName $primary -Credential $admUser -ScriptBlock {
hostname
}
or
$session = New-PSSession -ComputerName $primary -Credential $admUser
Invoke-Command -Session $session -ScriptBlock {hostname}
Invoke-Command -Session $session -ScriptBlock {$env:USERNAME}
Disconnect-PSSession -Session $session

Powershell command SetUser for a List

I am using the following command for about 100 users. I would like to put the email addresses in a list and have it run through them.
Set-User -Identity name#company.org -LinkedMasterAccount $null
Trying this
Import-Module activedirectory
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
http://servername/powershell -Authentication Kerberos -
Credential $mycredentials
Import-PSSession $session
$list=Get-Content "C:\Email.txt"
ForEach ($user in $list) {Set-User -Identity $user-LinkedMasterAccount $null}
This file exists and it looks to be interating through it - I get an error for each listed below
A positional parameter cannot be found that accepts argument '$null'.
+ CategoryInfo : InvalidArgument: (:) [Set-User],
ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Set-User
+ PSComputerName : servername.com
Put your emails in a txt file and loop through each of them like -
Get-Content \\PathToYourTextFile\File.txt | % { Set-User -Identity $_ -LinkedMasterAccount $null }