Rewriting a Powershell line for another script - powershell

There is this existing PS snippet that works as intended:
$creds = New-Object -TypeName System.Management.Automation.PSCredential ("USERID", (new-object System.Security.SecureString));
$FullVM | Where-Object {$_.runtime.powerState -eq "PoweredOn"} |
Select-Object -Property Name,#{N="GuestId";E={$_.Guest.GuestId}},
#{N="Installed Guest OS";E={$_.Guest.GuestFullName}},
#{N="Configured Guest OS";E={$_.Config.GuestFullName}},
#{N="ACCESS";E={$CurrentSession=New-SSHSession -ComputerName $_.Name -AcceptKey -keyfile C:\temp\key.txt -Credential $creds ;(Invoke-SSHCommand -SSHSession $CurrentSession -Command "echo YES" -OutVariable result).output}}
Basically, from what I understand, it collects data and saves them to variables 'or objects?'.
For the last line, it tries to SSH to remote machine(defined in $_.Name) and echoes "YES" if successful and it gets saved to the 'object' "ACCESS":
#{N="ACCESS";E={$CurrentSession=New-SSHSession -ComputerName $_.Name -AcceptKey Credential $creds ;(Invoke-SSHCommand -SSHSession $CurrentSession -Command "echo YES" -OutVariable result).output}}
The issue that I'm running into right now is trying to figure out how to inject/attach/rewrite that same line into this:
foreach ($vmguest in $FullVM) {
$vmguest.Config.Hardware.Device | Where-Object {$vmguest.Guest.GuestFullName -cnotlike "*Microsoft*" -and $_.GetType().Name -match $unwantedHardware} | Foreach-Object {
New-Object -TypeName PSObject -Property #{
Name = $vmguest.name
Label = $_.DeviceInfo.Label
OS = $vmguest.Guest.GuestFullName
}
}
}
How do I rewrite this so it would still provide the same function as from the previous snippet? Do I write it like this?
foreach ($vmguest in $FullVM) {
$vmguest.Config.Hardware.Device | Where-Object {$vmguest.Guest.GuestFullName -cnotlike "*Microsoft*" -and $_.GetType().Name -match $unwantedHardware} | Foreach-Object {
New-Object -TypeName PSObject -Property #{
Name = $vmguest.name
Label = $_.DeviceInfo.Label
OS = $vmguest.Guest.GuestFullName
#{N="ACCESS";E={$CurrentSession=New-SSHSession -ComputerName $_.Name -AcceptKey Credential $creds ;(Invoke-SSHCommand -SSHSession $CurrentSession -Command "echo YES" -OutVariable result).output}}
}
}
}
Could you please guide me on how to accomplish this? Thank you very much in advance!

Related

Detect SMB1 version via powershell for all OSes

