Can we defer a variable initialization untill it is needed ?
What I would like to do is predefine some variables in my profile that will contain a list of AD computer:
let's say I want:
$OU1_workstation to be fill with computers found in OU=workstations,OU=OU1,dc=domain,dc=com
$OU2_workstation fill with computers found in
OU=workstations,OU=OU2,dc=domain,dc=com and so on...
I use the following script to do it but it takes 30sec to compute, so currently I can't put that in my profile...
Get-ADOrganizationalUnit -SearchScope onelevel -Filter "*" -Properties "name","distinguishedname" |%{
set-Variable -Name "$($_.name)_workstation" -value (Get-ADComputer -Searchbase "OU=workstations,$($_.Distinguishedname)" -Filter * )
}
What options are available in powershell ?
Finally, based on #Richard's reply of a previous question of mine, I've chosen the following path to achieve some sort of lazy loading : using a scriptproperty of a PSCustomObject.
So I can put this in my profile
#requires -module activedirectory
$server=New-Object PSCustomObject
Get-ADOrganizationalUnit -SearchScope onelevel -Filter "*" -Properties "name","distinguishedname" |
?{
$_.name -notmatch 'Administrateurs|Administration|Comptes de deploiement|Contacts|Domain Controllers|Groupes|Serveurs|Services'
} |
%{
$OU=$_.name
$s=[scriptblock]::Create("Get-ADComputer -SearchBase ""OU=servers,OU=$OU,DC=domain,DC=com"" -Filter 'name -notlike "" *old""' |select -expand name")
$server| Add-Member -MemberType ScriptProperty -name $OU -value $s -Force
}
then when needed I can call $server.OU1 to get all server under this OU, $server.OU2 etc...
Related
In PowerShell, how do you get an object's property value by specifying its name (a string)? I want something like the following:
$obj = get-something
# View the object's members:
$obj | gm
# I could retrieve a property by doing so:
write-host $obj.SomeProp
# But for many purposes, I would really want to:
write-host $obj | Get-PropertyByName "SomeProp"
Is there something similar to "Get-PropertyByName" in PowerShell?
Sure
write-host ($obj | Select -ExpandProperty "SomeProp")
Or for that matter:
$obj."SomeProp"
Expanding upon #aquinas:
Get-something | select -ExpandProperty PropertyName
or
Get-something | select -expand PropertyName
or
Get-something | select -exp PropertyName
I made these suggestions for those that might just be looking for a single-line command to obtain some piece of information and wanted to include a real-world example.
In managing Office 365 via PowerShell, here was an example I used to obtain all of the users/groups that had been added to the "BookInPolicy" list:
Get-CalendarProcessing conferenceroom#example.com | Select -expand BookInPolicy
Just using "Select BookInPolicy" was cutting off several members, so thank you for this information!
You can get a property by name using the Select-Object cmdlet and specifying the property name(s) that you're interested in. Note that this doesn't simply return the raw value for that property; instead you get something that still behaves like an object.
[PS]> $property = (Get-Process)[0] | Select-Object -Property Name
[PS]> $property
Name
----
armsvc
[PS]> $property.GetType().FullName
System.Management.Automation.PSCustomObject
In order to use the value for that property, you will still need to identify which property you are after, even if there is only one property:
[PS]> $property.Name
armsvc
[PS]> $property -eq "armsvc"
False
[PS]> $property.Name -eq "armsvc"
True
[PS]> $property.Name.GetType().FullName
System.String
As per other answers here, if you want to use a single property within a string, you need to evaluate the expression (put brackets around it) and prefix with a dollar sign ($) to declare the expression dynamically as a variable to be inserted into the string:
[PS]> "The first process in the list is: $($property.Name)"
The first process in the list is: armsvc
Quite correctly, others have answered this question by recommending the -ExpandProperty parameter for the Select-Object cmdlet. This bypasses some of the headache by returning the value of the property specified, but you will want to use different approaches in different scenarios.
-ExpandProperty <String>
Specifies a property to select, and indicates that an attempt should
be made to expand that property
https://technet.microsoft.com/en-us/library/hh849895.aspx
[PS]> (Get-Process)[0] | Select-Object -ExpandProperty Name
armsvc
powershell variables
Try this :
$obj = #{
SomeProp = "Hello"
}
Write-Host "Property Value is $($obj."SomeProp")"
Here is an alternative way to get an object's property value:
write-host $(get-something).SomeProp
$com1 = new-object PSobject #Task1
$com2 = new-object PSobject #Task1
$com3 = new-object PSobject #Task1
$com1 | add-member noteproperty -name user -value jindpal #Task2
$com1 | add-member noteproperty -name code -value IT01 #Task2
$com1 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$com2 | add-member noteproperty -name user -value singh #Task2
$com2 | add-member noteproperty -name code -value IT02 #Task2
$com2 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$com3 | add-member noteproperty -name user -value dhanoa #Task2
$com3 | add-member noteproperty -name code -value IT03 #Task2
$com3 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$arr += $com1, $com2, $com3 #Task4
write-host "windows version of computer1 is: "$com1.ver() #Task3
write-host "user name of computer1 is: "$com1.user #Task6
write-host "code of computer1 is: "$com1,code #Task5
write-host "windows version of computer2 is: "$com2.ver() #Task3
write-host "user name of computer2 is: "$com2.user #Task6
write-host "windows version of computer3 is: "$com3.ver() #Task3
write-host "user name of computer3 is: "$com1.user #Task6
write-host "code of computer3 is: "$com3,code #Task5
read-host
We have the script here in the company when the user is fired, for a few months we leave the user disabled and do not delete it, however I need to clean our shared mailboxes and check which of these unblown users still have access to these mailboxes
Get-Mailbox -RecipientTypeDetails SharedMailbox -ResultSize:Unlimited | Get-MailboxPermission |Select-Object Identity,User,AccessRights | Where-Object {($_.user -like '#')}|Export-Csv C:\Temp\sharedfolders.csv -NoTypeInformation
I already have my script that checks all shared mailboxes, but I need to create a kind of filter where the results show me only users who are no longer active in AD, someone can help me, please?
I think this is what you are looking for.
$mailboxes = Get-Mailbox -RecipientTypeDetails SharedMailbox -ResultSize unlimited
$mailboxes | Get-MailboxPermission | ForEach-Object{
$perm = $_
$ADuser = Get-ADUser $perm.user.securityidentifier.value
$perm | Add-Member -MemberType NoteProperty -Name UserEnabled -Value $ADuser.Enabled
$perm
} | Select-Object Identity, User, AccessRights, UserEnabled | Where-Object { ($_.user -like '#') -and $_.UserEnabled -eq $false } | Export-Csv C:\Temp\sharedfolders.csv -NoTypeInformation
Note it does require the Active Directory module to use the Get-ADuser command.
I am very new to using powershell and trying to execute a script that scans the entire network for all .mdb and .accdb files, for example, and generates a spreadsheet containing the data on them that I process elsewhere.
I put the sensistive data that I didnt want to provide in ()s
Here is my code:
#single threaded
import-module activedirectory
$arr = #()
$computers = Get-ADComputer -filter 'name -like "(employee computers)*"' | Select -Exp Name
foreach ($computer in $computers) {
Write-Host "Scanning" $computer "..."
gci \\$computer\c$\* -Include *.mdb, *.accdb -Recurse | ? {$_.PSIsContainer -eq $False} | % {
$obj = New-Object PSObject
$obj | Add-Member NoteProperty Directory $_.DirectoryName
$obj | Add-Member NoteProperty Name $_.Name
$obj | Add-Member NoteProperty FullName $_.FullName
$obj | Add-Member NoteProperty Size $_.Length
$obj | Add-Member NoteProperty CreationTime $_.CreationTime
$obj | Add-Member NoteProperty LastWriteTime $_.LastWriteTime
$arr += $obj
Write-Host "Scanning..."
}}
$arr | Export-CSV -notypeinformation '(path)\EmployeeDBs.csv'
This has been working pretty well so far, but for certain machines and/or directories on some machines I am receiving the following error messages:
Get-ChildItem : The specified network name is no longer available
[Get-ChildItem], IOException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand
and
Get-ChildItem : An object at the specified path \\(employee computer)\c$ does not exist.
[Get-ChildItem], IOException
+ FullyQualifiedErrorId : ItemDoesNotExist,Microsoft.PowerShell.Commands.GetChildItemCommand
I have been googling around but havent had much luck in understanding these error messages. Would somebody be able to explain what the issues are?
I am thinking (hoping) that they are permissions problems because I am testing the scripts on my personal machine before I run them from the admin machine
Any insight is greatly appreciated!
EDIT: below is my edited code for asynchronous execution:
import-module activedirectory
$computers = Get-ADComputer -filter 'name -like "wa-150*"' | Select -Exp Name
Get-job | Remove-Job -Force
Remove-Item -path (path)\EmployeeDBs.txt
foreach ($computer in $computers) {
$scriptBlock = {gci \\$($args[0])\c$\Users\z*\Desktop\* -Include *.mdb, *.accdb -Recurse | ? {$_.PSIsContainer -eq $False} | % {
$obj = New-Object PSObject
$obj | Add-Member NoteProperty Directory $_.DirectoryName
$obj | Add-Member NoteProperty Name $_.Name
$obj | Add-Member NoteProperty Size $_.Length
$obj | Add-Member NoteProperty CreationTime $_.CreationTime
$obj | Add-Member NoteProperty LastWriteTime $_.LastWriteTime
Write-Output -InputObject $obj
}
}
while ((Get-Job -State Running).Count -ge 20) {
Write-Host "Full - Waiting ... "
Start-Sleep -Seconds 5;
}
Start-Job -name $computer -ScriptBlock $scriptBlock -ArgumentList $computer
#Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $computer
}
Get-Job | Wait-Job | Receive-Job | Out-File -Append -FilePath '(path)\EmployeeDBs.txt'
Write-Host "Done"
I want to get all of those users starting with a specific keywords in AD User Description field using PowerShell.
Keyword: Could not execute powershell
Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase 'OU=contoso, DC=contoso, DC=local' - Properties Description | select -expand name,distinguishedname,description | Export-Csv -path C:\description.csv -NoTypeInformation
Last Update :
Get-ADUser -Properties Description -Filter 'Description -like "*Could not execute powershell*"' -SearchBase 'OU=contoso, DC=contoso, DC=local' |
select name,distinguishedname,description |
Export-Csv -path C:\description2.csv -NoTypeInformation
This is an easy task using the -filter option that you can use with get-aduser.
For more info how to filter: https://technet.microsoft.com/en-us/library/ee617241.aspx?f=255&MSPPError=-2147217396
Under the filter bit
Get-ADUser -Properties Description -Filter {Description -like $Description} -SearchBase 'OU=contoso, DC=contoso, DC=local' | select Name, DistinguishedName, Description | Export-Csv -path C:\description2.csv -NoTypeInformation
You can simply filter for Description:
Get-ADUser -Properties Description -Filter 'Description -like "*Could not execute powershell*"' -SearchBase 'OU=contoso, DC=contoso, DC=local'
My goal is to get a list of AD computer objects not following naming conventions with the whenCreated property. I am trying to export out a HTML file using the following PowerShell function:
function get_bad_names
{
$result = Get-ADComputer -searchbase $OU
-Filter {Name -notlike 'name1' -and
Name -notlike 'name2' -and
Name -notlike 'name3'}
-Properties whenCreated | sort whenCreated
$result | ConvertTo-Html | Out-File $dir\badnames.html
}
get_bad_names
Is there a more elegant way of structuring the Name filter lines? We have over 40 lines of different "names." In other words, over 40 lines in my script say Name -notlike 'name#' -and
Ideally I'd like for the code to read from a text file and export out the same results.
FYI: this function works but it is not ideally written. Any suggestions would be appreciated.
If you'd like to filter the query, construct an LDAP filter:
# Define the names to exclude
$NamesToExclude = "Name1","Name2","Name3"
# Turn them into LDAP clauses in the form of "(!(Name=Name1))"
$LDAPClauses = $NamesToExclude |ForEach-Object {
'(!(Name={0}))' -f $_
}
# Create a single query filter string with all the clauses from above
$LDAPFilter = "(&$LDAPClauses)"
$result = Get-ADComputer -LDAPFilter $LDAPFilter -SearchBase $OU -Properties whenCreated |Sort-Object whenCreated
You could filter with a regular expression using Select-Object but then you should get all computers in the OU with the -filter *, and that might strain your network. I would do the filtering and if more properties are needed, run Get-Computer again only for the matches:
Get-ADComputer -searchbase $OU -Filter * |
? { $_.name -match "name\d{1,2}" } | # Match if string "name" is followed one or two digits
Get-ADComputer -property * # Get all properties for the computers if needed
Is there a more elegant way of structuring the Name filter lines?
Not exactly. You have a fairly limited set of operators when you use the -Filter parameter of commands in the ActiveDirectory module because it has to translate them all to LDAP filters.
However, you can do something like this:
$ExcludedPatterns = 'Name1', 'Name2', 'Name3'
$ComputerFilter = foreach ($Pattern in $ExcludedPatterns) { "(Name -notlike '$Pattern')" }
$ComputerFilter = $ComputerFilter -join ' -and '
Get-ADComputer -Filter $ComputerFilter
Now you can maintain a list of name patterns.
Keep in mind that the -Filter property is not a ScriptBlock on the ActiveDirectory commands. They're all Strings and in spite of the documentation for these commands they should be written that way. Writing them as ScriptBlocks will eventually cause you problems with variable expansion.
Compare:
$ComputerName = hostname
Get-ADComputer -Filter "Name -eq '$ComputerName'"
Get-ADComputer -Filter { Name -eq '$ComputerName' }
Thank you to everyone for their feedback. I was impressed how fast the responses were.
I was able to achieve my goal using regular expressions reading from a text file.
My code now looks like this:
[regex]$Expression = Get-Content $dir\regex.txt
function get_bad_names
{
$result = Get-ADComputer -searchbase $OU
-Filter {Enabled -eq $true}
-Properties whenCreated | Where-Object {$_.Name -notmatch $Expression}| sort whenCreated
$result | ConvertTo-Html | Out-File $dir\badnames.html
}
get_bad_names