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

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.

Related

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

Powershell IIS Audit Scripting

I'm in the early stages of learning powershell, and I'm trying to put together a script that remotely gathers information from our IIS servers, but I'm encountering several issues.
The first one is that the IP Address and OU columns remain empty in the output file.
The second one is that I'm not able to format the Administrator group column to have 1 group per line, or delimited by commas.
This is the current version of the code:
$computers = Get-Content "C:\servers.txt"
#Running the invoke-command on remote machine to run the iisreset
$output = foreach ($computer in $computers)
{
Write-Host "Details from server $computer..."
try{
Invoke-command -ComputerName $computer -ErrorAction Stop -ScriptBlock{
# Ensure to import the WebAdministration and AD module
Import-Module WebAdministration
Import-Module ActiveDirectory
$webapps = Get-WebApplication
$list = #()
foreach ($webapp in get-childitem IIS:\AppPools\)
{
$name = "IIS:\AppPools\" + $webapp.name
$item = #{}
$item.server = $env:computername
$item.WebAppName = $webapp.name
$item.Version = (Get-ItemProperty $name managedRuntimeVersion).Value
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.UserIdentityType = $webapp.processModel.identityType
$item.Username = $webapp.processModel.userName
$item.Password = $webapp.processModel.password
$item.OU = (Get-ADComputer $_ | select DistinguishedNAme)
$item.IPAddress = (Get-NetIPAddress -AddressFamily IPv4)
$item.Administrators = (Get-LocalGroupMember -Group "Administrators")
$obj = New-Object PSObject -Property $item
$list += $obj
}
$list | select -Property "Server","WebAppName", "Version", "State", "UserIdentityType", "Username", "Password", "OU", "Ip Address", "Administrators"
}
} catch {
Add-Content .\failedservers.txt -Force -Value $computer
}
}
$output | Export-Csv -Path .\output.csv
#Stop-Transcript
I'd really appreciate any input on how to get it to work properly or improve on the code itself.
Thanks in advance!
For the OU property, you'll want to reference $env:COMPUTERNAME instead of $_:
$item.OU = (Get-ADComputer $env:COMPUTERNAME |Select -Expand DistinguishedName)
For the IPAddress and Administrators fields you'll want to use -join to create comma-separated lists of the relevant values:
$item.IPAddress = (Get-NetIPAddress -AddressFamily IPv4).IPAddress -join ','
$item.Administrators = (Get-LocalGroupMember -Group "Administrators").Name -join ','

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.

Powershell start-process script calls a second script - how to make one script only

I have a powershell script that accepts parameters in the form of "sender-ip=10.10.10.10" and that runs perfectly with elevated credentials
#script.ps1
$userID=$NULL
$line_array = #()
$multi_array = #()
[hashtable]$my_hash = #{}
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){
return "userId=" + $userId
}
elseif ($userID -eq $NULL)
{
$userId = "Unknown/UserID"
return "userId=" + $userId
}
Since this script will be invoked by a third party program that doesn't use elevated credentials, I had to create a second powershell script that includes the elevated privileges (which the third party program will invoke)
#elevated.ps1
[string]$abc = $args
<#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
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
[string]$output = start-process powershell -Credential $credentials -ArgumentList '-noexit','-File', 'C:\script\script.ps1', $abc
return $output
And I can manually invoke elevated.ps1 with
.\elevated.ps1 "sender-ip=10.10.10.10"
Instead of having two scripts, i.e. one script with the start-process calling the other script, how to make this in one single script? I believe this would simplify the parameter passing because the third party program has to call elevate.ps1 which calls script.ps1 and some error is happening somewhere.
Windows does not allow a process to elevate while running. There are some tricks but in one way or another they will spawn a new process with the elevated rights. See here for more info. So the easiest way for PowerShell is still using one script to Start-Process the other script elevated.
Contrary to my man Dilbert, I say this can be done. Just use the builtin "$myInvocation.MyCommand.Definition" which is the secret variable to get the full path of a running script. Write a loop statement to verify if running as Admin, then if not, start-process with the $myIvocation.MyCommand.Definition as an argument.
Plop this at the top of your script. If in UAC mode you will get a confirmation prompt. Add your elevated scripts at the end where the Write-Host starts.
$WID=[System.Security.Principal.WindowsIdentity]::GetCurrent();
$WIP=new-object System.Security.Principal.WindowsPrincipal($WID);
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator;
If ($WIP.IsInRole($adminRole)){
}else {
$newProcess = new-object System.Diagnostics.ProcessStartInfo 'PowerShell';
$newProcess.Arguments = $myInvocation.MyCommand.Definition
$newProcess.Verb = 'runas'
[System.Diagnostics.Process]::Start($newProcess);Write-Host 'Prompting for Elevation'
exit
}
Write-Host 'ElevatedCodeRunsHere';
Write-Host 'Press any key to continue...'
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
Here are some more start process examples

