2016-08-04 65 views
1

在附加的腳本中,如果PC具有某個主機名,我試圖重命名PC。但是,腳本仍在繼續並繞過if/else語句。使用主機名作爲變量在powershell中創建if語句時出錯

我在做什麼錯?我對Windows Powershell有點新了。

謝謝!

# get current computername 
$hostname = hostname.exe 
#$env:computername 
If ($hostname = "CLNT3100") 
{ 

#Get all the computers with CLNT3* and sort them with the 'highest client' on top. Then put them in newlist.txt 
Get-ADComputer -Filter 'SamAccountName -like "CLNT3*"' | Select -Exp Name | Sort-Object -Descending >> C:\newlist.txt 

#Put the text file in a variable and show the top line 
$Text = Get-Content -Path C:\newlist.txt 
#$Text[0] 

#Trim CLNT for numbering 
$Text1 = $Text[0].TrimStart("CLNT") 

#Add 1 number to the previous CLNT 
$Text2 = 1 + $Text1 

#Add CLNT again to the new variable 
$Text3 = "CLNT" + $Text2 

#Rename the computer 
Rename-Computer –computername minint –newname $Text3 
} 
Else 
{ 
Write-Host "Computernaam is niet minint!!!" 
} 

回答

1

要比較兩個值是否在PowerShell中等於你必須使用-eq操作。 檢查Powershell equality operators以查看其他人,如-gt,-lt等,或在PS外殼中鍵入man about_Comparison_Operators

此外,要學習PowerShell,我發現this free ebook是非常好的。

+0

OK,所以應該是If($ hostname -eq「CLNT3100」)呢? – Kevin

+0

是的。這將是-eq/-like/-match。取決於你在做什麼。 –