Skip to content

Instantly share code, notes, and snippets.

@skunkie
Created December 19, 2014 13:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save skunkie/7f09cd3f13de190d262d to your computer and use it in GitHub Desktop.
Save skunkie/7f09cd3f13de190d262d to your computer and use it in GitHub Desktop.
Shell script to rename a virtual machine in VMware ESXi
#!/bin/sh
# shell script to rename a virtual machine in ESXi
VOLNAME=$1
DIRNAME=$2
OLDNAME=$3
NEWNAME=$4
VM_DIRPATH="/vmfs/volumes/$VOLNAME/$DIRNAME"
f_OK() {
if [ $? -eq 0 ]; then
echo "OK"
fi
}
if [ $# -ne 4 ]; then
echo "Usage: $0 VOLNAME DIRNAME OLDNAME NEWNAME
where VOLNAME is the volume name, e.g. datastore1,
DIRNAME is the the name of the directory of the virtual machine,
OLDNAME is the name of the files of the virtual machine before the '.',
NEWNAME is the new name for the directory and the files.
"
exit 1
fi
if [ ! -d $VM_DIRPATH ]; then
echo "The directory path $VM_DIRPATH is invalid"
exit 1
fi
## rename the content of the files
for FILE in $(ls $VM_DIRPATH | grep -E "\.vmx[f]?|\.vmdk|\.vmsd|\.xml" | grep -v "\-flat\.vmdk"); do
echo "changing the contents of the file $FILE"
eval sed -i 's/$OLDNAME/$NEWNAME/g' $VM_DIRPATH/$FILE
f_OK
done
## rename the files
for FILENAME in $(ls $VM_DIRPATH | grep $OLDNAME); do
NEWFILENAME=$(echo $FILENAME | eval sed 's/$OLDNAME/$NEWNAME/')
echo "renaming the file $FILENAME to $NEWFILENAME"
mv $VM_DIRPATH/$FILENAME $VM_DIRPATH/$NEWFILENAME
f_OK
done
## rename the directory
if [ $DIRNAME != $NEWNAME ]; then
NEWVM_DIRPATH=$(echo $VM_DIRPATH |eval sed 's/$DIRNAME/$NEWNAME/')
echo "renaming the directory $VM_DIRPATH to $NEWVM_DIRPATH"
mv $VM_DIRPATH $NEWVM_DIRPATH
f_OK
fi
@Erutan409
Copy link

Thank you for the script! Quick question, though:

I'm currently trying to execute the following:

rename-vm.sh datastore2 Windows\ Server\ 2012 Wndows\ Server\ 2012 Windows\ Server\ 2012\ R2\ \(SVN\)

I'm getting the following error:

sh: Server: unknown operand
ls: /vmfs/volumes/datastore2/Windows: No such file or directory
ls: Server: No such file or directory
ls: 2012: No such file or directory
grep: Server: No such file or directory
grep: 2012: No such file or directory
ls: /vmfs/volumes/datastore2/Windows: No such file or directory
ls: Server: No such file or directory
ls: 2012: No such file or directory
sh: Server: unknown operand

I'm also not that strong on Linux, so I'm slowly troubleshooting my issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment