使用PS合并计算机类型和资产标签

时间:2020-11-06 21:29:33

标签: powershell

我写了一个PowerShell脚本来重命名我的计算机,将其添加到特定的OU并将其加入域。我的问题是,我们有台式计算机(DT)和便携式计算机(LT)两种类型的计算机,我们给它提供了资产标签,我想请我选择它是台式机还是便携式计算机,然后索要资产标签编号,然后在资产标签号之前添加DT或LT作为计算机名(如果混淆,抱歉),例如:DT01234或LT01235。我将在下面发布我的代码,并以粗体显示重命名计算机的区域。任何帮助都将不胜感激。

Write-Host "Select Desktop or Laptop [1-2] [Default 1]:
1. Desktop
2. Laptop"

$computertype = Read-Host
Write-Host "Please Enter Asset Tag"
$NewCompName = Read-Host
$renamecomputer = $true
if ($NewCompName -eq "" -or $NewCompName -eq $env:COMPUTERNAME) {$NewCompName = $env:COMPUTERNAME; $renamecomputer = $false}
Write-Host "Please enter your desired location [1-7] [Default 1]: 
1. Test
2. Compliance Stations
3. Controls Stations
4. Processing Stations
5. QC Stations
6. Receiving Stations
7. Shipping Stations"
$ou = Read-Host



#$creds = Get-Credential 

function Test-ADCrential{
    [CmdletBinding()]
    param(
        [pscredential]$Credential
    )
     
    try {
        Add-Type -AssemblyName System.DirectoryServices.AccountManagement
        if(!$Credential) {
            $Credential = Get-Credential -EA Stop
        }
        if($Credential.username.split("\").count -ne 2) {
            throw "You haven't entered credentials in DOMAIN\USERNAME format. Given value : $($Credential.Username)"
        }
     
        $DomainName = $Credential.username.Split("\")[0]
        $UserName = $Credential.username.Split("\")[1]
        $Password = $Credential.GetNetworkCredential().Password
     
        $PC = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Domain, $DomainName)
        if($PC.ValidateCredentials($UserName,$Password)) {
            Write-Verbose "Credential validation successful for $($Credential.Username)"
            return $True
        } else {
            throw "Credential validation failed for $($Credential.Username)"
        }
    } catch {
        Write-Verbose "Error occurred while performing credential validation. $_"
        return $False
    }
}

$mycreds = Get-Credential

Write-Host "Adding $NewCompName to the domain"


Read-Host "Press enter to change computer name"

if ($renamecomputer -eq $true)
{Rename-Computer -NewName $NewCompName -DomainCredential $mycreds}
Read-Host "Press enter to restart computer"
Restart-Computer

1 个答案:

答案 0 :(得分:0)

看起来您想要这样的东西

if ($NewCompName -eq "" -or $NewCompName -eq $env:COMPUTERNAME) 
{
    
    $NewCompName = $env:COMPUTERNAME; $renamecomputer = $false
    
}
elseif($NewCompName -inotmatch "^DT|^LT")
{
  switch($computertype )
  {
    1{$NewCompNamePrefix = "DT"}
    2{$NewCompNamePrefix = "LT"}
    default{}
  }
  
  $NewCompName = $NewCompNamePrefix + $NewCompName
}

-inotmatch只是确保如果输入的$newcompname已经看起来像DTwhateverLTwhatever,则不会附加额外的{{1} }或LT

不相关(只是我有点挑剔):

查看DT并将提示嵌套在do while循环中,以便您可以验证输入是否符合您的期望。

类似的东西

Read-host -Prompt
相关问题