The member does not exist? Powershell script - powershell

I have been reading some questions and can find information on creating scripts but none seemingly using the object type "Computer".
Apologies if this is more suited to superuser. But this is still at the script level and as such I thought it would be best placed here.
Here is my script. I want to add a domain registered Server (Computer) to the performance monitor users group on a range of servers.
$ComputerName = Read-Host "Remote Computer name:"
$PmuGroup = [ADSI]"WinNT://$ComputerName/Performance Monitor Users,group"
$User = [ADSI]"WinNT://DOMAIN/ServerName,computer"
$PmuGroup.Add($User.Path)
The following error is displayed:
Exception calling "Add" with "1" argument(s): "A member could not be added to
or removed from the local group because
the member does not exist.
"
At line:1 char:1
+ $AdminGroup.Add($User.Path)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
If I enter $user into PS, it returns the Path and seemingly finds the machine.
Tried without .path as suggested in comments;
PS C:\WINDOWS> $PmuGroup.Add($User)
Exception calling "Add" with "1" argument(s): "Type mismatch. (Exception
from HRESULT: 0x80020005
(DISP_E_TYPEMISMATCH))"
At line:1 char:1
+ $PmuGroup.Add($User)
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
Is this an error with my script / can anyone please advise on any errors in it?
For info : Domain/ServerName is not what is being used. I have removed the actual name from here.

The samAccountName of a computer account always ends with a $:
$ComputerName = Read-Host "Remote Computer name:"
$PmuGroup = [ADSI]"WinNT://$ComputerName/Performance Monitor Users,group"
$Computer = [ADSI]"WinNT://DOMAIN/ServerName$"
$PmuGroup.Add($Computer.Path)

Related

Powershell create access policy Azure

I'm trying to create an access policy so that I can create meetings using Microsoft Graph API on the user's behalf. To do this I need to do a script that is similar to this:
Connect-MicrosoftTeams
New-CsApplicationAccessPolicy -Identity Random -AppIds "applicationid" -Description "Users"
Grant-CsApplicationAccessPolicy -PolicyName Random -Identity "userId"
But when I try to run the second line I get this error:
At C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\2.3.1\net472\SfBORemotePowershellModule.psm1:63 char:22
+ $remoteSession = & (Get-CsOnlineSessionCommand)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-CsOnlineSession], UnauthorizedAccessException
+ FullyQualifiedErrorId : UnauthorizedAccessException,Microsoft.Teams.ConfigApi.Cmdlets.GetCsOnlineSession
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
I'm guessing it has something to do with the first command that it's not remembering my login, but I can't find anywhere on how to do this. Does anyone know what I'm doing wrong and what the correct way is?.
Edit:
I finished the first problem. I needed to create an account on the active directory itself because Microsoft accounts weren't allowed. But my second error is still here:
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
Is there a way to set the session via a parameter or is this something you need to do outside this method?

Unable to run powershell script within powershell

If i run this code it will run the file
{Write-host "Please Enter the email address of the user you want to check the permissions"
$user = Read-Host
Powershell.exe C:\Temp\Report\Reports.ps1}
But if i run it like this which is what i need to do
{ Write-host "Please Enter the email address of the user you want to check the permissions"
$user = Read-Host
Powershell.exe C:\Temp\Report\Reports.ps1 -processOneDrive $true -OneDriveEmail $user}
I get this error
Powershell.exe : C:\Temp\ReportSharedFiles\ReportSharedFiles.ps1 : Missing an argument for parameter 'OneDriveEmail'. Specify a
At C:\Temp\ReportSharedFiles\Full Exchange Script Menu.ps1:88 char:2
+ Powershell.exe "c:\Temp\ReportSharedFiles\ReportSharedFiles.ps1" -pr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (C:\Temp\ReportS...il'. Specify a :String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
parameter of type 'System.String' and try again.
At line:1 char:71
+ ... haredFiles\ReportSharedFiles.ps1 -processOneDrive True -OneDriveEmail
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [ReportSharedFiles.ps1], ParameterBindingException
+ FullyQualifiedErrorId : MissingArgument,ReportSharedFiles.ps1
What am i doing wrong and how can i get this to work? any help will be appreciated
I believe its asking you for a sting parameter in the error
parameter of type 'System.String' and try again.
Hope this works out>
{ [string]$user = Read-Host "Please Enter the email address of the user you want to check the permissions"
Powershell.exe C:\Temp\Report\Reports.ps1 -processOneDrive $true -OneDriveEmail $user}
Type String >
I have figured it out. It seems when running the powershell script within another script and to have the arguments in. when it comes to the -processOneDrive $true It tried to convert that to boolem which caused errors. i changed this to 1 which im sure means true so code looks like this
Powershell.exe "c:\Temp\Report\Reports.ps1" -processOneDrive 1 -OneDriveEmail $user
Now it runs smoothly. Thanks for everyone that tried to help me with this :)

Powershell script for catching exception for adding group members to local group

