我有一个脚本来重命名网络上的计算机。我试图更改它,以便可以输入当前名称和机器的新名称作为参数或参数(在这种情况下,这是有意义的)。此外,我希望脚本检查参数,如果不存在,则导入CSV文件。
这是我想出来的,但不起作用。从控制台输出来看,param似乎是空的,但是IF语句运行时似乎没有空。
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
}
}发布于 2017-01-31 13:06:32
您是在if语句中将、$o和$n分配给$null,而不是进行比较。您可以检查$o是否为空,如下所示:
if($o)
{
}但是,由于您正在比较一个字符串,所以您可能希望使用静态[string]::IsNullOrEmpty方法检查该字符串是空还是空。因此,重构的代码可能如下所示:
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
}https://stackoverflow.com/questions/41958311
复制相似问题