Powershell Get-ciminstance error in foreach Loop - powershell

New to Powershell, trying to use it to update our AD inventory with Serial Numbers from all computers in the environment. I have exported a .csv with all the machine names, and am trying to run through that in a loop from my machine
The script runs fine without the loop-- if I run it and swap the $name variable with a string it works, and if I run it and define the variable and don't loop it work.When in the loop I get this error:
WS-Management could not connect to the specified destination: (#{Name="PC1"}:5985).
This is a different error than if I type a hostname that doesn't exist or one that isn't in DNS. It's getting the proper info from the .csv like "PC1". tried using start-sleep -second 2 to give it some time to connect to each machine but I don't think that's helping.
$admachines = import-csv .\Computerinventory.csv
foreach ($hostname in $admachines){
$sn = Get-CimInstance -Class win32_bios -ComputerName $hostname |select-object -expandproperty serialnumber
Set-ADComputer -identity $hostname -replace #{serialNumber = $sn}
}

Related

Get Service from remote machines in a domain

Trying to get list of all machines in a Domain with a certain service
tried via all posts in here, helped per one machine, but if i use a text file with multiple machines, it failes
$computers = Get-Content c:\script\computers.txt
$service = "*crystal*"
foreach ($computer in $computers) {
$servicestatus = Get-Service -ComputerName $computer -Name $service
}
$Data = $servicestatus | Select-Object Name,Machinename | Format-Table -AutoSize
Write($Data) | Out-File c:\script\output.txt -Append
Expected list of machines with service in table, instead got error:
This operation might require other privileges
same script, but with a direct machine name, works like a charm.
Any clue what is wrong?
Why not use:
Invoke-Command -ComputerName $computers -ScriptBlock {Get-Service -Name *crystal*}
Eventually you may store the result from invoke into a variable and work with it.
The benefit of using Invoke-Command, insted of foreach is that Invoke works in parallel, while foreach is serial ...
Hope it helps!
Best regards,
Ivan

Get List of Printer Drivers from list of Computers PowerShell

I've tried a variety of iterations of this and gotten a range of errors. I'm trying to get a a list of installed drivers off from a list of computers. None of the ways I've tried in PowerShell have piped the information into a csv. Here's the current iteration of the script.
#Load Active Directory
Import-Module activedirectory
#Load list of computers
$results = #()
$Computer = Get-Content -path 'C:\ScriptResources\computers.txt'
#Check each computer in the list
foreach($ComputerName in $Computer)
{
$results += Get-ADComputer -Filter " Name -Like '*$ComputerName*' " | Get-PrinterDriver; Start-Sleep -milliseconds 500
}
#Export to CSV file
$results | export-csv 'C:\ScriptResults\InstalledPrinters.csv'
I've also used it with just the Get-Printer command and got the following error.
Get-Printer : No MSFT_Printer objects found with property 'Name' equal to 'Redacted'. Verify the value of the
property and retry.
Depending what I've fed the $Computer file I'll get different errors. I've also gotten the RPC server is unavailable and Error Spooler Service Not Running. I have domain wide privileges and I checked the print spooler service and it is running.
The reason I think this is odd is that I have .bat tool that I use that gets printer info from a singular host and I don't run into any issues. The reason I'm trying to put this in PowerShell is because 1) I want to do the whole domain and 2) PowerShell formats its outputs in a more useable fashion.
wmic /node:%ComputerIP% path win32_printer get deviceid, drivername, portname
Additionally, I've also tried the following in the $results function of the script
$results += Get-WmiObject -class Win32_printer -ComputerName name, systemName, shareName
This didn't give errors. What it did instead is that for each computer in the list of computers it checked the computer I was running the script from for its printers and output on each line which printers were installed on my computer.
I'm at a loss and any help would be appreciated. Thanks!
Just so this is closed out. Vivek's answer ended up working.
$results += Get-WmiObject -class Win32_printer -ComputerName $Computer | Select name, systemName, shareName
The RPC issue I was getting was that the list of computers were all turned off for some reason (remote site + different time zone + doing the testing during second shift). Normally, everything remains on though. So that was just an anomaly.
Thanks for the help!

Powershell script to get NIC speed from remote hosts

