How do I search in Powershell - powershell

I have two commands that aim to search for the Input Hostname:
$Hostname = Read-Host -Prompt "Which HOSTNAME do you want to search for?"
Get-ADComputer -Filter {Name -like $Hostname* } -Server {domain.org} | Sort-Object
How do I make this work? I want to make it interchangably so that I can put in the name I want to search and it executes it for me but I want to search all Hostname that start with $Hostname not just $Hostname thats why I put the * there but that doesnt seem to work. Does anyone have a suggestion?

Related

Modifying the object result in PowerShell [duplicate]

This question already has an answer here:
Pull NT user ID from powershell
(1 answer)
Closed 3 years ago.
I'm new to PowerShell and it would be much appreciated if I could get some expertise assistance with a script that I'm trying to write in PowerShell.
Objective:
Run a script to remotely check the name of the current user who is logged on to that machine.
Current script:
This line with the variable of $EnterComputerName prompts us to input in what computer name we want to search.
$EnterComputerName = Read-Host -Prompt "Enter Computer name"
This line searches the details from that specified computer and pipe it so that it will only show the Username property.
$Name = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $EnterComputerName | Select-Object Username
Problem:
The result of the above line only outputs the user ID instead of their actual name, example: domain\N12345
I want to use the following line to convert userID into name:
Get-ADUser $Name | Select-Object GivenName, Surname
However, Get-ADUser only recognizes 'N23705' instead of 'domain\N23705'. Is there a way I can shorten this to 'N23705' and pass that value to the $Name variable?
One simple way to accomplish this is to use replace to remove the unwanted domain prefix.
$Name = (Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $EnterComputerName).UserName -replace ".*\\", ""
Edit: removed Parenthesis in replace syntax

Powershell Get AD user group query

I am trying to create a script that will allow me to enter a user name and will then present me with all the groups that the user is a member of in AD. I have the following code which works when i run it in Powershell ISE but when i just run the script in Powershell it allows me to enter the username but closes as it has queried AD. It does not print the results out on the screen.
$username = Read-Host 'Please enter Username!'
get-aduser $username -Properties memberof | select -expand memberof
If you are pasting the code into an already open PowerShell terminal then yes, that is definitely weird.
If you are right clicking and "Running with PowerShell" then this is the expected behaviour because the script has finished. You'll need to tell the script to stay open after it has retrieved the information. The easiest way to do this is by telling the script to wait for your input using Read-Host
$username = Read-Host 'Please enter Username!'
get-aduser $username -Properties memberof | select -expand memberof
Read-Host 'Done!'
UPDATE
Using an if statement wouldn't be feasible since it only catches terminating errors and Get-ADUser doesn't return terminating errors you would need to use a try/catch block. I over engineered this solution use to show you how it could be done using different PowerShell features :)
#Function to search for the user
function searchUser{
Param([string]$userName)
try{
Get-ADUser -Identity $userName -Properties MemberOf | Select-Object -ExpandProperty MemberOf
}catch{
return $false
}
}
#Ask the user for input until a valid username is entered
do {
$userInput = Read-Host "Enter a username: "
}until ($Output = searchUser -userName $userInput)
#Output the value from the searchUser function
Write-Host $Output

Powershell command execution order problem

I'm new in learning Powershell and I ran into a problem that makes me go insane. I want to write a simple Powershell script, that can be used to get both the group memberships of certain ActiveDirectory users, and the users of certain ActiveDirectory groups, and in the end gives the option to write the result on the console, or save it as csv.
Everything works perfectly fine, except no matter what I do, I can't stop the window from closing right after it writes the results on the console. I know that I can run a PS1 from command line in a way that doesn't allow the window to close, but I'd like Powershell do it by itself.
I tried to use both "pause" and Read-Host after the query script, but the stop event always happens BEFORE the result gets out on the console, no matter what's the order between the two of them. I simply cannot understand why the order of the execution of the two commands is backwards. Could you give me some insight why Powershell does it?
$nameofgroup = Read-Host -Prompt "`nPlease enter the name of the group!`n"
Get-ADGroupMember -identity $nameofgroup | Get-ADObject -Properties description, samAccountName | select #{n='Name'; e='name'}, #{n='Description'; e='description'}, #{n='Username'; e='samAccountName'}
$temp = Read-Host "Press Enter to continue..."
So you need to explicitly tell powershell to output the string. I also added in some error handling for you, so you don't have to run the script every time. Like if the group was typed wrong or doesn't exist.
Do
{
$nameofgroup = Read-Host -Prompt "`nPlease enter the name of the group!`n"
try
{
Get-ADGroupMember -identity $nameofgroup | Get-ADObject -Properties description, samAccountName | select #{n='Name'; e='name'}, #{n='Description'; e='description'}, #{n='Username'; e='samAccountName'} | Out-String
$errorMessage = 'False'
Read-Host -Prompt 'Press Enter key to exit'
}
catch
{
Write-Host "Could not find group please try again"
$errorMessage = 'True'
}
}
while($errorMessage -eq 'True')

