Форум программистов, компьютерный форум, киберфорум
PowerShell
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.78/181: Рейтинг темы: голосов - 181, средняя оценка - 4.78
0 / 0 / 1
Регистрация: 25.10.2012
Сообщений: 87
1

Получить список принтеров, установленных на удалённом компьютере

25.10.2012, 14:47. Показов 35809. Ответов 5
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Здравствуйте. Нужно вывести на экран список установленных принтеров с удалённого компьютера, используя PowerShell. На данной стадии у меня кое-что получилось, но не выводятся сетевые принтеры, которые установлены на удалённом компьютере.
Вот текст скрипта:
PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    cd\|cls
    $compname = "."
    if (($c = Read-Host "Имя компьютера или IP-адрес") -ne "") {$compname = $c} 
    $printer = Get-WmiObject win32_printer -ComputerName $compname
     
    Write-Host "ПРИНТЕРЫ"
    Write-Host "____________________________________________________________________"
    foreach($prn in $printer) 
    {
        Write-Host "Имя......................."$prn.Name
        Write-Host "Драйвер..................."$prn.DriverName
        Write-Host "По умолчанию.............."$prn.Default
        ""
    }
Читал, что если делаешь это через wmi-объекты, то powershell берёт локального пользователя машины, с которой подключаешься удалённо. Пробовал ключ "-Credential" - не помогло.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
25.10.2012, 14:47
Ответы с готовыми решениями:

Получить список установленных программ на удаленном ПК в сети
Всем привет. На форме есть listbox (со списком компьютеров в сети). Кнопка и listview со...

На удаленном сервере не видно локально установленных принтеров
Всем привет! Нужна Ваша помощь, чтобы разобраться в одной штуке. Ситуация: у нас имеются 3...

Как получить список установленных программ на компьютере?
Есть программа CCleaner, если зайти в раздел инструменты/ удаление, то там весь список программ для...

Как получить список всех установленных служб на компьютере
Нагуглил такой код: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As...

5
403 / 86 / 8
Регистрация: 16.02.2013
Сообщений: 358
16.02.2013, 10:37 2
Цитата Сообщение от lich130387 Посмотреть сообщение
Читал, что если делаешь это через wmi-объекты, то powershell берёт локального пользователя машины, с которой подключаешься удалённо. Пробовал ключ "-Credential" - не помогло.
Наврали. Запускается под учеткой того, кто запустил скрипт.

Сетевые принтеры устанавливаются для каждого пользователя отдельно.
Задача разбивается на следующие этапы.

1. Определить текущего интерактивного пользователя.
2. Определить его сетевые принтеры.

Оба этапа решаемы.
К сожалению код у меня на работе
0
0 / 0 / 1
Регистрация: 25.10.2012
Сообщений: 87
16.02.2013, 14:34  [ТС] 3
Допустим первую часть я сделаю (пока ещё не думал об этом).
А во второй-то как получить сетевые принтеры? после -Credential писать?
0
403 / 86 / 8
Регистрация: 16.02.2013
Сообщений: 358
16.02.2013, 16:55 4
-Credential нужен только в двух случаях

1. Запускающий не является локальным админом на целевой машине и надо запустить скрипт из-под другой учетной записи, которая эти права имеет.

