[powershell] Powershell: A positional parameter cannot be found that accepts argument "xxx"

I am trying to understand what this error actually means. So far a search of similar help requests for this error range from missing parameters, missing pipes, use of single or multi-lines, and also concatenation issues but none of the answers seem to give a definitive reason. So I assume the issue is code format (which makes it a lot harder to track down).

This is my script which I am writing to rename active directory users per target OU from whatever format they are now into a firstname.surname format.

I have created a test OU in AD with some users who will trigger errors and some that will not. However, the users that should not give me an error are giving me the "a positional parameter cannot be found that accepts argument "firstname.surname"

I cannot see what is wrong with the script but hopefully, someone can give me some pointers.

Import-Module ActiveDirectory

$users = $null

$users = Get-ADUser -SearchBase "ou=Testing,ou=Users,dc=my,dc=domain" -Filter * -Properties *
foreach ($user in $users) {
    Write-Host "Processing... $($user)"
    $newname = $null

    # Check first/last name is set
    if (!$user.givenName -or !$user.Surname) {
        Write-Host "$($user) does not have first name or last name set. Please correct, skipping user."
        continue
    } else {
        $newname = ("$($user.givenName).$($user.Surname)")

        #Check if new username already exists
        if (dsquery user -samid $newname) {
            Write-Host "$($user) requires altered username with initial."

            if (!$user.Initials) {
                Write-Host "$($user) does not have any initials set. Please correct, skipping user."
                continue
            }

            $newname = ("$($user.givenName)$($user.Initials).$($user.Surname)")

            #Check if altered new username already exists
            if (dsquery user -samid $newname) {
                Write-Host "$($user) requires manual change. Please correct, skipping user."
                continue
            }
        }

        try {
            #Change UPN
            Set-ADUser $user -userPrincipalName = $newname
            #Change DN
            Rename-ADObject -identity $user -Newname $newname
        } catch {
            Write-Host "Error when renaming $($user). Error is: $($_.Exception.Message). User requires manual change. Please correct, skipping user."
            continue
        }
    }
}

This question is related to powershell active-directory

The answer is


Cmdlets in powershell accept a bunch of arguments. When these arguments are defined you can define a position for each of them.

This allows you to call a cmdlet without specifying the parameter name. So for the following cmdlet the path attribute is define with a position of 0 allowing you to skip typing -Path when invoking it and as such both the following will work.

Get-Item -Path C:\temp\thing.txt
Get-Item C:\temp\thing.txt

However if you specify more arguments than there are positional parameters defined then you will get the error.

Get-Item C:\temp\thing.txt "*"

As this cmdlet does not know how to accept the second positional parameter you get the error. You can fix this by telling it what the parameter is meant to be.

Get-Item C:\temp\thing.txt -Filter "*"

I assume you are getting the error on the following line of code as it seems to be the only place you are not specifying the parameter names correctly, and maybe it is treating the = as a parameter and $username as another parameter.

Set-ADUser $user -userPrincipalName = $newname

Try specifying the parameter name for $user and removing the =


I had this issue after converting my Write-Host cmdlets to Write-Information and I was missing quotes and parens around the parameters. The cmdlet signatures are evidently not the same.

Write-Host this is a good idea $here
Write-Information this is a good idea $here <=BAD

This is the cmdlet signature that corrected after spending 20-30 minutes digging down the function stack...

Write-Information ("this is a good idea $here") <=GOOD


In my case it was the distinction between (En dash) and -(Hyphen) as in:

Add-Type –Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"

and:

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"

Dashes, Hyphens, and Minus signs oh my!


I had this problem when trying to change directory, using the character _. The solution was to use a string to change directories.

C:\> cd "my_new_dir"

In my case there was a corrupted character in one of the named params ("-StorageAccountName" for cmdlet "Get-AzureStorageKey") which showed as perfectly normal in my editor (SublimeText) but Windows Powershell couldn't parse it.

To get to the bottom of it, I moved the offending lines from the error message into another .ps1 file, ran that, and the error now showed a botched character at the beginning of my "-StorageAccountName" parameter.

Deleting the character (again which looks normal in the actual editor) and re-typing it fixes this issue.


I had to use

powershell.AddCommand("Get-ADPermission");
powershell.AddParameter("Identity", "complete id path with OU in it");

to get past this error


In my case I had tried to make code more readable by putting:

"LONGTEXTSTRING " +
"LONGTEXTSTRING" +
"LONGTEXTSTRING"