Using a different active directory tree in powershell

So I have a script with the purpose of scanning devices that start with a certain name, then return results of computers missing a group. My problem is, the device I need it to run from turns out not to be in the same tree. I have seen some commands, but I wanted to be sure I had the syntax right. I will include part of the script for context:
Import-Module ActiveDirectory
$Group = "A-Certain-Group"
$Groupname = (Get-ADGroup $Group).distinguishedName
$Computers = Get-ADComputer -filter "name -like 'Big*'" -Prop MemberOf | Where{$_.MemberOf -notcontains $Groupname}
So let's say I am running it from "company.net", and it needs to perform the above script on "companynet.net" instead. What is the proper method?
The AD cmdlets all have a -server parameter which lets you specify other domains. Just use it to specify the other domain assuming there is a trust.
$Groupname = (Get-ADGroup $Group -Server companynet.net).distinguishedName
$Computers = Get-ADComputer -Server companynet.net -filter "name -like 'Big*'" -Prop MemberOf | Where{$_.MemberOf -notcontains $Groupname}
Note that if you don't have permission to perform actions in the domain you will also need to use the -credential parameter.

get all ADcontroller of another domain

I'm stuck in a stupid problem that I can't figure out how to solve.
I need to get all domain controllers of a trusted domain.
With this piece of code I get all DC in the current domain Get-ADDomainController -Filter *
With this I get one DC from target domain Get-ADDomainController -domain MyTrustedDomain -Discover
But how can I get all DC in target domain?
Can't test this due to lack of AD, but you could try the -Server option with the FQDN of the trusted domain:
Get-ADDomainController -Filter * -Server trusted.example.com
One way without using AD module:
$a = new-object 'System.DirectoryServices.ActiveDirectory.DirectoryContext'("domain", "other.domain.local" )
[System.DirectoryServices.ActiveDirectory.DomainController]::FindAll($a)
You need to be an 'authenticated user' in the remote domain or add username and password parameter to the DirectoryContext object
This command will list all domain controllers in the forest for each domain
(get-adforest).domains |%{get-addomaincontrollers -filter * -server $_}
I've come across the same problem as I work regularly with multiple domains. I was hoping for a more elegant solution, but so far the best I've come up with is to take your work one step further.
if Get-ADDomainController -domain MyTrustedDomain -Discover gives you one server in the target domain, you can feed that to the -server parameter to query that one DC. You do need to provide credentials to query a DC from a different domain than your login session if a trust DOES NOT exist (in a trust, the trusting domain considers you to be 'authenticated').
$targetdcname = (Get-ADDomainController -DomainName <MyTrustedDomain> -Discover).hostname
Get-ADDomainController -Filter * `
-Server $targetdcname `
-Credential (Get-Credential MyTrustedDomain\username) | ft HostName
or
Get-ADDomainController -Filter * `
-Server $((Get-ADDomainController -DomainName <MyTrustedDomain> -Discover).hostname) `
-Credential (Get-Credential MyTrustedDomain\username) | ft HostName
If you do this sort of thing alot, you can always store your credentials in a variable for reuse, $cred = Get-Credential MyTrustedDomain\username) and save the repeated prompts. The password is stored as a System.Security.SecureString and will be secure as long as you keep it within your session.
Until the Get-ADDomainController cmdlet is updated to allow both the -filter parameter AND the Domainname parameter, we're stuck with a workaround.
from: help get-addomaincontroller -examples
This should list all DCs in your domain
-------------------------- EXAMPLE 12 --------------------------
C:\PS>Get-ADDomainController -Filter { isGlobalCatalog -eq $true -and Site -eq "Default-First-Site-Name" }
Get all global catalogs in a given site.
Get-ADDomain -Identity <DOMAIN NAME> | select -ExpandProperty ReplicaDirectoryServers
Here is what I used
cls
$domains = (Get-ADForest).Domains;
foreach ($domain in $domains)
{
Write-Host $domain
(Get-ADDomain -Identity $domain | select -ExpandProperty ReplicaDirectoryServers).Count;
Write-Host "";
$totalCount = $totalCount + (Get-ADDomain -Identity $domain | select -ExpandProperty ReplicaDirectoryServers).Count;
}
Write-Host "Total domain controller count is: "$totalCount
Thanks for the start, here's what I came up with. Then I feed it to a SharePoint list.
get-adtrust -Filter * | Select-object Name, Domain,ipv4Address, OperatingSystem, Site, HostName, OperatingSystemVersion | ForEach-Object{Get-ADDomainController -Filter * -Server $_.Name}
Sometimes Powershell adds complexity, just open a cmd prompt and enter
C:\Windows\System32\nltest.exe /dclist:[trusted domain]
Of course, replace [trusted domain] with the name of the domain whose DC's you want.