Looking to Rename Computers with csv file and .vbs script

谁说我不能喝 提交于 2019-12-04 06:52:22

问题


I would love to do this in Powershell but that isn't an option. I have a bunch of computers I'm looking to rename and am trying to automate the process as much as I can. I'd like to have a csv file setup with two columns (oldname,newname) and be able to pull that info into a vbs script to rename the computers automatically.

The code to rename an individual computer is:

Name = "wantedcomputername"
Password = "localadminpassword"
Username = "localadminusername"

Set objWMIService = GetObject("Winmgmts:root\cimv2")

'Call always gets only one Win32_ComputerSystem object.
For Each objComputer In objWMIService.InstancesOf("Win32_ComputerSystem")

    Return = objComputer.rename(Name,Password,Username)
    If Return <> 0 Then
        WScript.Echo "Rename failed. Error = " & Err.Number
    Else
        WScript.Echo "Rename succeeded." &
            "Reboot for new name to have effect"
    End If
Next

I don't want to force a restart of the machine after the name is changed either. A restart will be done but I can't include one in the rename. I don't know enough about coding to go about pulling info from a csv file but I'd appreciate any help or feedback.


回答1:


Opening the CSV as a database is arguably the most elegant way of going about this:

filename = "C:\path\to\your.csv"

Set csv = CreateObject("Scripting.FileSystemObject").GetFile(filename)

Set conn = CreateObject("ADODB.Connection")
Set rs   = CreateObject("ADODB.Recordset")

conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & csv.ParentFolder.Path & ";" & _
          "Extended Properties=""text;HDR=YES;FMT=Delimited"""

rs.Open "SELECT * FROM [" & csv.Name & "]", conn

Do Until rs.EOF
  WScript.Echo rs.Fields("ComputerName").Value
  rs.MoveNext
Loop

rs.Close
conn.Close



回答2:


Essentially you need to:

  1. Open your file for reading as a text file (a csv is just a text file)
  2. While there are lines in the file
  3. Read a line, split the line using the comma into 2 variables oldname, newname, run this bit of code you have to do a rename for the computer
  4. Repeat step 3 until you have no more lines (ie. no more computers) in the csv

Please read how to open a file for reading and read it line by line in vbscript. [Link]

Then read how to split a string in vbscript. [Link]

Combine this knowledge and fill in the last remaining steps in your script. You're almost there! You will need to know file reading, splitting anyways - these are important tools always!!!!



来源:https://stackoverflow.com/questions/24005349/looking-to-rename-computers-with-csv-file-and-vbs-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!