foreach powershell i'm totally blind - powershell

I have issues with this PowerShell script, if i execute the line without the foreach works great but with him don't show up nothing, can someone tell me why?
The foreach works fantastic by himselft he read all the data from the CSV but for some reason don't work, the CSV contain PC names like PC1, Pc-RRHH, JosePc from my network, like i say without the foreach is fine.
$computers = Import-Csv “C:\PowerShell\Pc.csv”
$array = #()
foreach($pc in $computers)
{
Get-WmiObject -Namespace ROOT\CIMV2 -Class Win32_Product -Computer $pc.computername
Select-Object Name, Version, PSComputerName
Where-Object -FilterScript {$_.Name -like “Adobe*”}
}
Best regards

Assuming your CSV file indeed has a header with column 'computername' in it, you can change your code to:
$computers = Import-Csv "C:\PowerShell\Pc.csv"
# let PowerShell collect the data for you in an array
$array = foreach($pc in $computers) {
# because NameSpace 'root/CIMV2' is the default, you do not have to specify that
Get-CimInstance -ClassName Win32_Product -ComputerName $pc.computername |
# or use the old Get-WmiObject
# Get-WmiObject -Class Win32_Product -Computer $pc.computername |
Where-Object { $_.Name -like "Adobe*" } |
Select-Object Name, Version, PSComputerName
}
Instead of piping to a Where-Object {..} clause, you can also use the -Filter parameter.
Beware though that this filter requires WQL syntax, which is different from PowerShell syntax.
$computers = Import-Csv "C:\PowerShell\Pc.csv"
# let PowerShell collect the data for you in an array
$array = foreach($pc in $computers) {
# because NameSpace 'root/CIMV2' is the default, you do not have to specify that
Get-CimInstance -ClassName Win32_Product -ComputerName $pc.computername -Filter "Name like 'Adobe%'" |
Select-Object Name, Version, PSComputerName
}
Or use the -Query parameter:
$computers = Import-Csv "C:\PowerShell\Pc.csv"
# the query string to filter on. Also WQL syntax
$query = "Select * from Win32_Product where Name LIKE 'Adobe%'"
# let PowerShell collect the data for you in an array
$array = foreach($pc in $computers) {
Get-CimInstance Get-CimInstance -Query $query -ComputerName $pc.computername |
Select-Object Name, Version, PSComputerName
}
From your comment, I gather that your CSV file isn't a CSV at all, but just a text file with pc names each on a separate line and that there is not header 'computername'.
In that case, change $computers = Import-Csv "C:\PowerShell\Pc.csv" to $computers = Get-Content -Path "C:\PowerShell\Pc.csv" and in the loop use -ComputerName $pc instead if -ComputerName $pc.computername

Related

Query the NetAdapter on Multiple Machines

#Listing machine from which we will Query
$Machines = Get-ADComputer -Filter * -SearchBase 'OU=Laptops,OU=Win10Modern,OU=LN,OU=Workstations,DC=cooley,DC=com' | Select-Object Name
#Getting the Network Adapter version for Wi-Fi Adapter
ForEach ($Machine in $Machines) {
Get-NetAdapter | Select-Object Name,InterfaceDescription,DriverVersion,DriverDate,DriverProvider
}
Currently, your code loops over objects in variable $Machines, where each object has a single property called Name.
In order to get just the name values, either use Select-Object -ExpandProperty Name or get the array of names like this:
# get an array of computernames
$Machines = (Get-ADComputer -Filter * -SearchBase 'OU=Laptops,OU=Win10Modern,OU=LN,OU=Workstations,DC=cooley,DC=com').Name
Next loop over these computernames and have each computer run the Get-NetAdapter cmdlet:
# capture the output(s) in variable $result
$result = foreach ($Machine in $Machines) {
if (Test-Connection -ComputerName $Machine -Count 1 -Quiet) {
Invoke-Command -ComputerName $Machine -ScriptBlock {
Get-NetAdapter | Select-Object SystemName,Name,InterfaceDescription,
DriverVersion,DriverDate,DriverProvider,Status,AdminStatus
}
}
else {
Write-Warning "Computer '$Machine' does not respond"
}
}
# output on screen
$result
# or to GridView
$result | Out-GridView -Title 'NetAdapterInfo'
# or to CSV file
$result | Export-Csv -Path 'X:\NetAdapterInfo.csv' -NoTypeInformation
AdminStatus is a setting (enabled --> 'up'; disabled --> 'down')
Status is operational status (connected --> 'up'; disconnected --> 'down')
I don't think you can use Get-NetAdapter to connect to remote computers.
You can however use Get-WmiObject Win32_NetworkAdapter -ComputerName .
Like this:
ForEach ($Machine in $Machines) {
Get-WmiObject -Class Win32_NetworkAdapter -Filter "NetConnectionStatus = 2" -ComputerName $Machine
}
You need to become familiar with the properties of the Win32_NetworkAdapter class. You can see all of the properties by running this command:
Get-WmiObject -Class Win32_NetworkAdapter -ComputerName "Localhost" | fl * -Force
or you can use this command to see all of the properties (and methods) available to you.
Get-WmiObject -Class Win32_NetworkAdapter -ComputerName "Localhost" | Get-Member
Most computers will have more than 1 network card (some are hidden) and you have to filter the irrelevant ones out.