My workflow:
check if server is pingable
find if they are domain connected or not and perform a task accordingly. if Operating system 2012 and/or R2 ,2016 or 2019 newer OSes then I will run Get-SmbServerConfiguration cmdlet. if machine is not a part of default domain then else block will run.
if Operating system 2003 or 2008 oldest OSes then I will run Get-Wmi cmdlet. if machine is not a part of default domain then else block will run.
Finally , I will concentanate $results variable.
My question is :
1- How can we get remotely regedit value for 2003 or 2008 oldest OSes IS NOT a part of default domain insie else block?
Also , Condition will be like below.
if SMB1 value is "0" then result will be `false`
if SMB1 value is "1" then result will be `true`
if SMB1 value is not exist then result will be `not exist value`
2- How can I create object properties $SMBAudit variable ? because , I will concentanate all outputs inside $results variable.
$reg = [wmiclass]"\\$computer\root\default:StdRegProv"
$SMBAudit = $reg.GetStringValue($basekey, $subkey, $value).sValue
My desired output :
Computername,SMB1Enabled
Host01,True
Host02,False
I will write so far a script like below. but I am stucking somethings.
Script :
# Computer List
$allComputers = Get-Content .\path\to\computers.txt
read-host -assecurestring | convertfrom-securestring | out-file C:\mysecurestring_domain.txt
read-host -assecurestring | convertfrom-securestring | out-file C:\mysecurestring_local.txt
# Create empty array of results
$Results = #()
# Loop through computers
foreach($computer in $allComputers) {
# check if server is pingable before running the query on the server
if (Test-Connection $computer -Count 1 -Quiet) {
Write-Host "`n`n$computer is online!" -BackgroundColor Green -ForegroundColor Black
}
if(Get-ADComputer -Filter {Name -eq $computer -and OperatingSystem -notlike '*Windows*Server*2003*' -and OperatingSystem -notlike '*Windows*Server*2008*'})
{
#"machine $_ is a part of default domain"
# The command we want to run
$username = "domain01\admin01"
$password = Get-Content 'C:\mysecurestring_domain.txt' | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$SMB = Invoke-Command -ComputerName $computer -Credential $cred -ScriptBlock {Get-SmbServerConfiguration | Select EnableSMB1Protocol }
# Create properties
$Properties = #{
# Populate the properties "Computername" and "SMB1Enabled" with variables
Computername = $Computer
SMB1Enabled = $SMB.EnableSMB1Protocol
}
# Add the properties to the result for each object
$Results += New-Object psobject -Property $Properties
}
else
{
#"machine $_ IS NOT a part of default domain"
$username = "localadmin01"
$password = Get-Content 'C:\mysecurestring_local.txt' | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$SMB = Invoke-Command -ComputerName $computer -Credential $cred -ScriptBlock {Get-SmbServerConfiguration | Select EnableSMB1Protocol }
# Create properties
$Properties = #{
# Populate the properties "Computername" and "SMB1Enabled" with variables
Computername = $Computer
SMB1Enabled = $SMB.EnableSMB1Protocol
}
# Add the properties to the result for each object
$Results += New-Object psobject -Property $Properties
}
# Oldest OSes
if(Get-ADComputer -Filter {Name -eq $computer -and OperatingSystem -notlike '*Windows*Server*2012*' -and OperatingSystem -notlike '*Windows*Server*2016*' -and OperatingSystem -notlike '*Windows*Server*2019*'})
{
#"machine $_ is a part of default domain"
# The command we want to run
<# HKEY_CLASSES_ROOT (2147483648 (0x80000000))
HKEY_CURRENT_USER (2147483649 (0x80000001))
HKEY_LOCAL_MACHINE (2147483650 (0x80000002))
HKEY_USERS (2147483651 (0x80000003))
HKEY_CURRENT_CONFIG (2147483653 (0x80000005))
#>
$basekey = [uint32]'0x80000002'
$subkey = 'SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters'
$value = 'SMB1'
$reg = [wmiclass]"\\$computer\root\default:StdRegProv"
$SMBAudit = $reg.GetStringValue($basekey, $subkey, $value).sValue
}
else
{
#"machine $_ IS NOT a part of default domain"
}
# Output
$Results | Select-Object Computername, SMB1Enabled | Out-File -Filepath c:\temp\smb1-computers.txt
I think you are over complicating this and although not tested by me, you could try this:
# Computer List
$allComputers = Get-Content '.\path\to\computers.txt'
# get credentials for domain-joined machines and for local machines
$domainCred = Get-Credential -UserName "domain01\admin01" -Message "Please enter the DOMAIN password"
$localCred = Get-Credential -UserName "localadmin01" -Message "Please enter the LOCAL password"
# loop through the list of computers and collect output in variable $Results
$Results = foreach($computer in $allComputers) {
# check if server is pingable before running the query on the server
if (Test-Connection -ComputerName $computer -Count 1 -Quiet) {
Write-Host "$computer is online!" -BackgroundColor Green -ForegroundColor Black
$server = Get-ADComputer -Filter "Name -eq '$computer'" -Properties OperatingSystem -ErrorAction SilentlyContinue
# if domain joined, use $domainCred, otherwise $localCred
if ($server) {
$cred = $domainCred
$version = ([regex]'Windows Server (\d+)').Match($server.OperatingSystem).Groups[1].Value
}
else {
$cred = $localCred
$info = Get-WmiObject -ComputerName $computer -Credential $cred -Class Win32_OperatingSystem
$version = ([regex]'Windows Server (\d+)').Match($info.Caption).Groups[1].Value
}
if ($version -eq '2003') {
# try reading the registry
try {
$RegBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Computer)
$RegKey = $RegBase.OpenSubKey("SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters")
$SMB = $RegKey.GetValue("SMB1")
[PsCustomObject]#{ ComputerName = $computer; SMB1Enabled = ($null -eq $SMB -or [int]$SMB -eq 1) }
}
catch {
[PsCustomObject]#{ ComputerName = $computer; SMB1Enabled = 'Could not read Remote Registry' }
}
finally {
if ($RegBase) { $RegBase.Close() }
if ($RegKey) { $RegKey.Close() }
}
}
elseif ($version -eq '2008') {
# Older OS
try {
# try via WinRM
$SMB = Invoke-Command -ComputerName $computer -Credential $cred -ScriptBlock {
Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters' -Name SMB1
} -ErrorAction Stop
# output an object
[PsCustomObject]#{ ComputerName = $computer; SMB1Enabled = ($null -eq $SMB -or [int]$SMB -eq 1) }
}
catch {
# try reading the registry
try {
$RegBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Computer)
$RegKey = $RegBase.OpenSubKey("SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters")
$SMB = $RegKey.GetValue("SMB1")
[PsCustomObject]#{ ComputerName = $computer; SMB1Enabled = ($null -eq $SMB -or [int]$SMB -eq 1) }
}
catch {
[PsCustomObject]#{ ComputerName = $computer; SMB1Enabled = 'Could not read Remote Registry' }
}
finally {
if ($RegBase) { $RegBase.Close() }
if ($RegKey) { $RegKey.Close() }
}
}
}
else {
# Newer OS
$SMB = Invoke-Command -ComputerName $computer -Credential $cred -ScriptBlock { Get-SmbServerConfiguration | Select-Object EnableSMB1Protocol }
# output an object
[PsCustomObject]#{ ComputerName = $computer; SMB1Enabled = $SMB.EnableSMB1Protocol }
}
}
else {
Write-Warning "Computer $computer is off-line"
# output an object anyway, so that in the CSV it is known that the computer didn't ping
[PsCustomObject]#{ ComputerName = $computer; SMB1Enabled = 'Off-Line' }
}
}
# Output on screen
$Results | Format-Table -AutoSize
# Output to CSV file
$Results | Export-Csv -Path 'c:\temp\smb1-computers.csv' -NoTypeInformation -UseCulture

