編輯PC名稱的腳本

編輯PC名稱的腳本

我知道重命名 PC 的 PowerShell 命令是

Rename-Computer -NewName "LAPTOP-*******" -Force

我需要一個腳本,將“DESKTOP”替換為“LAPTOP”,並在 PC 名稱中保留接下來的 8 個字元。

有什麼建議麼?

編輯:

好吧,我想我已經接近解決方案了:

$cmdOutput = $env:COMPUTERNAME -replace "DESKTOP", "LAPTOP" | Out-String
Rename-Computer -NewName "$cmdOutput" -Force

但我收到有關不允許字元的錯誤(這不是真的):

Rename-Computer : Il computer 'DESKTOP-RJL7RM8' con il nuovo nome 'LAPTOP-RJL7RM8
' verrà ignorato perché il nuovo nome non è valido. Il formato del nuovo nome di computer immesso non è corretto. I
nomi standard possono contenere lettere (a-z, A-Z), numeri (0-9) e segni meno (-), ma non sono consentiti spazi o
punti (.). Il nome non può essere costituito esclusivamente da cifre e la lunghezza non può essere maggiore di 63
caratteri.
In D:\RenamePC\RenamePC.ps1:2 car:1
+ Rename-Computer -NewName "$cmdOutput" -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (LAPTOP-RJL7RM8
:String) [Rename-Computer], InvalidOperationException
    + FullyQualifiedErrorId : InvalidNewName,Microsoft.PowerShell.Commands.RenameComputerCommand

重新編輯:

我認為錯誤是新名稱後面的新行。我嘗試-NoNewLine在第一行末尾添加,但 Powershell 回答:

A parameter cannot be found that matches parameter name 'NoNewLine'.

答案1

您只需要「修剪」空白即可。這是代碼。

$cmdOutput = ($env:COMPUTERNAME -replace "DESKTOP", "LAPTOP" | Out-String).Trim()

相關內容