Script
$ADUser = Get-ADUser
if($ADUser -ne "") {echo "there are existing ADUsers!"} #
$Zeilen = (Get-Content C:\Users\Administrator\Documents\users.csv | Measure-Object –Line).Lines #import file, count lines with Measure-Object(mo)(-> output object), ".Lines" takes just number from Measure-Object and convert it to a number
$Zeilen -= 1 # "-1" because 1. line = header without relevant information
$Ausgabe = Import-Csv C:\Users\Administrator\Documents\users.csv
$password = "Ausbildung2020" | ConvertTo-SecureString -AsPlainText -Force #is disabled without password
###################
#creates list with existing users
$Userlist = ""
$CsvData = (Get-ADUser).DistinguishedName | Select-Object -Skip 3 #removes first 3 Zeilen, which contains Admin, Guest und kgrtgt because the are irrelevant
$ZeilenCsvData = $CsvData.count #line amount from (Get-ADUser).DistinguishedName
for($line = 0;$line -lt $ZeilenCsvData; $line++ ) #-lt oder -le ?
{
$UserLine = $CsvData[$line]
$user1 = $UserLine.Split(",")
$user2 = $user1[0].Split("=")
$user3 = $user2[1] #extract Username from String
$UserList += $user3 + "`r`n" #paste Username from current Iteration to $UserList
}
###################
#check if ADUser exists
for ($loop = 0; $loop -lt $Zeilen; $loop++) #-lt oder -le ? #execute loop as often as lines in (Csv-file with (new) Users) exists
{
for($i = 0; $i -lt $ZeilenCsvData ; $i++) #$ZeilenCsvData: number of lines from Get-ADUser without Admin, Guest und kgrtgt
{
if($Ausgabe[$loop].Name -eq $UserList.[$i]) #!!line with problem!!
{
$match = $true
break
}
}
if($match -eq $true){ continue } #ends Iteration and continue with new one if User exists
###################
#create User if it doesn't exist
New-ADUser -Name $Ausgabe[$loop].Name `
-GivenName $Ausgabe[$loop].GivenName `
-Surname $Ausgabe[$loop].Surname `
-City $Ausgabe[$loop].City `
-AccountPassword $password `
-path "OU=Benutzer,DC=dmamgt,DC=local" `
Enable-ADAccount -Identity $Ausgabe[$loop].Name #requirement: password matches standard
}
Problem
In the problem line the „ [$ “ marked red and I get those errors which make the script unexecutable
Task
I got the task to create a organizational unit called "Benutzer" in which I should create 20 Users with some properties like name, city,password, enabled,... which I imported from a csv file. But I have to check whether the user already exists if so the loop should go to the next user to create it.
Errors:
At C:\Users\Administrator\Documents\extended New-ADUser mit csv.ps1:36 char:48
+ if($Ausgabe[$loop].Name -eq $UserList.[$i])
+ ~
Missing type name after '['.
At C:\Users\Administrator\Documents\extended New-ADUser mit csv.ps1:36 char:47
+ if($Ausgabe[$loop].Name -eq $UserList.[$i])
+ ~
Missing property name after reference operator.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingTypename
Method invocation failed because [System.Char] does not contain a method named 'Split'.
At C:\Users\Administrator\Documents\extended New-ADUser mit csv.ps1:23 char:5
+ $user1 = $UserLine.Split(",")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Make $UserList an array:
$UserList = #()
Add items like this:
$UserList += $user
And this is how you index an array (without the dot)
$UserList[$i]
There might be some other issues with your script too, I didn't read it fully, but I hope this will get you started.
Related
Essentially, my script is supposed to check if each user in the administrators group is listed inside of a text file, and if it is then ignore it and move on. If it isn't, it removes the user from the administrator group. However, Get-LocalGroupMember prepends the computer name to the username. This means that the username in the txt file (ex user1), does not match the $._Name variable from the Get-LocalGroupMember command (ex desktop/user1). Here is a copy of the code
$GroupName = "Administrators"
$Exclude = "Administrator","$env:UserName"
$AuthorizedAdmins = Get-Content C:\Users\$env:UserName\admins.txt
Get-LocalGroupMember $GroupName |
ForEach-Object{
if ($_.ObjectClass -eq 'User'){
if ($AuthorizedAdmins -contains $_.Name -or $Exclude -contains $_.Name){
Continue
}
else{
Remove-LocalGroupMember -Group $GroupName -Member $_.Name -Confirm
}
}
}
I have tried several solutions. In the code, I created a new variable that removed the first $env:ComputerName+1 characters of the $._Name string. While this did work to remove the computername, powershell errors out. Here is the error code and changed script:
Get-LocalGroupMember : System error.
At users.ps1:6 char:1
+ Get-LocalGroupMember $GroupName |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-LocalGroupMember], ContinueException
+ FullyQualifiedErrorId : An unspecified error occurred.,Microsoft.PowerShell.Commands.GetLocalGroupMemberCommand
$GroupName = "Administrators"
$Exclude = "Administrator","$env:UserName"
$AuthorizedAdmins = Get-Content C:\Users\$env:UserName\admins.txt
Get-LocalGroupMember $GroupName |
ForEach-Object{
$User = $_.Name
$length = $env:ComputerName.Length+1
$ShortUser = $User.Remove(0,$length)
if ($_.ObjectClass -eq 'User'){ #ignore groups and select only users
if ($AuthorizedAdmins -contains $ShortUser -or $Exclude -contains $ShortUser){
Continue
}
else{
Remove-LocalGroupMember -Group $GroupName -Member $_.Name -Confirm
}
}
}
The admin.txt file is formatted as follows:
user1
user2
user3
I cannot figure out how to fix this, though it is probably someting simple. Any help would be appreciated.
The real issue with your code is your use of continue in a ForEach-Object loop, see note from the docs. If you want to emulate continue in a pipeline processing function you should use return instead. So your code, with some improvements and simplifications would be:
$GroupName = "Administrators"
$exclude = #(
"Administrator"
$env:UserName
Get-Content C:\Users\$env:UserName\admins.txt
)
Get-LocalGroupMember $GroupName | ForEach-Object{
# if its not a user, skip this logic
if ($_.ObjectClass -ne 'User') {
return
}
# here we assume its a user
if ($_.Name.Split('\')[-1] -in $exclude) {
return
}
Remove-LocalGroupMember -Group $GroupName -Member $_.Name -Confirm
}
I am having a text file that has content in this manner.
One;Thomas;Newyork;2020-12-31 14:00:00;0
Two;David;London;2021-01-31 12:00:00;0
Three;James;Chicago;2021-01-20 15:00:00;0
Four;Edward;India;2020-12-25 15:00:00;0
In these entries according to date time, two are past entries and two are future entries. The last 0 in the string indicates the Flag. With the past entries that flag needs to be changed to 1.
Consider all the entries are separated with the array. I tried this block of code but its not working to solve the problem here.
for ($item=0 ; $item -lt $entries.count ; $item++)
{
if ($entries.DateTime[$item] -lt (Get-Date -Format "yyyy-MM-dd HH:mm:ss"))
{
$cont = Get-Content $entries -ErrorAction Stop
$string = $entries.number[$item] + ";" + $entries.name[$item] + ";" +
$entries.city[$item]+ ";" + $entries.DateTime[$item]
$lineNum = $cont | Select-String $string
$line = $lineNum.LineNumber + 1
$cont[$line] = $string + ";1"
Set-Content -path $entries
}
}
I am getting errors with this concept.
Output should come as:-
One;Thomas;Newyork;2020-12-31 14:00:00;1 ((Past Deployment with respect to current date)
Two;David;London;2021-01-31 12:00:00;0
Three;James;Chicago;2021-01-20 15:00:00;0
Four;Edward;India;2020-12-25 15:00:00;1 (Past Deployment with respect to current date)
This output needs to be overwritten on the file from where the content is extracted ie Entries.txt
param(
$exampleFileName = "d:\tmp\file.txt"
)
#"
One;Thomas;Newyork;2020-12-31 14:00:00;0
Two;David;London;2021-01-31 12:00:00;0
Three;James;Chicago;2021-01-20 15:00:00;0
Four;Edward;India;2020-12-25 15:00:00;0
"# | Out-File $exampleFileName
Remove-Variable out -ErrorAction SilentlyContinue
Get-Content $exampleFileName | ForEach-Object {
$out += ($_ -and [datetime]::Parse(($_ -split ";")[3]) -gt [datetime]::Now) ? $_.SubString(0,$_.Length-1) + "1`r`n" : $_ + "`r`n"
}
Out-File -InputObject $out -FilePath $exampleFileName
Background: I've been using Netwrix to audit permissions to network shares for a few years now and It's only ever worked smoothly 1 time..... So I've decided to move on to just an automated powershell script. I've run into a block. When I try to parse out the group members, it doesn't like the network name in front of the group name (TBANK). Then I also need to take the next step of just showing the name instead of the whole output of get-adgroupmember. Any help would be greatly appreciated as I'm very to to scripting with powershell. Current script below:
$OutFile = "C:\users\user1\Desktop\test.csv" # Insert folder path where you want to save your file and its name
$Header = "Folder Path,IdentityReference, Members,AccessControlType,IsInherited,InheritanceFlags,PropagationFlags"
$FileExist = Test-Path $OutFile
If ($FileExist -eq $True) {Del $OutFile}
Add-Content -Value $Header -Path $OutFile
$Folder = "\\server1.tbank.com\share1"
$ACLs = get-acl $Folder | ForEach-Object { $_.Access }
Foreach ($ACL in $ACLs){
$ID = $ACL.IdentityReference
$ID = $ID -replace 'TBANK\' , ''
$ACType = $ACL.AccessControlType
$ACInher = $ACL.IsInherited
$ACInherFlags = $ACL.InheritanceFlags
$ACProp = $ACL.PropagationFlags
$Members = get-adgroupmember $ID.
$OutInfo = $Folder + "," + $ID + "," + $Members + "," + $ACType + "," + $ACInher + "," + $ACInherFlags + "," + $ACProp
Add-Content -Value $OutInfo -Path $OutFile
}
First of all, there is a way better way to output a CSV file than by trying to write each row yourself (with the risk of missing out required quotes), called Export-Csv.
To use that cmdlet, you wil need to create an array of objects which is not hard to do.
$OutFile = "C:\users\user1\Desktop\test.csv" # Insert folder path where you want to save your file and its name
$Folder = "\\server1.tbank.com\share1"
# get the Acl.Access for the folder, loop through and collect PSObjects in variable $result
$result = (Get-Acl -Path $Folder).Access | ForEach-Object {
# -replace uses regex, so you need to anchor to the beginning of
# the string with '^' and escape the backslash by doubling it
$id = $_.IdentityReference -replace '^TBANK\\' # remove the starting string "TBANK\"
# Get-ADGroupMember can return users, groups, and computers. If you only want users, do this:
# $members = (Get-ADGroupMember -Identity $id | Where-Object { $_.objectClass -eq 'user'}).name -join ', '
$members = (Get-ADGroupMember -Identity $id).name -join ', '
# output an onbject with all properties you need
[PsCustomObject]#{
'Folder Path' = $Folder
'IdentityReference' = $id
'Members' = $members
'AccessControlType' = $_.AccessControlType
'IsInherited' = $_.IsInherited
'InheritanceFlags' = $_.InheritanceFlags -join ', '
'PropagationFlags' = $_.PropagationFlags -join ', '
}
}
# output on screen
$result | Format-List
# output to CSV file
$result | Export-Csv -Path $OutFile -Force -UseCulture -NoTypeInformation
I've added a lot of inline comments to hopefully make things clear for you.
The -UseCulture switch in the Export-Csv line makes sure the field delimiter that is used matches what is set in your system as list separator. This helps when opening the csv file in Excel.
P.S> the Get-ADGroupMember cmdlet also has a switch called -Recursive. With that, it will also get the members from groups inside groups
Very very much a PowerShell newbie here I wanted a script to scan devices on the network and report on Local Admins. Found one out there and made some minor modifications to meet my needs - but I have one mod I cant work out how to do. Hoping someone out there will know a simple way to do it ?
The scrip below will read in a list of device names - scan them and output a dated report for all devices that are live and on-line. If the device is not accessible I get the following error on screen but nothing in the report.
I would like when it encounters an error that it writes to the report file - something along the lines of "$computor was not accessible!"
The code I am using is
$date = Get-Date -Format o | foreach {$_ -replace ":", "."}
ECHO "Starting scan"
$Result = #()
foreach($server in (gc .\servers.txt)){
$computer = [ADSI](”WinNT://” + $server + “,computer”)
$Group = $computer.psbase.children.find(”Administrators”)
$Filename = "c:\" + "LocalAdminAudit" + $date + ".txt"
function getAdmins
{
ECHO "SEARCHING FOR DEVICE"
$members = ($Group.psbase.invoke(”Members”) | %
{$_.GetType().InvokeMember(”Adspath”, ‘GetProperty’, $null, $_, $null)}) -
replace ('WinNT://DOMAIN/' + $server + '/'), '' -replace ('WinNT://DOMAIN/',
'DOMAIN\') -replace ('WinNT://', '')
$members}
ECHO "READY TO WRITE OUTPUT"
$Result += Write-Output "SERVER: $server"
$Result += Write-Output ' '
$Result += ( getAdmins )
$Result += Write-Output '____________________________'
$Result += Write-Output ' '
ECHO "Record written"
}
# Added date run to report
$result += Write-Output "Date Reported: $date"
$Result > $Filename
Invoke-Item $Filename
# replace "DOMAIN" with the domain name.
ECHO "Scan Complete"
And the on screen error when a machine is off line or otherwise doesn't respond is
Exception calling "Find" with "1" argument(s): "The network path was not found.
"
At \server\users\User.Name\Powershell Scripts\Get-Local-AdminsV3.ps1:1
0 char:40
+ $Group = $computer.psbase.children.find <<<< (”Administrators”)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
I would like when it encounters an error that it writes to the report file - something along the lines of "$computor was not accessible!" - I am pretty sure there must be an easy way of doing this - but I cant work it out so any tips would be greatly appreciated
As Matt, mentioned in the comments. You can use a Try/Catch block inside your function to catch the error.
I also made some other changes. The most major is that I changed the function to contain all of the code necessary to get the local administrator group. Then the loop just calls the function once per computer with the computer name. This function is then reusable.
Secondly rather than output to a text file, I changed to outputting to a CSV as is a more structured format that can be used better later.
Also rather than relying on writing to the console host, I used Write-Progress to report the progress of the loop.
$Servers = Get-Content .\servers.txt
$ExportFileName = "c:\LocalAdminAudit$date.csv"
function Get-LocalAdministrator {
[cmdletbinding()]
Param(
$ComputerName
)
$Group = [ADSI]("WinNT://$computername/Administrators,group")
try {
$Group.Invoke("Members") | ForEach-Object {
$User = ($_.GetType().InvokeMember("Adspath", 'GetProperty', $null, $_, $null) -split '/')[-2,-1] -join '\'
[PSCustomObject]#{
"User" = $User
"Server" = $ComputerName
"Date" = Get-Date -Format o | ForEach-Object {$_ -replace ":", "."}
}
}
}
catch {
[PSCustomObject]#{
"User" = "Failed to Report"
"Server" = $ComputerName
"Date" = Get-Date -Format o | ForEach-Object {$_ -replace ":", "."}
}
}
}
$LocalAdmins = foreach ($Server in $Servers) {
Write-Progress -Activity "Retrieving Local Administrators" -Status "Checking $Server" -PercentComplete (([array]::indexof($Servers,$Server)/($Server.count))*100)
Get-LocalAdministrator $Server
}
$LocalAdmins | Export-CSV $ExportFileName -NoTypeInformation
Invoke-Item $ExportFileName
Lastly, be careful of smart quotes especially when cutting and pasting between Outlook and word.
I'm currently rewriting a script that is in VB into a Powershell script.
What the script does is search our Active Directory for a user based on the script-users input.
Function PromptForName{
$nameInput = "*"
$nameInput += Read-Host ("Please enter a full or partial name.")
$nameInput += "*"
return $nameInput
}
Function FindUsers{
param ([string]$n)
$usersArray = Get-ADUser -f {DisplayName -like $n} | Select-Object Name
return $usersArray
}
This code will print out the correct list of names. What I then want to do is allow the user to choose one of those names, and have more information about that person. I'm stuck at allowing the script-user to select one of those names.
How can I prompt for another input; where the box will display a numbered list of all the names that FindUsers gave, and then return a number based on which user they chose? I'm completely lost.
This is currently how I am trying to do it, although I'm pretty sure it's completely wrong.
Function PrintUsers{
param $a
[int]$i, $j
[string]$userList
$j = 1
foreach($object in $array){
$userList += ($j + $array[$i])
$j++
}
return $userList
}
Function SelectUser{
param $list
$user = Read-Host ($list)
}
EDIT:
I have updated my functions to the following:
Function FindUsers{
param ([string]$n)
$usersArray = #(Get-ADUser -f {DisplayName -like $n} | Select-Object Name| Format-List)
return $usersArray
}
Function PrintUsers{
param ([String[]]$array)
$i
for($i = 1; $i -lt $usersArray.length; $i++){
Write-Host "$i. $($usersArray[$i-1].Name)"
}
}
The output after FindUsers is like this:
Name : xxxxx yyyyy
Name : xxxxx zzzzz
etc.
So the return of $usersArray is printing all that.
I don't want any printing until the PrintUsers function, and I want it to be in a numbered list type format like this:
1. xxxx yyyy
2. xxxx zzzz
etc.
I'm having the most difficult time figuring this out.
# get all users
$usersArray = #(Get-ADUser -f {DisplayName -like $n} )
# create menu
for($i=1; $i -le $usersArray.count; $i++){
Write-Host "$i. $($usersArray[$i-1].Name)"
}
# prompt for user number
$user = Read-Host Enter the user number to get more info
# display full info for selected user
$usersArray[$user-1] | Format-List *
Use Add-Member to add a unique identifier to each user. Let's treat processes as if they're user objects, for the sake of example:
$procs = gps;
$procs = $procs | % { $i=0; } {
Add-Member -MemberType NoteProperty -InputObject $_ -Name Number -Value $i -PassThru;
$i++;
};
$procs | select Number,Name;
$procid = Read-Host -Prompt 'Enter the number of the process you would like to operate on';
$proc = $procs | ? { $_.Number -eq $procid };
Write-Host -Object ('Operating on proc: {0}' -f $proc.Name);