Data type issue when exporting BIOS settings to CSV file

I've run into an issue with exporting a string to a CSV file. My script is remotely getting BIOS settings from a Lenovo laptop using WMI queries and PowerShell. And I'm exporting the result to a CSV file. All the settings are exporting great, but "AvailableSettings" (BIOS setting options) seem to run into a type mismatch issue.
The output file looks like this:
CurrentSetting,"Status","AvailableSettings"
WakeOnLAN,"ACOnly","System.String[]"
EthernetLANOptionROM,"Enable","System.String[]"
The code:
$Computers = Get-Content -Path C:\temp\ComputerList.txt
foreach ($Computer in $Computers) {
$Computer = $Computer -replace "`t|`n|`r",""
$Get_manufacturer = (Get-WmiObject -ComputerName $Computer Win32_Computersystem).Manufacturer
if ($Get_manufacturer -like "*lenovo*") {
$manufacturer = "Lenovo"
$selections = Get-WmiObject -ComputerName $Computer -Class Lenovo_GetBiosSelections -Namespace root\wmi
$resultsLenovo = Get-WmiObject -ComputerName $Computer -Class Lenovo_BiosSetting -Namespace root\wmi | Where-Object CurrentSetting | ForEach-Object {
$parts = $_.CurrentSetting.Split(',')
[PSCustomObject]#{
CurrentSetting = $parts[0]
Status = $parts[1]
AvailableSettings = $selections.GetBiosSelections($parts[0]).Selections.Split(',')
}
}
$resultsLenovo | Export-Csv -Path "C:\temp\$Computer-BIOS-settings.csv" -NoTypeInformation -Delimiter ',' -Encoding ASCII
}
Clear-Variable -Name manufacturer
}
There are more IFs for other manufacturers as well, but I haven't included them in this code snippet here.
When outputting the result to Out-GridView, it seems to be working just fine.
The result should be like this:
CurrentSetting,"Status","AvailableSettings"
WakeOnLAN,"ACOnly","Disable, ACOnly, ACandBattery, Enable"
EthernetLANOptionROM,"Enable","Disable, Enable"
Any ideas where do I messed up and how to sort the types out?

Use WMI to convert a remote SID to username

I am using Invoke-WMIMethod to identify all SIDS beginning with S-1-5-21, like so (thanks to Mathias R. Jessen):
$Keys = Invoke-WmiMethod -Path $ClassPath -Name EnumKey -ArgumentList 2147483651,''
| Select-Object -ExpandProperty sNames | Where-Object {$_ -match 'S-1-5-21-[\d\-]+$'}
I want to convert these SIDs from the remote system to usernames on the remote system using WMI. Is this possible through WMI or Invoke-WmiMethod?
You can use the Win32_SID class to obtain the account name:
foreach($Key in $Keys)
{
$SID = [wmi]"\\$RemoteComputer\root\cimv2:Win32_SID.SID=$Key"
New-Object psobject -Property #{
SID = $Key
Username = $SID.ReferencedDomainName,$SID.AccountName -join '\'
}
}
Rather than grabbing from the registry you could get the same information from the Win32_UserProfile provider. Then if folder name is good enough, consider something like this:
$Computer = "ExampleComputer"
Get-WMIObject Win32_UserProfile -Filter "SID like 'S-1-5-21-*'" -ComputerName $Computer |
select SID,#{name=LocalPath;Expression={Split-Path -leaf $_.LocalPath}}
Otherwise Win32_UserAccount exists but can be really slow with a large domain.
$Computer = "ExampleComputer"
$SIDs = Get-WMIObject Win32_UserProfile -Filter "SID like 'S-1-5-21-*'" -ComputerName $Computer | select -ExpandProperty SID
$UserAccounts = Get-WMIObject Win32_UserAccount -ComputerName $Computer
foreach ($SID in $SIDs) {
foreach ($Account in $UserAccounts) {
If ($SID -eq $Account.SID) {
$Account
}
}
}