I'm trying to create PowerShell script to get the NIC speed of remote hosts, and output the end result to a txt file.
So far, this is what I've got:
Hostname
Get-NetAdapter | SELECT LinkSpeed
Out-File C:\CheckNIC-Speed\checknic.txt
That's a script for the local computer, but it also won't output the results to the txt, instead it will just create an empty file.
Now, I also need to run it on multiple remote hosts and get the output to the same file.
Thanks.
("Server1","Server2","Server3") | Foreach {
Invoke-Command -ComputerName $_ -ScriptBlock {
[PSCustomObject]#{
LinkSpeed = (Get-NetAdapter).LinkSpeed -join " & "
HostName = $env:COMPUTERNAME
}
}
} | Out-File "C:\File.txt"
This should retrieve info for any of the servers listed within the brackets, you can also import from a list.
look up Invoke-Command Help if you need to do this kind of thing.
You can use wmi-object for the same:
get-wmiobject win32_networkadapter -ComputerName Server01,Server02,Server03 | select name,speed, pscomputername

Trouble with Get-WmiObject while running powershell script to back up DNS Zones

I have this script that I am trying to run, that I hope will back up DNS zones. I am attempting to export this information into a csv file using the export-csv powershell cmdlet. Finally, I use use the dnscmd.exe command to export zones information into a text file and store them in the defined location.
# Get Name of the server with env variable
$DNSSERVER=get-content env:computername
#—Define folder where to store backup —–#
$BkfFolder=”c:\windows\system32\dns\backup”
#—Define file name where to store Dns Settings
$StrFile=Join-Path $BkfFolder “input.csv”
#—-Check if folder exists. if exists, delete contents–#
if (-not(test-path $BkfFolder)) {
new-item $BkfFolder -Type Directory | Out-Null
} else {
Remove-Item $BkfFolder”\*” -recurse
}
#—- GET DNS SETTINGS USING WMI OBJECT ——–#
#– Line wrapped should be only one line –#
$List = get-WmiObject -ComputerName $DNSSERVER
-Namespace root\MicrosoftDNS -Class MicrosoftDNS_Zone
#—-Export information into input.csv file —#
#– Line wrapped should be only one line –#
$list | Select Name,ZoneType,AllowUpdate,#{Name=”MasterServers”;Expression={$_.MasterServers}},
DsIntegrated | Export-csv $strFile -NoTypeInformation
#— Call Dnscmd.exe to export dns zones
$list | foreach {
$path=”backup\”+$_.name
$cmd=”dnscmd {0} /ZoneExport {1} {2}” -f $DNSSERVER,$_.Name,$path
Invoke-Expression $cmd
}
# End of Script
#——————————————————————————————-#
When I run the script, I get the following message:
I am not exactly sure what this message is saying. I tried inputting my computer name, but that does not work either.
Any help is appreciated!
From line 2:
$DNSSERVER=get-content env:computername
should be:
$DNSSERVER = $Env:Computername
The error is in this line:
$List = get-WmiObject -ComputerName $DNSSERVER -Namespace root\MicrosoftDNS -Class MicrosoftDNS_Zone
Make sure that it's on the same line instead of separate lines, It is requesting the class for the gwmi command, but since it is in another line it's not taking it. Because the class does exist in here so the issue should be in that particular line.
Another point it is looking for the DNS class so only would work if the windows servers have DNS feature or role installed on it.

How can I hardcode specific server names in powershell script

I want to reboot specific servers, I am using findstr to find specific servers in the list of 1000's of servers, however, is there any way I can hardcode servernames in a script so the script only run on a particular set of remote servers? Also, how to use for each against array variable. For e.g is below method correct?
$serverlist = "server1,server2,server3"
for each ($server in $serverlist){ $serverboot= gwmi win32_operatingsystem -comp $server
$serverboot.Reboot
}
First define a list of your servers for this the coma (,) is the array operator in PowerShell :
$serverlist = "server1","server2","server3"
Now $serverlist is an array or a collection you can use.
Then you pipe this list in the Foreach-Object Cmdlet that allow you to execute a scriptblock for each element in the list. $_ represent the current element. ; is the instruction seprator :
$serverlist | ForEach-Object {$serverboot= gwmi win32_operatingsystem -comp $_; $serverboot.Reboot()}