PowerShell create a new object and add the values to an array

What I am trying to achieve here is add the servers and the updates that are not installed on the server to an array and create a new object that is going to display the names of the servers in one column and the missing updates on another column, but at the end I am getting an empty Grid-View table.
The values for the servers and updates are read from a file.
Write-Host
#Read the password from stdin and store it in a variable
$password = Read-Host -AsSecureString -Prompt "Enter your password"
Write-Host
#Get credentials and password for later user
$cred = New-Object System.Management.Automation.PSCredential ("Administrator#testing.local", $password )
#Get the list of available servers to test
$servers = Get-Content -Path $HOME\Desktop\servers.txt
#Get the list of available updates that need to be installed on the server
$available_updates = Get-Content $HOME\Desktop\update.txt
$add_updates = #()
$add_updates_and_servers = #()
#Get each server name from the list and execute the following commands
foreach ($server in $servers) {
#Test if the server is reponding
$ping = Test-Connection $server -Count 1 -Quiet
#If the above command returns True continue
if ($ping -eq "True") {
#Write a message saying Testing server_name
Write-Host "Testing $server"
foreach ($update in $available_updates) {
#Check if update is installed
$updates_from_os = Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock { Get-HotFix | Select-Object -Property HotFixID | Where-Object -Property HotFixID -EQ $Using:update } -HideComputerName | Select-Object -ExpandProperty HotFixID
if (!$updates_from_os) {
$add_updates += $update
}
}
New-Object -TypeName PSObject -Property $updates -OutVariable final
$updates = #{
"Server" = $server
"Updates" = $add_updates
}
}
$add_updates_and_servers += $final
}
$add_updates_and_servers | Out-GridView
For what is probably happening with your script:
I suspect that each time you calling the statement New-Object -TypeName PSObject -Property $updates -OutVariable final You overwriting any previous created $final object which references to the same objects as your $add_updates_and_servers collection.
Anyways, try to avoid using the increase assignment operator (+=) to create a collection, instead stream the results to a variable (or even better, directly to next/final cmdlet: ... }| Out-GridView).
Something like:
$add_updates_and_servers = foreach ($server in $servers) {
$ping = Test-Connection $server -Count 1 -Quiet
if ($ping -eq "True") {
Write-Host "Testing $server"
$add_updates = #(
foreach ($update in $available_updates) {
$updates_from_os = Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock { Get-HotFix | Select-Object -Property HotFixID | Where-Object -Property HotFixID -EQ $Using:update } -HideComputerName | Select-Object -ExpandProperty HotFixID
if (!$updates_from_os) { $update }
}
)
[PSCustomObject]#{
"Server" = $server
"Updates" = $add_updates
}
}
}
Note: in case you want each $update in a separate column, also have a look at: Not all properties displayed

