2015-08-24 3 views
2

Я пытаюсь запустить сценарий с моего хоста Active Directory на других хостах в сети, которые будут извлекать информацию об устройстве для каждого из хостов.Не удалось получить код PowerShell для работы

код я использую:

# Exports Local System Information to CSV 
# Run this PowerShelll script at log on to collect PC information to a CSV file on a network share 
# Thom McKiernan 28/08/2014 

#Get hostnames 
#$Computers = Get-Content ("C:\Users\Administrator.ESP\Documents\SoftwareAuditing\ComputerDetails\ComputerListAug2015.txt") -ErrorAction SilentlyContinue 

foreach ($computer in Get-Content "C:\Users\Administrator.ESP\Documents\SoftwareAuditing\ComputerDetails\ComputerListAug2015.txt") 
{ 

# Collect the info from WMI 
$computerSystem = get-wmiobject Win32_ComputerSystem -Computer $computer.$deviceinfile 
$computerBIOS = get-wmiobject Win32_BIOS -Computer $computer.$deviceinfile 
$computerOS = get-wmiobject Win32_OperatingSystem -Computer $computer.$deviceinfile 
$computerCPU = get-wmiobject Win32_Processor -Computer $computer.$deviceinfile 
$computerHDD = Get-WmiObject Win32_LogicalDisk -ComputerName $computer.$deviceinfile -Filter drivetype=3 
$macAddress = Get-WmiObject win32_networkadapterconfiguration -Computer $computer.$deviceinfile -Filter "IpEnabled = TRUE" 

#Build the CSV file 
$csvObject = New-Object PSObject -property @{ 
    "PCName" = $computerSystem.Name 
    "Manufacturer" = $computerSystem.Manufacturer 
    "Model" = $computerSystem.Model 
    "SerialNumber" = $computerBIOS.SerialNumber 
    "RAM" = "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB) + "GB" 
    "HDDSize" = "{0:N2}" -f ($computerHDD.Size/1GB) + "GB" 
    "HDDFree" = "{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size) + "GB" 
    "CPU" = $computerCPU.Name 
    "OS" = $computerOS.caption 
    "SP" = $computerOS.ServicePackMajorVersion 
    "User" = $computerSystem.UserName 
    "BootTime" = $computerOS.ConvertToDateTime($computerOS.LastBootUpTime) 
    "MACAddress" = $macAddress.MacAddress 
    } 

#Export the fields you want from above in the specified order 
$csvObject | Select PCName, Maufacturer, Model, SerialNumber, RAM, HDDSize, HDDFree, CPU, OS, SP, User, BootTime, MACAddress | Export-Csv 'system-info.csv' -NoTypeInformation -Append 

} 

# Open CSV file for review (leave this line out when deploying) 
notepad system-info.csv 

Однако, я постоянно получаю следующее сообщение об ошибке:

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.

Я пытался настроить текстовый файл, как только имена компьютеров (экспортированный из Active Directory), и я попытался добавить каждое имя с «.domain.com», и ни один из них не работал.

Я попытался иметь только свое устройство в списке, и никаких ошибок не было, но выхода не было. Это было похоже на то, что он не запускался при использовании «powershell -noexit. \ ComputerDetails.ps1», но когда я просто запускаю скрипт, щелкнув правой кнопкой мыши по нему, я вижу, как пролетают ошибки, и ошибка из «Блокнота», в которой указан файл не существует.

Я попытался решить эту проблему и нашел множество ресурсов, которые, похоже, не помогают избавиться от этой ошибки.