I want to add members in Remote Desktop Users group and if i find "The specified account name is already a member of the group" exception then skip and move to other member to add.
I have tried below but it didnt catch the exception and keep giving me same error.. Please advice.
$LocalGroup = [ADSI]"WinNT://$env:computername/Remote Desktop Users,group"
$DomainGroup = [ADSI]"WinNT://Domain/Test Success Team"
$LocalGroup.Add($DomainGroup.path)
Try {
$LocalGroup.Add($DomainGroup.path)
} Catch [Microsoft.ActiveDirectory.Management.ADException] {
if ($_ -like "The specified account name is already a member of the group.")
{
Write-Host “!!! LOCAL GROUP ALREADY EXISTS !!!”
}
elseif ($_ -eq $null)
{
Write-Host " lOCAL GROUP CREATED SUCCESSFULLY "
}
I am getting below error...
Exception calling "add" with "1" argument(s): "The specified account name is already a
member of the group.
"
At line:4 char:1
+ $LocalGroup.Add($DomainGroup.path)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
Unable to find type [Microsoft.ActiveDirectory.Management.ADException].
At line:11 char:9
+ } Catch [Microsoft.ActiveDirectory.Management.ADException] {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Activ...ent.ADException:TypeN
ame) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
I woulduse $($Error[0].Exception.InnerException.Message) insted $_
if($($Error[0].Exception.InnerException.Message).Contains("The specified account name is already a member of the group."))

Error: "Get-ADUser : The operation returned because the timeout limit was exceeded."

I am working on creating a script to copy specific information from an existing AD User into a new account. The script is giving me 3 errors, the third one i know is because the script fails before it gets to that section.
Get-ADUser : The operation returned because the timeout limit was exceeded.
At line:115 char:14
+ $New_Path = (Get-ADUser ($UsernameCopy.Text)).DistinguishedName -repl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationTimeout: (cnelsontest:ADUser) [Get-ADUser], TimeoutException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.TimeoutException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
New-ADUser : Cannot validate argument on parameter 'Path'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command
again.
At line:155 char:35
+ New-ADUser -Name $New_DisplayName #params
+ ~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Add-ADGroupMember : Cannot find an object with identity: 'cnelsontest1' under: 'DC=azcorrections,DC=local'.
At line:159 char:29
+ Add-ADGroupMember -Members $Username.Text
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (cnelsontest1:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
Full Script link
Here is the line the first error refers to:
$New_Path = (Get-ADUser ($UsernameCopy.Text)).DistinguishedName -replace '^.*?,\s*(?=ou=)', ''
I have a feeling the second error message is caused by the first error, and the third error message is because it doesn't complete the New-ADUser command.
I'm running PSVersion 5.1.150
Edit: Can someone assist me in figuring out what the error messages mean as well as how to fix it?
You're running into three different errors being thrown:
Get-ADUser : The operation returned because the timeout limit was exceeded.
This one is obvious. You have a timeout on the AD server and it was exceeded before it found a result. You can adjust the timeout or deal with no returns.
New-ADUser : Cannot validate argument on parameter 'Path'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
You provided a bad (empty) path argument.
Add-ADGroupMember : Cannot find an object with identity: 'cnelsontest1' under: 'DC=azcorrections,DC=local'.
The object cnelsontest1 doesn't exist in the DC=azcorrections,DC=local path.

How the PowerShell Cmdlets that have a ComputerName parameter authenticate to remote computers?

Some PowerShell Cmdlets have a ComputerName parameter and I can use them to get information from remote computers. Like Get-Process, Get-Service etc. However, they don't have a Credential parameter, which in turn makes the command fail in some circumstances. Like the following example.
PS C:\Users\x\AppData\Roaming> Get-Service *sql* -ComputerName mylab.testing.com
Get-Service : Cannot open Service Control Manager on computer 'mylab.testing.com'. This operation might require other privileges.
At line:1 char:1
+ Get-Service *sql* -ComputerName mylab.testing.com
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
PS C:\Users\x\AppData\Roaming> Get-Error
******************************
Errors: 104
******************************
System.ComponentModel.Win32Exception (0x80004005): Access is denied
----------------------------------------------
System.Management.Automation.RuntimeException: ScriptHalted
----------------------------------------------
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext()
at System.Management.Automation.Interpreter.FuncCallInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
----------------------------------------------
System.Management.Automation.RuntimeException: You cannot call a method on a null-valued expression.
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
----------------------------------------------
You cannot call a method on a null-valued expression.
At line:18 char:21
+ write-host $err.Exception.ToString()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
----------------------------------------------
Collection was modified; enumeration operation may not execute.
At line:9 char:17
+ foreach($err in $Error)
+ ~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException
ScriptHalted
At line:22 char:9
+ throw
+ ~~~~~
+ CategoryInfo : OperationStopped: (:) [], RuntimeException
+ FullyQualifiedErrorId : ScriptHalted
PS C:\Users\x\AppData\Roaming> help Get-Service -full
Note I used a custom function Get-Error and its code is listed below.
function Get-Error
{
$errorsReported = $False
if($Error.Count -ne 0)
{
write-host "******************************"
write-host "Errors:", $Error.Count
write-host "******************************"
foreach($err in $Error)
{
$errorsReported = $True
if( $err.Exception.InnerException -ne $null)
{
write-host $err.Exception.InnerException.ToString()
}
else
{
write-host $err.Exception.ToString()
}
write-host "----------------------------------------------"
}
throw
}
}
I want to know whether my understanding is correct? Does that simply means it's impossible to authenticate to remote servers when using those commands?
Thanks.
You have to be running your PowerShell session with an account that has admin rights on the remote computer as capsch says. If the remote computer has remoting enabled, you could run the Get-Service command using Invoke-Command and remoting, which does support alternate credentials. Another alternative is to use WMI and query services that way which also supports alternate credentials.
UAC aside you by default have to be an admin of member to administer remotely
Cannot open Service Control Manager on computer