Issue adding to a Substring if a dsquery finds the same sAMAccountName - windows

I am editing a Powershell script that a colleague created before they left which I assume was created on an older version of Powershell/Activedirectoy. It is to create an AD account but I'm having an issue checking if a username already exists then carrying out an action if it does.
$UsernameInteger = 1
$sAMAccountName = $sn+$givenName.substring(0,$UsernameInteger)
# Check to see if the username is available in Active Directory
do
{
if (dsquery user -samid $sAMAccountName)
{
$CreateUser = $False
$UsernameInteger++
$Username = $sn+$givenName.substring(0,$UsernameInteger)
}
Else
{
$CreateUser = $True
}
}
Until ($CreateUser -eq $True)
When I run this code with an account with the same name I get the following error:
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
Parameter name: length"
At C:\AD Account Creation.ps1:43 char:5
+ $Username = $sn+$givenName.substring(0,$UsernameInteger)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException
What I want is when the $createuser = $false then it will add the next letter of their $givenName to the $username and keep doing this until an account with the same $sAMAccountName is not found and the account can be created.
How would I go about doing this?

You've incremented the counter to a value bigger than the length of the $givenName string. You need to change the increment logic to something like:
if ($UsernameInteger -le $givenName.length) {
$UsernameInteger++
}
This won't help if the username you pass in already exists in its entirety though, so you'll also need to handle that scenario

Related

Powershell Force Maximize / Reopen if close