Trying to capture IP from powershell script, getting System.String[] instead

I'm trying to pull a machine's IPAddress, MACAddress, and DefaultIPGateway information from the Win32_NetworkAdapterConfiguration object into an exported CSV file named NetworkAdapterConfiguration.csv using this script:
$StrComputer = $env:computername
$NetAdConfig = gwmi Win32_NetworkAdapterConfiguration -Comp $StrComputer
$NetAdConfig | Select-Object IPAddress,MACAddress,DefaultIPGateway | Export-Csv -Path C:\CSVFolder\NetworkAdapterConfiguration.csv -Encoding ascii -NoTypeInformation
When I view this CSV I get "System.String[]" where the IP and DefaultIPGateway values should be displayed. I'm assuming this information gets represented as an array and that is why I'm seeing the System.String[] view, but I have little experience with Powershell. Any help, advice, and references are much appreciated.
The IPAddress and DefaultIPGateway properties are arrays. If you are sure your machines only have one IP address and default gateway, you can do this:
$computer = $ENV:COMPUTERNAME
get-wmiobject Win32_NetworkAdapterConfiguration -filter "IPEnabled=TRUE" -computername $computer | foreach-object {
new-object PSObject -property #{
"Computer" = $computer
"MACAddress" = $_.MACAddress
"IPAddress" = $_.IPAddress[0]
"DefaultIPGateway" = $_.DefaultIPGateway[0]
} | select-object Computer,MACAddress,IPAddress,DefaultIPGateway
}
Here's another way that uses Select-Object:
$computer = $ENV:COMPUTERNAME
get-wmiobject Win32_NetworkAdapterConfiguration -filter "IPEnabled=TRUE" -computername $computer | foreach-object {
$_ | select-object `
#{Name="ComputerName"; Expression={$_.__SERVER}},
#{Name="MACAddress"; Expression={$_.MACAddress}},
#{Name="IPAddress"; Expression={$_.IPAddress[0]}},
#{Name="DefaultIPGateway"; Expression={$_.DefaultIPGateway[0]}}
}
I have a function that I wrote called Convert-OutputForCSV that can help to remove the string[] issues you are seeing as well. You could do something like this to expand out the arrays into a more readable property.
$StrComputer = $env:computername
$NetAdConfig = gwmi Win32_NetworkAdapterConfiguration -Comp $StrComputer
$NetAdConfig | Select-Object IPAddress,MACAddress,DefaultIPGateway |
Convert-OutputForCSV |
Export-Csv -Path C:\CSVFolder\NetworkAdapterConfiguration.csv -Encoding ascii -NoTypeInformation

PowerShell - Select-Object from Win32_OperatingSystem displays rather oddly

First time poster here, I'm a bit of a beginner and I've been keen to get my PowerShell scripting skills up to scratch and I'm come across something rather confusing...
I've made a script to query a collection of computers and I want to query Win32_OperatingSystem but only extrapolate the Build number so I can populate my PSObject with it. I'm trying to add some If logic so that if the build number is 7601, I can write a message under my OS column.
The problem I'm having is that the BuildNumber values are coming out as #{BuildNumber=7601} instead of 7601 for instance. That, and my If statement is borked.
$Machines = Get-Content .\Computers.txt
Foreach($Machine in $Machines)
{
$sweet = (Get-WmiObject -Class Win32_OperatingSystem -computer $Machine | Select-Object BuildNumber)
$dversion = if ($sweet -eq "#{BuildNumber=7601}") {Yes!} else {"Nooooo!"}
New-Object PSObject -Property #{
ComputerName = $Machine
Sweet = $sweet
OS = $dversion
}
}
The issue is that the Get-WMIObject cmdlet is returning a Hash Table. Then the Select-Object is returning just the BuildNumber section you want, the BuildNumber property and it's value. You need to add the -ExpandProperty parameter to only get the value back, not the name/value pair.
Get-WMIObject -Class Win32_OperatingSystem | Select-Object BuildNumber
Returns
#{BuildNumber=7601}
With ExpandProperty
Get-WMIObject -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber
Returns
7601
Just another option with a ping test to skip unavailable machines.
Get-Content .\Computers.txt | Where-Object {Test-Connection -ComputerName $_ -Count 1 -Quiet} | Foreach-Object {
$sweet = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $_ | Select-Object -ExpandProperty BuildNumber
New-Object PSObject -Property #{
ComputerName = $_.__SERVER
Sweet = $sweet
OS = if ($sweet -eq 7601) {'Yes!'} else {'Nooooo!'}
}
}