Reputation: 95
I have a script to rename computers on my network. I am trying to change it so that I can enter a current name and new name for the machine as an argument or parameter (which ever makes sense in this case.) Also I would like the script to check for the argument and if it does not exist import a CSV file.
This is what I came up with and it is not working. The param appear to be empty from the console output but the IF statement runs as if they are not.
param (
$o = "oldname",
$n = "newname"
)
if(!($o = $null)){
if(!($n = $null)){
Write-Host "Renaming computer from: $o to: $n"
netdom renamecomputer $o /newName:$n /uD:domain\user /passwordD:* /force /reboot
}
}else{
Write-Host "Importing Computers from CSV file"
$csvfile = "C:\Sysinternals\rename.csv"
Import-Csv $csvfile | foreach {
$oldName = $_.OldName;
$newName = $_.NewName;
Write-Host "Renaming computer from: $oldName to: $newName"
netdom renamecomputer $oldName /newName:$newName /uD:domain\username /passwordD:* /force /reboot
}
}
Upvotes: 1
Views: 308
Reputation: 59031
You are assigning $o
and $n
to $null
in your if statement - instead of comparing it. You can check whether $o
is null like this:
if($o)
{
}
But since you are comparing a string, you probably want to check whether the string is null or empty using the static [string]::IsNullOrEmpty
method. So your refactored code could look like this:
param (
$o = "oldname",
$n = "newname"
)
if ([string]::IsNullOrEmpty($o) -or [string]::IsNullOrEmpty($n))
{
Write-Host "Importing Computers from CSV file"
$csvfile = "C:\Sysinternals\rename.csv"
Import-Csv $csvfile | foreach {
$oldName = $_.OldName;
$newName = $_.NewName;
Write-Host "Renaming computer from: $oldName to: $newName"
netdom renamecomputer $oldName /newName:$newName /uD:domain\username /passwordD:* /force /reboot
}
}
else
{
Write-Host "Renaming computer from: $o to: $n"
netdom renamecomputer $o /newName:$n /uD:domain\user /passwordD:* /force /reboot
}
Upvotes: 3