Created
December 19, 2014 13:26
-
-
Save skunkie/7f09cd3f13de190d262d to your computer and use it in GitHub Desktop.
Shell script to rename a virtual machine in VMware ESXi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for the script! Quick question, though:
I'm currently trying to execute the following:
I'm getting the following error:
I'm also not that strong on Linux, so I'm slowly troubleshooting my issue.