Working on a Kiosk Windows tablet, was working before I started to optimize. I had used a Windows Debloating tool to remove all the unnecessary items on the tablets. But I believe it removed something I was calling on in the script. Just looking to see if anyone has any idea what I would need to reinstall. Or if I should start over on the Image
Here is the Powershell script
Add-Type -AssemblyName UIAutomationClient
$MyProcess = Get-Process | where { $_.MainWindowTitle -like "Kiosk*" }
while (1 -eq 1) {
if ($null -ne $MyProcess) {
# if Minimized make it Normal
$ae = [System.Windows.Automation.AutomationElement]::FromHandle($MyProcess.MainWindowHandle)
$wp = $ae.GetCurrentPattern([System.Windows.Automation.WindowPatternIdentifiers]::Pattern)
if ($wp.Current.WindowVisualState -eq 'Minimized') {
$wp.SetWindowVisualState('Normal')
}
# execute needed function
}
else {
start-process "C:\Users\Public\Desktop\Welcome.lnk" -WindowStyle Normal
# execute needed function
}
start-sleep -Milliseconds 500
}
And here is the error attempted a copy and paste
Cannot convert argument "hwnd", with value: "System.Object[]", for "FromHandle' to type "System.IntPtr": "Cannot convert the "System.Object[]" value of type "System.Object[]"' to type "System. IntPtr At C:\Scripts\KioskMinimizedcheckscript.ps1:9 char:5 + Sae = [system.windows. Automation.AutomationElement]:: FromHandle($
+
+CategoryInfo
: NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgument Conversion InvalidcastArgument
You cannot call a method on a null-valued expression. At C:\scripts\KioskMinimizedcheckscript.ps1:10 char:5
Swp = Sae.GetCurrentPattern([system.windows. Automation.windowPatt ...
+ CategoryInfo
Invalidoperation; (:) [], RuntimeException
+ FullyQualifiedErrorId: InvokeMethodonNull
Image of Actual Error
Tried running script on default install of windows and works fine. Just need to know what to add back into the stripped down version.

Covert ObjectID to displayname from Azure

Hi I'm trying to convert objectID to display name from logs in Azure. So the trouble I'm running into is that I have the ps script but can't get it to work for created account for my alerts. It seems that the request body field keeps giving me errors.
$responseBodyObject = ConvertFrom-Json $_.Properties.Content.responseBody
$principalId = $responseBodyObject.properties.principalId
Write-Host "PrincipalID: $($principalId)"
$azUser = Get-AzADUser -ObjectId $principalId
Write-Host "User: $($azUser.DisplayName)"
ERROR MESSAGE
`Get-AzADUser : Cannot bind argument to parameter 'ObjectId' because it is an empty string.
At C:\xxxx\xxxx\xxxxx\xxxxxx.ps1:33 char:36
+ $azUser = Get-AzADUser -ObjectId $principalId
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-AzADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Get-AzADUser
Get-AzADUser : Cannot bind argument to parameter 'ObjectId' because it is an empty string.
The error message shows that Objectid has empty value.
Make sure to check your Principal ObjectID whether it contains the valid ObjectID or not.
To check whether it is valid or not use below command
# use get-azaduser to get the objectid
Get-AzADUser
# Search for specific user using Startwith filter
Get-AzADUser -StartsWith demo
workaround:
Here i am using both ObjectId and UserPrinicipalName
using ObjectID
using UserPrinicipalName

How to test if an EventSubscriber exists in Windows Powershell

Before deleting an EventSubscriber with SourceIdentifier "abc", I want to test if it exists and only then delete it. Otherwise there is no need to.
But every time I access it to test if it exists with:
Get-EventSubscriber -SourceIdentifier "abc"
Powershell responds with an error:
get-eventsubscriber : Event subscription with source identifier 'abc' does not exist.
At line:1 char:8
+ $chk = get-eventsubscriber -SourceIdentifier "abc"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-EventSubscriber], Argu
mentException
+ FullyQualifiedErrorId : INVALID_SOURCE_IDENTIFIER,Microsoft.PowerShell.C
ommands.GetEventSubscriberCommand
stating that it does not exist. Is there a way to avoid the error messages and instead set a variable to null or false that can be tested to see if it does not exist?
Something like:
$eventSubscriberExists = Get-EventSubscriber -SourceIdentifier "abc"
if ($eventSubscriberExists) {
Unregeister-Event -SourceIdentifier "abc"
}
In other words instead of sending error messages to the console, set a variable to true or false.

PowerShell folder permission error - Some or all identity references could not be translated

I am running this script as Admin and It does create the folders requred, just does not set the appropriate permissions.
$Users = Get-Content "D:\New_Users.txt"
ForEach ($user in $users)
{
$newPath = Join-Path "F:\Users" -childpath $user
New-Item $newPath -type directory
$UserObj = New-Object System.Security.Principal.NTAccount("DOMAIN",$user)
$acl = Get-Acl $newpath
$acl.SetAccessRuleProtection($True, $False)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("O1OAK\$user","AppendData,CreateDirectories,CreateFiles,DeleteSubdirectoriesAndFiles,ExecuteFile,ListDirectory,Modify,Read,ReadAndExecute,ReadAttributes,ReadData,ReadExtendedAttributes,ReadPermissions,Synchronize,Traverse,Write,WriteAttributes,WriteData,WriteExtendedAttributes","ContainerInherit, ObjectInherit","None","Allow")
$acl.SetAccessRule($accessRule)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("NT AUTHORITY\SYSTEM","FullControl","ContainerInherit, ObjectInherit","None","Allow")
$acl.SetAccessRule($accessRule)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators","FullControl","ContainerInherit, ObjectInherit","None","Allow")
$acl.SetAccessRule($accessRule)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("1OAK\$user","Delete","ContainerInherit, ObjectInherit","None","Allow")
$acl.removeAccessRule($accessRule)
$acl.SetOwner($UserObj)
$acl | Set-Acl $newpath
}
The first error in a string of 3 that I get is below. I think it is the most important and will fix the other 2.
Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
At D:\DOMAIN\IT\IT Private\User Drives\user_folders.ps1:12 char:20
+ $acl.SetAccessRule <<<< ($accessRule)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
The error is pretty self explanatory: Some or all identity references could not be translated.
This means the account couldn't be found. So what you have to do is verify your accounts. Since you're adding 4 ACE's, you'll need to identify which is invalid.
The easiest way to do this is to debug through, line by line using the ISE or PowerGUI.
I tried your code with "NT AUTHORITY\SYSTEM" and "BUILTIN\Administrators" and it works so the issue is with "O1OAK\$user" or "1OAK\$user". You likely have an invalid account in your text file.
a gotch with the user ID is that AD truncates the username, so a user with a long name "j_reallylongname" will have a samid (Security Account Manager (SAM) account name) which is truncated. (j_reallylong)
so when fetching usernames, make sure you verify against the AD before using it.
When i've got the upns, so i run a dsget query to get the samid then use that to build the identity reference.
Adding this in case any C#/ASP.NET developers get this (which is my scenario, and I found this post).
I am using .NET Core in a corporate environment, and I need to check UserGroups as part of security. The code is like (where "user" is a ClaimsPrincipal):
var windowsIdentity = user.Identity as WindowsIdentity;
if( windowsIdentity is null )
throw new Exception( $"Invalid Windows Identity {user.Identity.Name}" );
return windowsIdentity.Groups
.Select( g => g.Translate( typeof( NTAccount ) ).Value );
Anyway, someone in charge of groups deleted a group I was part of, and the AD replication lag caused me to get the error in the title. A logoff and/or reboot worked just fine.
For me it was a case of where i verified whether the script execution knew the password by using $user = Get-Credential "username". i had to turn my $user into $user.UserName To give the script parameters the value they were expecting

I want to add a user to a Group based on name form a CVS file

I have the following code that can make a user however when I write the group in the CSV file the user is not added to said group.
I am able to run this right on the server.
The group is in a sub-group of a much larger group. so I am also not sure how to inform Powershell I want a group of a group.
this is the path would this work?
BILOMNI.BILPROMETRIC.ROOT/EasyServe_OU/EasyServeChannel_OU/Channel_CenterUsers_OU
I also have the group unique name
RequestingAccess_CenterUsers_GG
$computer = $ENV:COMPUTERNAME;
$users = Import-Csv "C:\Users.csv";
Foreach ($user in $users)
{
#for ($i=0; $i -le 2000; $i++)
#{
# Grab required info
$userName = $user.User
$objOu = [ADSI]"WinNT://$computer"
$Group = $user.Group
# Create user
$objUser = $objOU.Create("User", $userName + $i)
$objUser.setpassword($user.password)
$objUser.SetInfo()
# Find target group and add the user to it
$de = [ADSI]"WinNT://$computer/$Group,Group"
$de.add([ADSI]"WinNT://$computer/$userName")
# }
}
The following exception occurred while retrieving member "add": "An invalid dn syntax has been specified.
"
At C:\Users\dennis.hayden\Desktop\makingbilusers.ps1:20 char:12
+ $de.add <<<< ([ADSI]"LDAP://$computer/$userName")
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember
Below is the CSV file I am use:
User,Group,password
Masstestuser,RequestingAccess_CenterUsers_GG,P#ssWord
Can you try to change all your Wint:// by LDAP:// and modify a bit your code like the following :
# Find target group and add the user to it
$de = [ADSI]"LDAP://$computer/$Group,Group"
$user=[ADSI]"LDAP://$computer/$userName"
$de.add($user.Path)
# Commit
$de.setinfo()

Resources