How to output from a Powershell hashtable to a output file

I am trying to get the .NetFramwork version from all the windows servers. I am using powershell script. I can get the output displayed but unable to get the output from the hashtable to a output file. Also how would I get rid of the "..." from VersionDetails : {1.0.3705, 1.1.4322, 2.0.50727, 3.0...} and show the full content.
Any help will be greatly appreciated
here is the code I am using:
$username = "username"
$password = "Password"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$query = "select name from win32_directory where name like 'c:\\windows\\microsoft.net\\framework\\v%'"
$ComputerNames = Get-Content "d:\Scripts\serverList.txt"
foreach ($ComputerName in $ComputerNames)
{
write-host "ComputerName = $ComputerName"
$ComputerName | ForEach-Object {
$res = Get-WmiObject -query $query -Credential $cred -ComputerName $ComputerName | ForEach-Object {
Split-Path $_.name -Leaf } | # returns directories
Where-Object { $_ -like 'v*' } | # only include those that start with v
ForEach-Object { [system.version]( $_ -replace "^v" ) }
# remove "v" from the string and convert to version object
# Create hashtable with computername and version details
$prop = #{
ComputerName = $ComputerName
#V1_Present = &{ if ( $res | Where-Object { $_.Major -eq 1 -and $_.Minor -eq 0 } ) { $true } }
#V1_1Present = &{ if ( $res | Where-Object { $_.Major -eq 1 -and $_.Minor -eq 1 } ) { $true } }
V2_Present = &{ if ( $res | Where-Object { $_.Major -eq 2 -and $_.Minor -eq 0 } ) { $true } }
V3_Present = &{ if ( $res | Where-Object { $_.Major -eq 3 -and $_.Minor -eq 0 } ) { $true } }
V3_5Present = &{ if ( $res | Where-Object { $_.Major -eq 3 -and $_.Minor -eq 5 } ) { $true } }
V4_Present = &{ if ( $res | Where-Object { $_.Major -eq 4 -and $_.Minor -eq 0 } ) { $true } }
VersionDetails = $res
}
# Create and output PSobject using hashtable
New-Object PSObject -Property $prop
}
=========================================================
Output dispalys
PS D:\Scripts> .\GetDotNetFrameworkver.ps1
in for loop ComputerName = XXXXXXX
V4_Present : True
V3_5Present : True
V2_Present : True
V3_Present : True
ComputerName : XXXXX
VersionDetails : {1.0.3705, 1.1.4322, 2.0.50727, 3.0...}
Based on the answer of link there is a "simpler" (and faster) solution to fetch the versions.
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | Get-ItemProperty -name Version,Release -ErrorAction Ignore | Where { $_.PSChildName -match '^(?!S)\p{L}'} | Select PSChildName, Version, Release
If you want to get the versions of different remote machines you can use PowerShell remoting. Be aware that you've to enable PS remoting .If your OS version is WIN10/WIN2012R2 it is enabled per default. If you're using an older OS you've to call Enable-PSRemoting on the remote machine. See this link for details.
Example:
$result = Invoke-Command -ComputerName computer1.domain, computer1.domain -Credential (Get-Credential ) -ScriptBlock {
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | Get-ItemProperty -name Version,Release -ErrorAction Ignore | Where { $_.PSChildName -match '^(?!S)\p{L}'} | Select PSChildName, Version, Release
}
$hash = $result | group PSComputerName -AsHashTable # Group the .Net versions by computername
$hash.'computer1.domain' # Print all .Net version of computer1
$hash.'computer1.domain'.Version # Only print the version
Hope that helps.

