我写了这个小脚本,当我测试Write-Host $serial
时,它显得很好,但当它在后台运行时$serial
似乎包含一个数组。
它尝试将计算机重命名为C000@{SerialNumber=F7ZL3F2}
,而不仅仅是C000F7ZL3F2
。
我该怎么办才能得到字符串而不是这个数组?
Import-Module ActiveDirectory
Get-ADComputer -Filter {Name -like 'DESKTOP-*'} -Properties * | Select Name, DNSHostName | ForEach-Object {
$rtn = Test-Connection -CN $_.dnshostname -Count 1 -BufferSize 16 -Quiet
if ($rtn -match 'True') {
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name | Select-String SerialNumber
$serial = "C000$serial"
// Write-Host $serial
Rename-Computer -ComputerName $_.name -NewName $serial -DomainCredential $mycreds -Force -Restart
}
}
答案 0 :(得分:3)
您的代码中有两个错误需要指出 -
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name | Select-String SerialNumber
Select-String
cmdlet在输入字符串和文件中搜索文本和文本模式。 Get-WMIObject Win32_Bios
的基本类型输出为System.Management.ManagementBaseObject
(Get-WMIObject Win32_Bios).Gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True ManagementObject System.Management.ManagementBaseObject
在这种情况下,您可以使用Select-Object
代替Select-String
,而不是Serial Number
。因为,$serial = "C000$serial"
是输入命令返回的属性之一。
$serial
$serial.SerialNumber
的输出将是这样的:
SerialNumber
5CXXXXYYYXZZZ
同样,您可以Import-Module ActiveDirectory
Get-ADComputer -Filter {Name -like 'DESKTOP-*'} -Properties * | Select Name, DNSHostName | ForEach-Object {
$rtn = Test-Connection -CN $_.dnshostname -Count 1 -BufferSize 16 -Quiet
if ($rtn -match 'True') {
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name |
Select-Object SerialNumber
$serial = "C000$($serial.SerialNumber)"
Rename-Computer -ComputerName $_.name -NewName $serial -DomainCredential $mycreds -Force -Restart
}
}
直接调用它。所以你的整体代码将是
-ExpandProperty
或者您可以使用Select-Object
cmdlet的$serial = Get-WMIObject Win32_Bios -ComputerName $_.name |
Select-Object -ExpandProperty SerialNumber
$serial = "C000$serial"
参数,如
del output.txt
for /R %F in (*.txt) do type "%F" >> output.txt
答案 1 :(得分:1)
您为什么使用Select-String
?我会使用Select-Object
然后使用-ExpandProperty
Import-Module ActiveDirectory
Get-ADComputer -Filter {Name -like 'DESKTOP-*'} -Properties * | Select Name, DNSHostName | ForEach-Object {
$rtn = Test-Connection -CN $_.dnshostname -Count 1 -BufferSize 16 -Quiet
if ($rtn -match 'True') {
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name | Select-Object -ExpandProperty SerialNumber
$serial = "C000$serial"
// Write-Host $serial
Rename-Computer -ComputerName $_.name -NewName $serial -DomainCredential $mycreds -Force -Restart
}
}
答案 2 :(得分:1)
尝试更改此行:
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name |
Select-String SerialNumber
到此:
$serial = (Get-WMIObject Win32_Bios -ComputerName $_.name).SerialNumber
或者这个:
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name |
Select-Object -ExpandProperty SerialNumber