Once I changed it to

LONGTEXTSTRING LONGTEXTSTRING LONGTEXTSTRING 

Then it worked


I had a similar challenge when writing a Powershell script to interact with AWS CLI using the AWS Powershell Tools

I ran the command:

Get-S3Bucket // List AWS S3 buckets

And then I got the error:

Get-S3Bucket : A positional parameter cannot be found that accepts argument list

Here's how I fixed it:

Get-S3Bucket does not accept // List AWS S3 buckets as an attribute.

I had put it there as a comment, but it's not acceptable by the AWS CLI as a comment. AWS CLI rather sees it as a parameter.

I had to do it this way:

#List AWS S3 buckets
Get-S3Bucket

That's all.

I hope this helps


Questions with powershell tag:

Why powershell does not run Angular commands? How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line? How to print environment variables to the console in PowerShell? Check if a string is not NULL or EMPTY The term 'ng' is not recognized as the name of a cmdlet VSCode Change Default Terminal 'Connect-MsolService' is not recognized as the name of a cmdlet Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet Change directory in PowerShell ps1 cannot be loaded because running scripts is disabled on this system How do I force Robocopy to overwrite files? How to use the curl command in PowerShell? Changing PowerShell's default output encoding to UTF-8 Upload file to SFTP using PowerShell Convert a string to datetime in PowerShell Catching FULL exception message The response content cannot be parsed because the Internet Explorer engine is not available, or Extract the filename from a path Making a PowerShell POST request if a body param starts with '@' If strings starts with in PowerShell Powershell: A positional parameter cannot be found that accepts argument "xxx" Powershell script to check if service is started, if not then start it How to convert string to integer in PowerShell Read file line by line in PowerShell How open PowerShell as administrator from the run window A better way to check if a path exists or not in PowerShell Check if a file exists or not in Windows PowerShell? Ternary operator in PowerShell Splitting a string into separate variables Simple InputBox function How can I find the product GUID of an installed MSI setup? Running PowerShell as another user, and launching a script How do I check if a PowerShell module is installed? How do I assign a null value to a variable in PowerShell? How to Correctly Check if a Process is running and Stop it Convert a secure string to plain text Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API How to unzip a file in Powershell? How to switch to another domain and get-aduser You cannot call a method on a null-valued expression Out-File -append in Powershell does not produce a new line and breaks string into characters User Get-ADUser to list all properties and export to .csv How can I verify if an AD account is locked? How can you test if an object has a specific property? Powershell: count members of a AD group Powershell folder size of folders without listing Subdirectories How to overwrite files with Copy-Item in PowerShell Using "-Filter" with a variable How do I use Join-Path to combine more than two strings into a file path?

Questions with active-directory tag:

Powershell: A positional parameter cannot be found that accepts argument "xxx" How to switch to another domain and get-aduser How can I verify if an AD account is locked? Powershell script to see currently logged in users (domain and machine) + status (active, idle, away) Querying Windows Active Directory server using ldapsearch from command line How to list AD group membership for AD users using input list? Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory What are CN, OU, DC in an LDAP search? PowerShell script to return members of multiple security groups How do I get specific properties with Get-AdUser Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs] Adding and removing extensionattribute to AD object Connect to Active Directory via LDAP Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7) Converting LastLogon to DateTime format Query to list all users of a certain group using wildcards in LDAP search filters/queries DirectorySearcher Filter LDAP root query syntax to search more than one specific OU How to connect with Java into Active Directory "A referral was returned from the server" exception when accessing AD from C# Gradle proxy configuration How to get the groups of a user in Active Directory? (c#, asp.net) How can I get a list of users from active directory? How to get all groups that a user is a member of? Domain Account keeping locking out with correct password every few minutes How to get all the AD groups for a particular user? How to Export-CSV of Active Directory Objects? Finding CN of users in Active Directory Error 0x80005000 and DirectoryServices Get user's non-truncated Active Directory groups from command line "Active Directory Users and Computers" MMC snap-in for Windows 7? VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory How can I find out which server hosts LDAP on my windows domain? How do I find out where login scripts live? What are the differences between LDAP and Active Directory? How to get the current user's Active Directory details in C# Active Directory LDAP Query by sAMAccountName and Domain Quick way to retrieve user information Active Directory Authenticating against Active Directory with Java on Linux Validate a username and password against Active Directory? Authenticating in PHP using LDAP through Active Directory