Remote Registry Query Powershell

I am trying to make a powershell script that gets computer names from a txt file, checks the registry to see what the current version of Flash is installed, and if it is less than 18.0.0.203, run an uninstall exe. Here is what I have been trying:
# Retrieve computer names
$Computers = Get-Content C:\Users\araff\Desktop\FlashUpdater\Servers.txt
# Select only the name from the output
#$Computers = $Computers | Select-Object -ExpandProperty Name
#Sets command to execute if the version is not 18.0.0.203
$command = #'
cmd.exe /C uninstall_flash_player.exe -uninstall
'#
#Iterate through each computer and execute the command if the version is not 18.0.0.203
[Array]$Collection = foreach ($Computer in $Computers){
$AD = Get-ADComputer $computer -Properties LastLogonDate
$ping = Test-Connection -quiet -computername $computer -Count 2
$datetime = Get-Date
$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)
$RegKey= $Reg.OpenSubKey("SOFTWARE\Macromedia\FlashPlayerActiveX")
$version = $RegKey.GetValue("Version")
if ($version -eq '= 18.0.0.203') {
$installed = "Flash is up to date!"
}
Else {
$installed = "Removing old version..."
Invoke-Expression -Command:$command
}
New-Object -TypeName PSObject -Property #{
TimeStamp = $datetime
ComputerName = $computer
Installed = $installed
OnlineStatus = $ping
LastLogonDate = $AD.LastLogonDate
} | Select-Object TimeStamp, ComputerName, Installed, OnlineStatus, LastLogonDate
}
#Exports csv
$Collection | Export-Csv FlashUpdaterOutput.csv -NoTypeInformation
It exports the CSV just fine, but all the installed columns say "Removing" even if it is the current version. Any ideas on what I am doing wrong? Thanks!
Rather than opening a remote registry key and running cmd /c why not make a [scriptblock] and pipe it to Invoke-Command.
AsJob it and come back for the results later.
[scriptblock]$code = {
$uninst = gci "C:\Windows\System32\Macromed\Flash" -Filter "*.exe" | ?{ $_.Name -ne "FlashUtil64_18_0_0_204_ActiveX.exe" -and $_.Name -like "FlashUtil64_18_0_0_*_ActiveX.exe" }
foreach($flash in $uninst) {
Write-Host $flash.FullName
$proc = New-Object System.Diagnostics.Process
$proc.StartInfo.FileName = $flash.FullName
$proc.StartInfo.Arguments = "-uninstall"
$proc.Start()
$proc.WaitForExit()
Write-Host ("Uninstalling {0} from {1}" -f $flash.BaseName,$env:COMPUTERNAME)
}
}
Invoke-Command -ScriptBlock $code -ComputerName frmxncsge01 -AsJob
Then later just come back and Get-Job | Receive-Job -Keep and see the results.

How to troubleshoot "Get-WmiObject : Access is denied."?