Полный список ошибок получил:

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argum 
ent is null or empty. Supply an argument that is not null or empty and then try 
the command again. 
At C:\Users\Administrator.ESP\Documents\SoftwareAuditing\ComputerDetails\Comput 
erDetails.ps1:12 char:63 
+ $computerSystem = get-wmiobject Win32_ComputerSystem -Computer <<<< $compute 
r.$deviceinfile 
    + CategoryInfo   : InvalidData: (:) [Get-WmiObject], ParameterBindi 
    ngValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power 
    Shell.Commands.GetWmiObjectCommand 

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argum 
ent is null or empty. Supply an argument that is not null or empty and then try 
the command again. 
At C:\Users\Administrator.ESP\Documents\SoftwareAuditing\ComputerDetails\Comput 
erDetails.ps1:13 char:51 
+ $computerBIOS = get-wmiobject Win32_BIOS -Computer <<<< $computer.$deviceinf 
ile 
    + CategoryInfo   : InvalidData: (:) [Get-WmiObject], ParameterBindi 
    ngValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power 
    Shell.Commands.GetWmiObjectCommand 

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argum 
ent is null or empty. Supply an argument that is not null or empty and then try 
the command again. 
At C:\Users\Administrator.ESP\Documents\SoftwareAuditing\ComputerDetails\Comput 
erDetails.ps1:14 char:60 
+ $computerOS = get-wmiobject Win32_OperatingSystem -Computer <<<< $computer.$ 
deviceinfile 
    + CategoryInfo   : InvalidData: (:) [Get-WmiObject], ParameterBindi 
    ngValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power 
    Shell.Commands.GetWmiObjectCommand 

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argum 
ent is null or empty. Supply an argument that is not null or empty and then try 
the command again. 
At C:\Users\Administrator.ESP\Documents\SoftwareAuditing\ComputerDetails\Comput 
erDetails.ps1:15 char:55 
+ $computerCPU = get-wmiobject Win32_Processor -Computer <<<< $computer.$devic 
einfile 
    + CategoryInfo   : InvalidData: (:) [Get-WmiObject], ParameterBindi 
    ngValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power 
    Shell.Commands.GetWmiObjectCommand 

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argum 
ent is null or empty. Supply an argument that is not null or empty and then try 
the command again. 
At C:\Users\Administrator.ESP\Documents\SoftwareAuditing\ComputerDetails\Comput 
erDetails.ps1:16 char:61 
+ $computerHDD = Get-WmiObject Win32_LogicalDisk -ComputerName <<<< $computer. 
$deviceinfile -Filter drivetype=3 
    + CategoryInfo   : InvalidData: (:) [Get-WmiObject], ParameterBindi 
    ngValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power 
    Shell.Commands.GetWmiObjectCommand 

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argum 
ent is null or empty. Supply an argument that is not null or empty and then try 
the command again. 
At C:\Users\Administrator.ESP\Documents\SoftwareAuditing\ComputerDetails\Comput 
erDetails.ps1:17 char:72 
+ $macAddress = Get-WmiObject win32_networkadapterconfiguration -Computer <<<< 
$computer.$deviceinfile -Filter "IpEnabled = TRUE" 
    + CategoryInfo   : InvalidData: (:) [Get-WmiObject], ParameterBindi 
    ngValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power 
    Shell.Commands.GetWmiObjectCommand 

Attempted to divide by zero. 
At C:\Users\Administrator.ESP\Documents\SoftwareAuditing\ComputerDetails\Comput 
erDetails.ps1:27 char:53 
+  "HDDFree" = "{0:P2}" -f ($computerHDD.FreeSpace/ <<<< $computerHDD.Size) 
+ "GB" 
    + CategoryInfo   : NotSpecified: (:) [], RuntimeException 
    + FullyQualifiedErrorId : RuntimeException 

Export-Csv : A parameter cannot be found that matches parameter name 'Append'. 
At C:\Users\Administrator.ESP\Documents\SoftwareAuditing\ComputerDetails\Comput 
erDetails.ps1:37 char:183 
+ $csvObject | Select PCName, Maufacturer, Model, SerialNumber, RAM, HDDSize, H 
DDFree, CPU, OS, SP, User, BootTime, MACAddress | Export-Csv 'system-info.csv' 
-NoTypeInformation -Append <<<< 
    + CategoryInfo   : InvalidArgument: (:) [Export-Csv], ParameterBind 
    ingException 
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Comm 
    ands.ExportCsvCommand 
+0

Пожалуйста, покажите содержимое файла ComputerListAug2015.txt, казалось бы, как если бы сценарий возникли проблемы при разборе имя компьютера из этого текстового файла – ShaneC

+1

я не вижу '$ deviceinfile' определено в любом месте. Почему это происходит в вашем вызове GWMI? – TheMadTechnician

+0

[TheMadTechnician] (http://stackoverflow.com/users/3245749/themadtechnician) имеет право. Что такое '$ deviceinfile'? Powershell рассматривает это как свойство '$ computer'. Если свойство не существует (а это не так), то возвращается null. – Matt

ответ

3

Вопрос у вас возникли здесь в том, что PowerShell пытается получить свойство, определяемое $deviceinfile от объекта $computer. Однако $computer - это просто строка, которая не имеет свойства $deviceinfile. Предполагается, что это суффикс как часть вашего соглашения об именах?

Краткое описание вопроса

Посмотрите на следующий пример

$Computer = "comp1" 
$deviceinfile = "Test" 

$Computer.$deviceinfile 

Это не возвращенного ничего, так как есть не свойство «Test» на объекте $computer строки. Я думаю, что результат, который вы ожидали, был comp1.Test. Теперь посмотрим на этот пример.

$deviceinfile = "Test" 
$computer = New-Object -TypeName PSCustomObject -Property @{Test = "Bagel"} 
$Computer.$deviceinfile 

Мы сделали объект с названием Test. «Bagel» - это то, что возвращается из этого кода.

Что вы можете сделать в вашем коде

Если это именование вам нужно положить, что в кавычки, чтобы остановить его от рассматриваться как вызов свойства. Эти переменные будут расширены так, как вы ожидали бы их. Это, конечно, предполагается, что у вас есть $deviceinfileдо это называется.

$computerSystem = get-wmiobject Win32_ComputerSystem -Computer "$computer.$deviceinfile" 

Else просто удалите его.

$computerSystem = get-wmiobject Win32_ComputerSystem -Computer $computer 
+0

Спасибо! deviceinfile был экспериментом, чтобы заставить это работать - это провалилось, и я подумал, что я его удалил. Тем не менее, похоже, что сейчас он работает, просто удалив их. Извините, что это была такая глупая ошибка. –

Смежные вопросы