2. При открытии сессии или запуске команды через WinRm (Invoke-Command), если в -computername используется IP, а не имя хоста
0
4 / 4 / 3
Регистрация: 16.07.2014
Сообщений: 19
08.09.2016, 14:25 5
Можно использовать такой скрипт, удобно

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
    <# 
    Script Name:  GetMappedNetworkPrinters.ps1 
     
    Purpose: 
    This script can be used to collect the mapped network printer information from the users who are logged into the console of the Computer or Computers specified. 
     
    Required Modules: 
    PSRemoteRegistry, and Active Directory 
     
    Permission Requirements: 
    The user account that the script is run with needs to have administrative permissions on the workstations and permission to query Active Directory user accounts. 
    The computers firewall if enabled needs to allow it to be pinged, connections to WMI and also Remote Registry. 
    A user will need to be logged into the console so their mapped network printer information can be collected. 
     
    How the script functions: 
    Create a text file that contains a list of Computer names that you want to get the mapped network printers info for. 
    Execute the script and you will be prompted for the path to the text file that contains the list. 
    Connectivity will be verified to each of the computers by pinging each of them. 
    Via WMI it will check to see which user is logged into the computers that responded to the ping. 
    Next it will query Active Directory for the SID of each of the users that were currently logged into one of the active computers polled. 
    Using the users SID a Remote Registry query is created to enumerate the list of mapped network printers for the logged on user. 
     
    The Log files and CSV file containing the list of mapped printers is located in C:\temp\logs 
    FileNames: 
    MappedPrinters-(currentdate).csv -- Contains the list of mapped printers. 
    NoMappedPrinters-(currentdate).log -- Contains list of users that do not have network printers mapped on their computer. 
    NoReply-(currentdate).csv -- Contains list of computers that did not respond to ping. 
    NoUsrLoggedIn-(currentdate).log -- Contains list of computers that responded to ping but did not have a user logged into it. 
    RemoteRegNotRunning-(currentdate).log -- Contains a list of computers where the Remote Registry service is not running. 
    WmiError-(currentdate).log -- If there are computers that it is not able to connect to via wmi it will be listed here. 
    #> 
     
     
     
    function global:Ping-Host {  
        BEGIN { 
             
        } 
            PROCESS { 
            $results = gwmi -Query "SELECT * FROM Win32_PingStatus WHERE Address = '$_'" 
            $obj2 = New-Object psobject 
            $obj2 | Add-Member Noteproperty Computer $_ 
            $obj2 | Add-Member Noteproperty IPAddress ($results.protocoladdress) 
                     
            if ($results.statuscode -eq 0) { 
            $obj2 | Add-Member NoteProperty Responding $True 
            } else { 
            $obj2 | Add-Member NoteProperty Responding $False 
        } 
            Write-Output $obj2 
             
        } 
        END {} 
         
    } 
    function VerifyConnectivity { 
    param ( 
    [parameter(ValueFromPipeline=$true)] 
    $compList 
    ) 
    BEGIN { 
    $modeMSG = "Verifying Connectivity to Desktops" 
    $HostComputer = @() 
    $d = Get-Date 
    $strDate = $d.ToString() 
    $month = $d.Month 
    $day = $d.Day 
    $year = $d.Year 
    $cDate = "$month-$day-$year" 
    $logFilePath = "C:\temp\logs" 
    $NoReplyLog = $logFilePath + "NoReply-" + $cDate + ".csv" 
    } 
    PROCESS { 
    $i = 1 
    $numComp = $compList.Count 
    If ($numComp -ge 1){ 
    Talk $modeMSG 
    $HostComputer = $HostComputer + $( 
        foreach ($computer in $compList){ 
        Write-Progress -Activity $modeMSG -Status "Currently Processing: $computer" -CurrentOperation "$i of $numComp" -PercentComplete ($i/$numComp*100) 
        $computer | Ping-Host 
        $i = $i + 1 
     
    }) 
     
    } 
    ElseIf ($numComp -lt 1){ 
    Write-Host "No Computers to Process" 
    Exit 
    } 
    } 
    END { 
    $Alive = $HostComputer | Where {$_.Responding -eq "$true"} 
    $global:Dead = $HostComputer | Where {$_.Responding -ne "$true"} 
    $global:Dead | select Computer | Export-Csv -Path $NoReplyLog 
    $Acomp = $Alive | select Computer 
    $Acomp 
    } 
     
    } 
     
    function GetPrinterInfo { 
    param ( 
    [parameter(ValueFromPipeline=$true)] 
    $compList 
    ) 
    BEGIN { 
    $d = Get-Date 
    $strDate = $d.ToString() 
    $month = $d.Month 
    $day = $d.Day 
    $year = $d.Year 
    $cDate = "$month-$day-$year" 
    $global:logFilePath = "C:\temp\logs" 
    $NoPrtMapLog = $logFilePath + "NoMappedPrinters-" + $cDate + ".log" 
    $WmiErrorLog = $logFilePath + "WmiError-" + $cDate + ".log" 
    $MappedPrinters = $logFilePath + "MappedPrinters-" + $cDate + ".csv" 
    $NoUsrLoggedIn = $logFilePath + "NoUsrLoggedIn-" + $cDate + ".log" 
    $RemoteRegNotRunning = $logFilePath + "RemoteRegNotRunning-" + $cDate + ".log" 
    $ErrorActionPreference = 'SilentlyContinue' 
    Import-Module activedirectory 
    Import-Module psremoteregistry 
    $global:wmiErrors = @() 
    $global:NoUserLoggedIn = @() 
    $CompUserInfo = @() 
    $arrCompLogonInfo = @() 
    $arrRemoteRegSvcStopped = @() 
    $arrNoMappedPrinters = @() 
    $arrMappedPrinters = @() 
    $statusMSG = "Getting Logged on User Information" 
    $statusMSG2 = "Getting User SID from Active Directory" 
    $statusMSG3 = "Collecting Mapped Printer Information" 
    } 
    PROCESS { 
    $u = 1 
    $Responded = VerifyConnectivity $compList 
    if ($Responded.count -gt 0){ 
    Talk $statusMSG 
    foreach ($client in $Responded){ 
        [string]$c = $client.Computer 
        $numClient = $Responded.Count 
        $logonInfo = $null 
        Write-Progress -Activity $statusMSG -Status "Currently Processing: $c" -CurrentOperation "$u of $numClient" -PercentComplete ($u/$numClient*100)   
        $logonInfo = Get-WmiObject -ComputerName $c -Query "select * from win32_computersystem" | select Username 
        if ($?){ 
            if ($logonInfo.Username -ne $null){ 
                [string]$strUserName = $logonInfo.Username 
                $arrStrUserName = $strUserName.Split("") 
                $strUser = $arrStrUserName[1]  
                $objCUinfo = New-Object psobject 
                $objCUinfo | Add-Member NoteProperty Workstation $c 
                $objCUinfo | Add-Member NoteProperty User $strUser 
                $CompUserInfo = $CompUserInfo + $objCUinfo             
            } 
            elseif ($logonInfo.Username -eq $null){ 
            $global:NoUserLoggedIn = $global:NoUserLoggedIn + $c 
            } 
        } 
        else { 
            $global:wmiErrors = $global:wmiErrors + "Could not Execute WMI Query to collect user logon information on $c" 
        } 
        $u = $u + 1 
        } 
        if ($CompUserInfo.Count -ge 1){ 
            $u = 1 
            Talk $statusMSG2 
            foreach ($logon in $CompUserInfo){ 
            [string]$userLN = $logon.User 
            $userCount = $CompUserInfo.count 
            [string]$wrksta = $logon.Workstation 
            Write-Progress -Activity $statusMSG2 -Status "Currently Processing: $userLN" -CurrentOperation "$u of $userCount" -PercentComplete ($u/$userCount*100) 
            $getSID = Get-ADUser -Identity $userLN | select SID 
            if ($?){ 
                [string]$sid = $getSID.sid 
                $LoggedOnUserInfo = New-Object psobject 
                $LoggedOnUserInfo | Add-Member Noteproperty Workstation $wrksta 
                $LoggedOnUserInfo | Add-Member Noteproperty User $userLN 
                $LoggedOnUserInfo | Add-Member Noteproperty SID $sid 
                $arrCompLogonInfo = $arrCompLogonInfo + $LoggedOnUserInfo 
            } 
            $u = $u + 1 
            } 
        } 
        if ($arrCompLogonInfo.count -ge 1){ 
            $u = 1 
            Talk $statusMSG3 
            foreach ($comp in $arrCompLogonInfo){ 
            $numT = $arrCompLogonInfo.Count 
            $Printers = $null 
            [string]$cn = $comp.Workstation 
            [string]$usid = $comp.sid 
            [string]$uName = $comp.User 
            Write-Progress -Activity $statusMSG3 -Status "Currently Processing: $cn" -CurrentOperation "$u of $numT" -PercentComplete ($u/$userCount*100) 
            $regStat = Get-Service -ComputerName $cn -Name "RemoteRegistry" 
            If ($?){ 
                If ($regStat.Status -eq "Running"){ 
                    $Printers =  Get-RegKey -ComputerName $cn -Hive "Users" -Key "$usid\Printers\Connections" -Recurse 
                    If ($Printers -ne $null){ 
                    foreach ($printer in $Printers){ 
                    [string]$printerKey = $printer.key 
                    $arrPrinterKey = $printerKey.Split("") 
                    $PrinterNamePiece = $arrPrinterKey[3] 
                    $arrPrinterParts = $PrinterNamePiece.Split(",") 
                    $printServer = $arrPrinterParts[2] 
                    $PrinterName = $arrPrinterParts[3] 
                    $PrinterUnc = "\\$printServer\$PrinterName" 
                    $printInfo = New-Object psobject 
                    $printInfo | Add-Member NoteProperty Workstation $cn 
                    $printInfo | Add-Member NoteProperty User $uName 
                    $printInfo | Add-Member NoteProperty PrintServer $printServer 
                    $printInfo | Add-Member NoteProperty PrinterName $PrinterName 
                    $printInfo | Add-Member NoteProperty PrinterUNC $PrinterUnc 
                    $arrMappedPrinters = $arrMappedPrinters + $printInfo 
                    } 
                    } 
                    ElseIf ($Printers -eq $null){ 
                        $arrNoMappedPrinters = $arrNoMappedPrinters + "$uName has no mapped printers on $cn" 
                        } 
                } 
                ElseIf ($regStat.Status -eq "Stopped"){ 
                    $arrRemoteRegSvcStopped = $arrRemoteRegSvcStopped + $cn 
                } 
            } 
            $u = $u + 1 
            } 
         
         
        } 
         
    } 
    } 
    END { 
        $arrMappedPrinters | Export-Csv -Path $MappedPrinters 
        Add-Content $NoPrtMapLog $arrNoMappedPrinters 
        Add-Content $WmiErrorLog $wmiErrors 
        Add-Content $NoUsrLoggedIn $global:NoUserLoggedIn 
        Add-Content $RemoteRegNotRunning $arrRemoteRegSvcStopped 
        } 
    } 
     
    function Talk { 
    param ( 
    [parameter(ValueFromPipeline=$true)] 
    $talk 
    ) 
    Add-Type -AssemblyName System.Speech 
    $synthesizer = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer 
    $synthesizer.Speak($talk) 
     
    } 
     
    cls 
    $getPath = $(Read-Host "Enter path to the text file that contains the list of Computer Names`n") 
    cls 
    if ($getPath -like "*.txt"){ 
        $valid = Test-Path -Path $getPath 
        if ($valid -eq $true){ 
            $compList = get-content -Path $getPath  
            GetPrinterInfo $compList 
            Write-Host "The Script Output is located in $logfilepath" 
            Exit 
     
        } 
     
        Else { 
        Write-Host "Path to file is not valid" -ForegroundColor Red 
        } 
    } 
    Elseif ($getPath -notlike "*.txt"){ 
        Write-Host "Path to file is not valid" 
        Exit 
    }
Источник
0
4 / 4 / 3
Регистрация: 16.07.2014
Сообщений: 19
15.09.2016, 07:54 6
Для корректной работы скрипта необходимо установить модуль PSRemoteRegistry для текущего пользователя с которого будет исполнятся скрипт
0
15.09.2016, 07:54
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
15.09.2016, 07:54
Помогаю со студенческими работами здесь

Как получить список дисков на удаленном компьютере?
Подскажите, как получить список дисков на удаленном компьютере через idFTP?

Получить информацию о модели монитора на удаленном компьютере
Помогите пожалуйста с программой. Необходимо получить информацию о модели монитора на удаленном...

Получить к файлу на удаленном компьютере (что-то наподобие вируса)
На локальном компьютере(в открытой папке, общедоступна) лежит моя программа. Могу ли я через нее...

С помощью командного файла получить информацию о разрешениях доступа к папке на удаленном компьютере
задали лабораторку(( первый раз слышу про bat-файл? помогите написать его ПОЖАЛУЙСТА (( Вот...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru