Показать полную графическую версию : Не преобразуется переменная в значение
MaleyDarc
19-04-2017, 14:22
Итак есть скрипт:
#$ErrorActionPreference= 'silentlycontinue'
try{
Remove-item 'host-os.txt'
}
catch{}
$FormatEnumerationLimit=-1
#Set-PSDebug -Trace 1
For ($n=1; $n -le 254; $n++) {
$IP = ("172.168.55." + $n).ToString()
#write-Output $IP
write-Output $IP":" | Add-Content 'host-os.txt'
Try {
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName $IP
$Error[0].InvocationInfo.line
# | Format-List -Property Caption,CSDVersion,InstallDate,OSArchitecture,SerialNumber
#| Add-Content 'host-os.txt'
}
Catch [Exception]{
write-Output $_.Exception|format-list -force
}
}
Я не понимаю почему в команде Get-WmiObject переменная $IP не преобразуется в значение.
Пробовал так:
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName $IP
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName $($IP)
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName $IP.ToString()
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName '172.16.55.$IP'
результат один: не воспринимает переменную $IP за переменную и не подставляет значение.
Второй вопрос, почему не срабатывает try, вывод:
"$Error[0].InvocationInfo.line" - "Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName $IP"
а должно быть "Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName 172.16.55.1"
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At C:\Users\adm-maleev\Documents\scan_os_ver.ps1:14 char:4
+ Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerNam ...
т.е. в catch никогда не попадаем.
1. Подставляет
2. Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName $IP - должно быть,а не содежимое переменной
3. Если требуется исполнять код в catch, то добавить -ErrorAction Stop
For ($n=1; $n -le 254; $n++) {
$IP = "172.168.55.$n"
Try {
Write-Host "Connect to $IP" -ForeGround Yellow
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName $IP -ErrorAction Stop
}
Catch {
write-Output $_.Exception|format-list -force
}
}
И чтобы убедиться:
PS (STA) > Trace-Command {Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName $IP} -PSHost -Name ParameterBinding
...........................................
DEBUG: ParameterBinding Information: 0 : BIND arg [172.168.55.1] to parameter [ComputerName]
MaleyDarc
19-04-2017, 14:50
Тогда я что-то не понимаю. Запускаю Ваш скрипт, получаю:
PS C:\Users\adm\Documents> C:\Users\adm\Documents\test1.ps1
Connect to 172.168.55.8
ErrorCode : -2147023174
Message : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
Data : {}
InnerException :
TargetSite : Void Start()
StackTrace : at System.Management.ThreadDispatch.Start()
at System.Management.ManagementScope.Initialize()
at System.Management.ManagementObjectSearcher.Initialize()
at System.Management.ManagementObjectSearcher.Get()
at Microsoft.PowerShell.Commands.GetWmiObjectCommand.BeginProcessing()
HelpLink :
Source : System.Management
HResult : -2147023174
Connect to 172.168.55.9
ErrorCode : -2147023174
Message : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
Data : {}
InnerException :
TargetSite : Void Start()
StackTrace : at System.Management.ThreadDispatch.Start()
at System.Management.ManagementScope.Initialize()
at System.Management.ManagementObjectSearcher.Initialize()
at System.Management.ManagementObjectSearcher.Get()
at Microsoft.PowerShell.Commands.GetWmiObjectCommand.BeginProcessing()
HelpLink :
Source : System.Management
HResult : -2147023174
По данным IP компьютеры включены и доступны, если выполнить обращение вручную.
Debug:
Connect to 172.168.55.8
DEBUG: 5+ >>>> Trace-Command {Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2
-ComputerName $IP} -PSHost -Name ParameterBinding
DEBUG: 5+ Trace-Command >>>> {Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2
-ComputerName $IP} -PSHost -Name ParameterBinding
DEBUG: 5+ Trace-Command { >>>> Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2
-ComputerName $IP} -PSHost -Name ParameterBinding
DEBUG: ParameterBinding Information: 0 : BIND NAMED cmd line args [Get-WmiObject]
DEBUG: ParameterBinding Information: 0 : BIND arg [Win32_OperatingSystem] to parameter [Class]
DEBUG: ParameterBinding Information: 0 : COERCE arg to [System.String]
DEBUG: ParameterBinding Information: 0 : Parameter and arg types the same, no coercion is needed.
DEBUG: ParameterBinding Information: 0 : BIND arg [Win32_OperatingSystem] to param [Class] SUCCESSFUL
DEBUG: ParameterBinding Information: 0 : BIND arg [root/cimv2] to parameter [Namespace]
DEBUG: ParameterBinding Information: 0 : COERCE arg to [System.String]
DEBUG: ParameterBinding Information: 0 : Parameter and arg types the same, no coercion is needed.
DEBUG: ParameterBinding Information: 0 : BIND arg [root/cimv2] to param [Namespace] SUCCESSFUL
DEBUG: ParameterBinding Information: 0 : BIND arg [172.168.55.8] to parameter [ComputerName]
DEBUG: ParameterBinding Information: 0 : COERCE arg to [System.String[]]
DEBUG: ParameterBinding Information: 0 : Trying to convert argument value from System.String to
System.String[]
DEBUG: ParameterBinding Information: 0 : ENCODING arg into collection
DEBUG: ParameterBinding Information: 0 : Binding collection parameter ComputerName: argument type [String],
parameter type [System.String[]], collection type Array, element type [System.String], coerceElementType
DEBUG: ParameterBinding Information: 0 : Creating array with element type [System.String] and 1 elements
DEBUG: ParameterBinding Information: 0 : Argument type String is not IList, treating this as scalar
DEBUG: ParameterBinding Information: 0 : COERCE arg to [System.String]
DEBUG: ParameterBinding Information: 0 : Parameter and arg types the same, no coercion is needed.
DEBUG: ParameterBinding Information: 0 : Adding scalar element of type String to array position 0
DEBUG: ParameterBinding Information: 0 : Executing VALIDATION metadata:
[System.Management.Automation.ValidateNotNullOrEmptyAttribute]
DEBUG: ParameterBinding Information: 0 : BIND arg [System.String[]] to param [ComputerName] SUCCESSFUL
DEBUG: ParameterBinding Information: 0 : BIND POSITIONAL cmd line args [Get-WmiObject]
DEBUG: ParameterBinding Information: 0 : MANDATORY PARAMETER CHECK on cmdlet [Get-WmiObject]
DEBUG: ParameterBinding Information: 0 : CALLING BeginProcessing
DEBUG: ParameterBinding Information: 0 : BIND PIPELINE object to parameters: [Out-Default]
DEBUG: ParameterBinding Information: 0 : PIPELINE object TYPE = [System.Management.Automation.ErrorRecord]
DEBUG: ParameterBinding Information: 0 : RESTORING pipeline parameter's original values
DEBUG: ParameterBinding Information: 0 : Parameter [InputObject] PIPELINE INPUT ValueFromPipeline NO COERCION
DEBUG: ParameterBinding Information: 0 : BIND arg [The RPC server is unavailable. (Exception from HRESULT:
0x800706BA)] to parameter [InputObject]
DEBUG: ParameterBinding Information: 0 : BIND arg [The RPC server is unavailable. (Exception from HRESULT:
0x800706BA)] to param [InputObject] SUCCESSFUL
То что 172.168.55.8 и 172.168.55.9 - включены, это не значит что корректно настроен firewall, работают требуемые службы и т.д.
По данным IP компьютеры включены и доступны, если выполнить обращение вручную. - Чтобы не быть голословным, что вручную все работает замечаетельно, прилагайте скриншот, где показано выполнение команд:
whoami /user
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName 172.168.55.8,172.168.55.9
MaleyDarc
19-04-2017, 15:11
Мои искренние извинения за потраченное время. Нашел ошибку. Адреса 172.16.*, а не 172.168.*!
Вот что значит не внимательность. Узнал для себя "глубины дебага".
Тогда наверное последний вопрос. Почему в файл попадает тип объекта, а не его значение:
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName $IP -ErrorAction Stop | Format-List -Property Caption, CSDVersion, InstallDate, OSArchitecture, SerialNumber | Add-Content 'host-os.txt'
В файле:
172.16.55.8:
Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
Microsoft.PowerShell.Commands.Internal.Format.GroupStartData
Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData
Microsoft.PowerShell.Commands.Internal.Format.GroupEndData
Microsoft.PowerShell.Commands.Internal.Format.FormatEndData
Использовать: Out-File -Append
© OSzone.net 2001-2012
vBulletin v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.