locked
CSV file script to name computersl RRS feed

  • Question

  • Hello, I am having a issues with a PowerShell script that is used to name computers in a domain environment from a CSV files. The script looks to the CSV file to see if the computer MAC address matches, if it does it is suppose to rename the computer that name. If it does not match it is suppose to rename based on the serial number of the computer. The CSV file is hosted on the imaging server. I have the script map a drive to where the file is stored. Here is a copy of the code. 

    $ADUser = "*******\LHMDTuser"
    $ADDomain = "*******.****"
    $ADPassword = ConvertTo-SecureString "**********" -AsPlainText -Force
    $Creds = New-Object System.Management.Automation.PsCredential $ADUser,$ADPassword
    $Compoldname = gc env:computername
    $LocalMac = Get-NetAdapter -Name "Ethernet" | Select Macaddress
    $DriveMap = New-PSDrive -Name "M" -PSProvider FileSystem -Root "\\***********\CSV_Files"  -Credential $Creds
    $ConvertMacHost = $LocalMac[0].MacAddress -replace '(:|-|\.)'
    $NameComputerCSV = Import-Csv '\\lh-wds-mdt\CSV_Files\LH_Master.csv' | Select Workstations,@{Label ="Mac Address"; Expression ={$_."Mac Address".ToUpper()}}|where-object {$_."Mac Address" -eq $ConvertMacHost}|Select Workstations
    $CompSerialNumber = (gwmi win32_BIOS).serialnumber
    $CompPrefix = 'LH'
    $CompNameSerial = ($CompSerialNumber.substring($CompSerialNumber.length - 11)) -replace "-",""
    $CompEnding = 'Desk'
    $CompFullName = $CompPrefix+"-"+$CompSerialNumber+"-"+$CompEnding
    
    Set-ExecutionPolicy -ExecutionPolicy Bypass
    
    Get-Command -Module ActiveDirectory
    $DriveMap
    
    If ([string]::IsNullorEmpty($NameComputerCSV)) 
    {
        rename-computer -NewName $CompFullName -PassThru -Credential $Creds
        
    }
    Else
    {
        #Remove-Computer -ComputerName $NameComputerCSV -Credential $Creds -Verbose -Force
        rename-computer -NewName $NameComputerCSV -PassThru -Credential $Creds
    }

    When the the script runs it puts out this error.

    Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again	TaskSequencePSHost	7/13/2020 2:24:53 PM	0 (0x0000)
    At \\LH-WDS-MDT\DeploymentShare$\Scripts\CSV_Computer_Rename_LH.ps1:7 char:13
    + $DriveMap = New-PSDrive -Name "M" -Root "\\LH-WDS-MDT\CSV_Files" -PSP ...
    +             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~	TaskSequencePSHost	7/13/2020 2:24:53 PM	0 (0x0000)
    InvalidOperation: (M:PSDriveInfo) [New-PSDrive], Win32Exception	TaskSequencePSHost	7/13/2020 2:24:54 PM	0 (0x0000)
    Exception calling "Substring" with "1" argument(s): "StartIndex cannot be less than zero.
    Parameter name: startIndex"	TaskSequencePSHost	7/13/2020 2:24:55 PM	0 (0x0000)
    At \\LH-WDS-MDT\DeploymentShare$\Scripts\CSV_Computer_Rename_LH.ps1:12 char:1
    + $CompNameSerial = ($CompSerialNumber.substring($CompSerialNumber.leng ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~	TaskSequencePSHost	7/13/2020 2:24:55 PM	0 (0x0000)
    NotSpecified: (:) [], MethodInvocationException	TaskSequencePSHost	7/13/2020 2:24:55 PM	0 (0x0000)
    Skip computer 'ADMINIS-8EMV500' with new name '@{Workstations=LH-TestMo-5040}' because the new name is not valid. The new computer name entered is not properly formatted. Standard names may contain letters (a-z, A-Z), numbers (0-9), and hyphens (-), but no spaces or periods (.). The name may not consist entirely of digits, and may not be longer than 63 characters.	TaskSequencePSHost	7/13/2020 2:25:03 PM	0 (0x0000)
    At \\LH-WDS-MDT\DeploymentShare$\Scripts\CSV_Computer_Rename_LH.ps1:29 char:5
    +     rename-computer -NewName $NameComputerCSV -PassThru -DomainCreden ...
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~	TaskSequencePSHost	7/13/2020 2:25:03 PM	0 (0x0000)
    InvalidArgument: (@{Workstations=LH-TestMo-5040}:String) [Rename-Computer], InvalidOperationException	TaskSequencePSHost	7/13/2020 2:25:03 PM	0 (0x0000)

    Any help that you can give would be helpful.

     
    Monday, July 13, 2020 8:19 PM

Answers

  • Okay . . . when you did this:

    $NameComputerCSV = Import-Csv '\\lh-wds-mdt\CSV_Files\LH_Master.csv' | 
        Select Workstations,@{Label ="Mac Address"; Expression ={$_."Mac Address".ToUpper()}}|
            where-object {$_."Mac Address" -eq $ConvertMacHost}|
                Select Workstations

    You create a PSCustomObject in the variable $NameComputerCSV. In that PSCustomObject there's just property name: WorkStations

    If you (as you did) use $NameComputerCSV without asking for that 'WorkStations' property name you got back the string representation of the hash.

    If you had used "Select -Expand Workstations" when you created the PSCustomObject only the value of the hash would have been placed into the property named "Workstations".


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    • Marked as answer by Trevor Roney Wednesday, July 15, 2020 2:39 PM
    Tuesday, July 14, 2020 9:23 PM

All replies

  • Hi Trevor,

    did you try unmount your M psdrive before re-runing the script, as was said in the first error message?

    For what you need M drive if you do not use it in any place?

    Why you need providing plaintext password, instead of using Run As Different user build in windows functionality? 


    The opinion expressed by me is not an official position of Microsoft


    • Edited by Vector BCO Monday, July 13, 2020 9:13 PM
    Monday, July 13, 2020 9:09 PM
  • Before you blindly use New-PsDrive, why not try a Get-PsDrive and then decide whether  to use the existing mapping, or remove the existing mapping and create a new mapping? It's possible that the "M" name, or a drive's 'root', has been created in some other context than the one involving the credentials you're trying to use.

    For the substring error, you should check the length of the string to ensure it's long enough (i.e. "if $CompSerialNumber.length -le 10) {<oops!>} else {<continue-what-you-were-doing>}


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)


    Monday, July 13, 2020 9:33 PM
  • The M drive is not mounted on the server or the workstation. I have the folder shared out on the network from the server. Could that be part of the issue?

    As far the password I haven't tried any other way. I am still new to learning PowerShell, to get this far has taken me about six months.

    Monday, July 13, 2020 9:33 PM
  • The problem with that is I can't see the code when it is running as a task on the MDT server. I can just check the logs after it finished. This script is not ran until after the computer has been joined to the Domain on a newly imaged machine. Also I picked a drive letter I knew that we  where not using. 

    I have thought about trying to use remove-psdrive before it remaps the drive to see if that works. 

    I will look into adding length if statement. 

    Also those error only occur when there is a match in the CSV file for the computer name.

    Monday, July 13, 2020 10:22 PM
  • The code that fails for the substring error isn't conditional on any matches with the data in your CSV. You always execute this line:

    $CompSerialNumber = (gwmi win32_BIOS).serialnumber

    Whether you can "see" the code when it's running as a task (which is a fact you failed to mention!) shouldn't matter. If you code defensively you don't need to see it run.

    Are you positive that all your computer serial numbers are long enough? You don't verify that before operating on the value returned.

    BTW, are you executing your script on the target computer? I don't see anything in your code that implies it's running from a central location. If it's running from a central location you're not supplying the name of the target computer in any thing that I can see.


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)


    Monday, July 13, 2020 11:06 PM
  • I checked on what you where saying the serial number I am trying to get is 7 characters long on the Dell desktops we have. The serial on them is the service tag dell uses. 

    The way the script is being ran is during the task sequence on MDT it runs the script on the computer that is being imaged. That is the only time the script is ran, and that is after the computer has been joined to the domain. The reason for the script is we use tools like PDQ deploy and PDQ Inventory to push software to the computers. It makes it easier if we use the same names for the computer, this is why we have it check the CSV file. 

    I have copied the script to one of the desktops to test the script in powershell ISE. I did a Get-Psdrive to see if the M: is mapped it is not. when I updated the code and took out the $drivemap it solved on of the issues. I was having. 

    I have changed the script around thinking it had something to do with my If else statements. Here is what the code looks like now. I have blanked out the password and domain in this script with *****.

    Set-ExecutionPolicy -ExecutionPolicy Bypass
    $ADUser = "******\LHMDTuser"
    $ADDomain = "*******"
    $ADPassword = ConvertTo-SecureString "********" -AsPlainText -Force
    $Creds = New-Object System.Management.Automation.PsCredential $ADUser,$ADPassword
    $Compoldname = gc env:computername
    $LocalMac = Get-NetAdapter -Name "Ethernet" | Select Macaddress
    $ConvertMacHost = $LocalMac[0].MacAddress -replace '(:|-|\.)'
    $NameComputerCSV = Import-Csv '\\lh-wds-mdt\CSV_Files\LH_Master.csv' | Select Workstations,@{Label ="Mac Address"; Expression ={$_."Mac Address".ToUpper()}}|where-object {$_."Mac Address" -eq $ConvertMacHost}|Select Workstations
    $CompSerialNumber = (gwmi win32_BIOS).serialnumber
    $CompPrefix = 'LH'
    $CompEnding = 'Desk'
    
    Get-Command -Module ActiveDirectory
    
    New-PSDrive -Name "M" -PSProvider FileSystem -Root "\\LH-WDS-MDT\CSV_Files"  -Credential $Creds
    
    
    If ($NameComputerCSV -eq 'True')
    {
      #Remove-Computer -ComputerName $NameComputerCSV -Credential $Creds -Verbose -Force
        rename-computer -NewName $NameComputerCSV -PassThru -DomainCredential $Creds  
    }
    Elseif($CompSerialNumber.Length -gt 11)
    {
        $CompNameSerial=($CompSerialNumber.substring($CompSerialNumber.length - 11)) -replace "-",""
        $CompFullName=$CompPrefix+"-"+$CompSerialNumber+"-"+$CompEnding
        
        rename-computer -NewName $CompFullName -PassThru -DomainCredential $Creds
    }
    Else
    {
        Write-Host "No Computer Name Found"
    }

    At one point I was getting this error after changing the script:

    Rename-Computer : Skip computer 'ADMINIS-H5BBICM' with new name '@{Workstations=LH-TestMo-5040}' because the new name is not valid. The new computer name entered is not 
    properly formatted. Standard names may contain letters (a-z, A-Z), numbers (0-9), and hyphens (-), but no spaces or periods (.). The name may not consist entirely of 
    digits, and may not be longer than 63 characters.
    At line:1 char:1
    + Rename-Computer -NewName $NameComputerCSV -PassThru -DomainCredential ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (@{Workstations=LH-TestMo-5040}:String) [Rename-Computer], InvalidOperationException
        + FullyQualifiedErrorId : InvalidNewName,Microsoft.PowerShell.Commands.RenameCompute

    It sees the computer name in the CSV file but add's this @{workstations=LH-TestMo-5040} to the name. Now it also just skips to the else where I added the write-host command. 

    Tuesday, July 14, 2020 3:30 PM
  • rename-computer -NewName $NameComputerCSV.workstations

    The opinion expressed by me is not an official position of Microsoft

    Tuesday, July 14, 2020 4:42 PM
  • Thank you that seemed get one thing fixed testing it now.
    Tuesday, July 14, 2020 5:02 PM
  • If the machine's serial number is only seven characters long then subtracting 11 from the length gives you a value of -4. The starting index of the substring operation cannot be a negative number. You've addressed that.

    Victor BCO has given you the fix for your name problem. But do you understand why you had that problem to begin with?


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    Tuesday, July 14, 2020 6:37 PM
  • Some what yes. With the Dell computers which is what we use at the location I am at only have the 7 and if I am subtracting then like you said it would be -4. At the other location they have HP machines which have a longer serial number. 

    Also found out that I don't need the new-psdrive to pull the info from the MDT server so I also removed that line as well. Now I am just getting the credentials correct.

    I am thankful both yours and Vector's help.

    Tuesday, July 14, 2020 7:09 PM
  • Okay . . . when you did this:

    $NameComputerCSV = Import-Csv '\\lh-wds-mdt\CSV_Files\LH_Master.csv' | 
        Select Workstations,@{Label ="Mac Address"; Expression ={$_."Mac Address".ToUpper()}}|
            where-object {$_."Mac Address" -eq $ConvertMacHost}|
                Select Workstations

    You create a PSCustomObject in the variable $NameComputerCSV. In that PSCustomObject there's just property name: WorkStations

    If you (as you did) use $NameComputerCSV without asking for that 'WorkStations' property name you got back the string representation of the hash.

    If you had used "Select -Expand Workstations" when you created the PSCustomObject only the value of the hash would have been placed into the property named "Workstations".


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    • Marked as answer by Trevor Roney Wednesday, July 15, 2020 2:39 PM
    Tuesday, July 14, 2020 9:23 PM