Powershell Invoke-command重命名 - 计算机

时间:2017-02-08 13:31:42

标签: powershell

我正在使用GUI重命名计算机,并且无法解析参数集错误。任何想法或建议?

有问题的功能在这里。如果需要,请在下面填写完整代码。

##Run Button
Function RenameComputers{
        $userPassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
        $Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $userPassword
        foreach ($item in $DataGrid.Items){
        $OName = $item.OldName
        $NName = $item.NewName
        $command = "Rename-Computer -ComputerName $OName -NewName $NName -DomainCredential $Credential -Force -Restart"
        Invoke-Command $command
    }
    }

完整代码

#LoadForm

./LoadDialog.ps1 -XamlPath 'C:\Forms\ReNamer.xaml'

#EVENT Handler
$OldName
$NewName

$AddNameBtn.Add_Click({AddName})

$Import.Add_Click({GetCompList})
$Run.Add_Click({RenameComputers})

#Launch the window
$xamGUI.ShowDialog() | Out-Null


#Csv import button
Function GetCompList{
   $inputfile = Get-FileName "C:\Sysinternals"
   $csvfile = import-csv $inputfile |
        Select-Object @{ n = "OldName"; e = { $_.OldName } }, @{ n = "NewName"; e = { $_.NewName } }
   $csvfile | % { $dataGrid.AddChild($_) }
   }


##Function to open File Explorer dialog box.
Function Get-FileName($initialDirectory){
  try{  
  [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = $initialDirectory
    $OpenFileDialog.filter = "CSV (*.csv)| *.csv"
    $OpenFileDialog.ShowDialog() | Out-Null
    $OpenFileDialog.filename
    }
    catch{
    }
}


##Run Button
Function RenameComputers{
        $userPassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
        $Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $userPassword
        #$creds = Get-Credential
        foreach ($item in $DataGrid.Items){
        $OName = $item.OldName
        $NName = $item.NewName
        $command = "Rename-Computer -ComputerName $OName -NewName $NName -DomainCredential $Credential -Force -Restart"
        Invoke-Command $command
    }
    }


##Add Name button
   Function AddName{
    $row = New-Object PSObject
    Add-Member -InputObject $row -MemberType NoteProperty -Name "OldName" -Value $OldName.Text
    Add-Member -InputObject $row -MemberType NoteProperty -Name "NewName" -Value $NewName.Text
    $DataGrid.AddChild($row)
}

1 个答案:

答案 0 :(得分:0)

该命令应该是一个脚本块。希望您不会将凭据提供给域管理员。该用户必须是本地管理员。

$command = {Rename-Computer -ComputerName $OName -NewName $NName -DomainCredential $Credential -Force -Restart}
Invoke-Command $command

对于远程计算机,即使您以域管理员身份在本地登录,也仍然必须发送域凭据:

invoke-command $OName {rename-computer $using:NName -DomainCredential $using:credential}

或者没有invoke-command:

rename-computer $NName -ComputerName $OName -Protocol WSMan -DomainCredential $credential