How to make script run remotelly on computers?

I have written a script that is to collect hardware and software information from a forrest/domain. I've read several posts about running a PS-script from a computer on a server, but I want to do the opposite.
How do you know that a script is "remotely accesible".
I've seen this command beeing used:
Invoke-Command -ComputerName {serverName} –ScriptBlock { commands }
Is there any other alternatives than computername? I'm thinking that this is not exclussive as several computers can have the same name..
This is my script:
try{
$ConfirmPreference="none"
$error.clear()
$erroractionpreference = "silentlycontinue"
#Gets the date of this day, used as name for XML-file later.
$a = get-date -uformat "%Y_%m_%d"
#Saves computername to compname variable(HELPER)
$compname = gc env:computername
#Gets the path to directory for all saved files and folders
$scriptpath = Split-Path -parent $myinvocation.MyCommand.Definition
#PC Serial Number, is used as name for directory containing XML files for this computer.
$serialnr = gwmi win32_bios | select -Expand serialnumber
#Creates a folder with the name of the computers hardware serialnumber if it does not exist.
if(!(Test-Path -path $scriptpath\$serialnr)) {
New-item -path $scriptpath -name $serialnr -type directory
}
#Username
$username = gc env:username
#System Info
gwmi -computer $compname Win32_ComputerSystem | ForEach {$siname = $_.Name; $simanufacturer = $_.Manufacturer; $simodel = $_.Model}
#Graphic card
$gpuname = gwmi win32_VideoController | select -Expand Name
#Processor Info
gwmi -computer $compname Win32_Processor | ForEach-Object {$cpuname = $_.Name; $cpumanufacturer = $_.Manufacturer; $cpucores = $_.NumberOfCores; $cpuaddresswidth = $_.AddressWidth}
#Memory
$totalmem = 0
$memsticks = gwmi -Class win32_physicalmemory
foreach ($stick in $memsticks) { $totalmem += $stick.capacity }
$totalmem = [String]$($totalmem / 1gb) + " GB"
#Drive
$totalspace = 0
$totalsize = gwmi -Class win32_logicaldisk
foreach($size in $totalsize) { $totalspace += $size.size }
$totalspace = "{0:N2}" -f ($totalspace/1Gb) + " GB"
#Install time for windows OS
$utctime = get-wmiobject win32_OperatingSystem | select-object -expandproperty installDate
$installtime = [System.Management.ManagementDateTimeConverter]::ToDateTime($utctime);
$installtime = Get-Date $installtime -uformat "%d/%m/%Y %X"
#--------#
#XML-form
#--------#
try{
$erroractionpreference = "stop"
$template = "<computer version='1.0'>
<hardware>
<serialnumber>$serialnr</serialnumber>
<systeminfo>
<name>$siname</name>
<manufacturer>$simanufacturer</manufacturer>
<model>$simodel</model>
</systeminfo>
<drive>
<size>$totalspace</size>
</drive>
<memory>
<size>$totalmem</size>
</memory>
<gpu>
<name>$gpuname</name>
</gpu>
<cpu>
<name>$cpuname</name>
<manufacturer>$cpumanufacturer</manufacturer>
<id>cpuid</id>
<numberofcores>$cpucores</numberofcores>
<addresswidth>$cpuaddresswidth</addresswidth>
</cpu>
</hardware>
<software>
<user>
<name>$username</name>
</user>
<osinfo>
<caption></caption>
<installdate>$installtime</installdate>
<servicepack></servicepack>
</osinfo>
</software>
</computer>"
$template | out-File -force $ScriptPath\$serialnr\$a.xml
$systemroot = [System.Environment]::SystemDirectory
$xml = New-Object xml
$xml.Load("$ScriptPath\$serialnr\$a.xml")
}catch{
}
#OSInfo, software
$newosinfo = (#($xml.computer.software.osinfo)[0])
Get-WmiObject -computer $compname Win32_OperatingSystem |
ForEach-Object {
$newosinfo = $newosinfo.clone()
[String] $bitversion = $_.osarchitecture
$newosinfo.caption = [String]$_.caption + "" + $_.osarchitecture
$newosinfo.servicepack = $_.csdversion
$xml.computer.software.AppendChild($newosinfo) > $null
}
$xml.computer.software.osinfo | where-object {$_.caption -eq ""} | foreach-object {$xml.computer.software.RemoveChild($_)}
#-------Save and get content--------
$xml.Save("$scriptpath\$serialnr\$a.xml")
#$new = Get-Content $scriptpath\$serialnr\$a.xml
#-----------------------------------
if(!$?){
"An error has occured"
}
}catch{
[system.exception]
"Error in script: system exception"
}finally{
}
For the -ComputerName parameter, you can use NETBIOS name, IP address, or fully-qualified domain name. For more details, see Invoke-Command on TechNet.
Seems like your script is "only" saving the data on the machine it is running, you will probably want it to return something in order to be useful with Invoke-Command.