I have two working powershell scripts. You would invoke script1.ps1 with:
.\script1.ps1 "sender-ip=10.10.10.10"
And the script is supposed to return userId=DOMAIN/UserId. The first script:
#script1.ps1
$abc = $args
$startInfo = $NULL
$process = $NULL
$standardOut = $NULL
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = "C:\script\script2.ps1 " + $abc
$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
$startInfo.Username = "Username"
$startInfo.Domain = "DOMAIN"
$startInfo.Password = $password
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$standardOut = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
# $standardOut should contain the results of "C:\script\script1.ps1"
$standardOut
And this is the entire working script2.ps1
#script2.ps1
$line_array = #()
$multi_array = #()
[hashtable]$my_hash = #{}
$Sender_IP = $NULL
$Win32OS = $NULL
$Build = $NULL
$LastUser = $NULL
$UserSID = $NULL
$userID=$NULL
$output = $NULL
foreach ($i in $args){
$line_array+= $i.split(" ")
}
foreach ($j in $line_array){
$multi_array += ,#($j.split("="))
}
foreach ($k in $multi_array){
$my_hash.add($k[0],$k[1])
}
$Sender_IP = $my_hash.Get_Item("sender-ip")
<#Gather information on the computer corresponding to $Sender_IP#>
$Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Sender_IP
<#Determine the build number#>
$Build = $Win32OS.BuildNumber
<#Running Windows Vista with SP1 and later, i.e. $Build is greater than or equal to 6001#>
if($Build -ge 6001){
$Win32User = Get-WmiObject -Class Win32_UserProfile -ComputerName $Sender_IP
$Win32User = $Win32User | Sort-Object -Property LastUseTime -Descending
$LastUser = $Win32User | Select-Object -First 1
$UserSID = New-Object System.Security.Principal.SecurityIdentifier($LastUser.SID)
$userId = $UserSID.Translate([System.Security.Principal.NTAccount])
$userId = $userId.Value
}
<#Running Windows Vista without SP1 and earlier, i.e $Build is less than or equal to 6000#>
elseif ($Build -le 6000){
$SysDrv = $Win32OS.SystemDrive
$SysDrv = $SysDrv.Replace(":","$")
$ProfDrv = "\\" + $Sender_IP + "\" + $SysDrv
$ProfLoc = Join-Path -Path $ProfDrv -ChildPath "Documents and Settings"
$Profiles = Get-ChildItem -Path $ProfLoc
$LastProf = $Profiles | ForEach-Object -Process {$_.GetFiles("ntuser.dat.LOG")}
$LastProf = $LastProf | Sort-Object -Property LastWriteTime -Descending | Select-Object -First 1
$userId = $LastProf.DirectoryName.Replace("$ProfLoc","").Trim("\").ToUpper()
}
else{
$userId = "Unknown/UserID"
}
if ($userId -ne $NULL){
$output = "userId=" + $userId
}
elseif ($userID -eq $NULL)
{
$userId = "Unknown/UserID"
$output = "userId=" + $userId
}
$output.replace("\","/")
Here is my problem. On most IP addresses in our domain, it returns:
Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005
(E_ACCESS DENIED))
I researched this, and
"get-wmiobject win32_process -computername" gets error "Access denied , code 0x80070005" recommends giving the elevated account permission to run WMI throughout the Domain.
And this article, http://technet.microsoft.com/en-us/library/cc787533(v=ws.10).aspx explains how to do it.
But convincing the team that is in charge of the domain to grant WMI permissions to this elevated account will be a stretch. And, the script is able to return the UserId for some of the IP addresses in the domain.
Is there another way to resolve this? What should I research on google?
Have you considered using Invoke-Command and executing your script2 remotely using PowerShell Remoting?
Your remote script can the be executed using alternative credentials, you may have better luck convincing your security team to enable PowerShell Remoting rather than WMI. Your wmi queries when run via invoke-command will be local to the machine so will have a better chance of working, it also avoids the need to read the standard-out buffer.
To get you started, try Enter-PSSession as this will enable you to quickly determine how much work is necessary to get PS Remoting working in your environment.
In the future you might want to target many computers simultaneously, in which case PS Remoting and Start-Job would be helpful.