PowerShell | Get Storage from Servers with "Get-ADComputer" - windows

i have an problem with my script, plz help :3
This script is supposed to get all Server Hostnames from our Server OU. And than get the Used and Free Space of the Servers But when i try to get the server list with the "Get-AdComputer" cmdlet i get errors.
$servers = Get-ADComputer -Filter * -SearchBase "OU=SomeOU, DC=SomeDomain, DC=SomeDomain, DC=SomeDomain" | Select-Object Name
$allDisks = foreach ($server in $servers)
{
Get-WmiObject Win32_LogicalDisk -ComputerName $server -Filter DriveType=3 |
Select-Object #{'Name'='ComputerName'; 'Expression'={$server}},
DeviceID,
#{'Name'='Size'; 'Expression'={[math]::truncate($_.size / 1GB)}},
#{'Name'='Freespace'; 'Expression'={[math]::truncate($_.freespace / 1GB)}}
}
$allDisks |Export-Csv C:\Servers.csv -NoTypeInformation
when i run this i get:
Get-WmiObject : Der RPC-Server ist nicht verfügbar.
In Zeile:5 Zeichen:5
+ Get-WmiObject Win32_LogicalDisk -ComputerName $server -Filter Dri ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
i also should add, that if i only run the thing from the first line i get an clean list of all of our servers.

As the error states that RPC server is not available for the one of the servers that you are trying to query. There can be multiple reasons as per the PS Blog:
The remote computer is blocked by the firewall.
Solution: Open the Group Policy Object Editor snap-in (gpedit.msc) to edit the Group Policy object (GPO) that is used to manage Windows Firewall settings in your organization. OpenComputer Configuration, open Administrative Templates, open Network, open Network Connections, open Windows Firewall, and then open either Domain Profile or Standard Profile, depending on which profile you want to configure. Enable the following exception: “Allow Remote Administration Exception” and “Allow File and Printer Sharing Exception“.
Hostname or IP address is wrong or the remote computer is shut down.
Solution: Verify correct hostname or IP address.
The “TCP/IP NetBIOS Helper” service isn’t running.
Solution: Verify that “TCP/IP NetBIOS Helper” is running and set to auto start after restart.
The “Remote Procedure Call (RPC)” service is not running on the remote computer.
Solution: Verify that “Remote Procedure Call (RPC)” is running and set to auto start after restart.
The “Windows Management Instrumentation” service is not running on the remote computer.
Solution: Verify that “Windows Management Instrumentation” is running and set to auto start after restart
So, I dont think there is any code issue there. Kindly check the network firwwall and server side. Also apply a try/catch block and capture the exact server name in the loop to see which server is that causing the issue.

Related

Jenkins on Windows fails to deploy with WinRM?

I have an old established codebase that I'm trying to bring up to modern era standards. Most of it is written on Windows using Visual Studio, so I need to have a Windows based build server to use the MSBuild pipeline. I have a mostly working Jenkins CI pipeline that ingests from Github webhooks, and should deploy to a Windows PC on my local network. I've tested that this works from any other user, on my workstation and on the build server. I know Jenkins runs jobs as the "NT AUTHORITY\System" user, and I've used SysInternals PSExec to pop in and setup my ssh keys, and so forth in the past. The problem is during the deploy step; I'm compressing and copying the build output using a PowerShell script, and using New-PSSession, and Copy-Item -ToSession.
I'm using a cred I'm constructing with Get-Credential, user/pass pair, that I've verified as working. All concerned systems are in a simple workgroup, no domain involved.
The New-PSSession command in my deploy.ps1 script fails with the following error:
PS C:\Program Files (x86)\Jenkins\workspace\xxx> .\deploy.ps1
Compressing to C:\Windows\TEMP\tmpEBB2.tmp.zip
New-PSSession: C:\Program Files (x86)\Jenkins\workspace\xxx\deploy.ps1:95
Line |
95 | … $sess = New-PSSession -ComputerName $TargetHost -Credential $cred …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| [205.208.87.185] Connecting to remote server 205.208.87.185 failed with the following error message :
| WinRM cannot process the request. The following error with errorcode 0x8009030d occurred while using
| Negotiate authentication: A specified logon session does not exist. It may already have been
| terminated. Possible causes are: -The user name or password specified are invalid. -Kerberos is
| used when no authentication method and no user name are specified. -Kerberos accepts domain user
| names, but not local user names. -The Service Principal Name (SPN) for the remote computer name and
| port does not exist. -The client and remote computers are in different domains and there is no trust
| between the two domains. After checking for the above issues, try the following: -Check the Event
| Viewer for events related to authentication. -Change the authentication method; add the destination
| computer to the WinRM TrustedHosts configuration setting or use HTTPS transport. Note that computers
| in the TrustedHosts list might not be authenticated. -For more information about WinRM
| configuration, run the following command: winrm help config. For more information, see the
| about_Remote_Troubleshooting Help topic. Other Possible Cause: -The domain or computer name was not
| included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName.
Write-Error: C:\Program Files (x86)\Jenkins\workspace\xxx\deploy.ps1:129
Line |
129 | Deploy-ToTargetHost
| ~~~~~~~~~~~~~~~~~~~
| Could not establish session.
I generated that second error when the $sess var fails to populate. This is line 95:
$sess = New-PSSession -ComputerName $TargetHost -Credential $cred
I believe I've heard something about the System user has some restrictions on network access? Is there any way to work around this?
I mean, I can just scp it over if there's no other way to do this, but I really wanted to just have all my shell scripting in pwsh if I could get away with it. Thanks.
[Edit: TL;DR, I suppose I can modify Jenkins to run as a different user, but why isn't it already running like that? This just seems trivially weird to me to install by default on a user with no network access, I guess?]
I ended up running Jenkins as a different user in Windows Services, specifically a "regular" login user. This made it do the deployment successfully.

Mount-DiskImage giving Access Denied when running through remote session

I have two VM's(Windows server 2008 r2) with ip
172.17.178.10
and
172.17.178.11
.
I have created a folder named
"share"
on vm with ip 172.17.178.10 that has an iso.
I logined into vm with ip 172.17.178.11 and run the following command
"Mount-DiskImage \\172.17.178.10\share\xyz.iso"
.It mounted successfully i can see the Drive in my computer.
Now i logined into 172.17.178.10 and took a remote session using powershell command
Enter-PSSession -ComputerName 172.17.178.11 -Credential Administrator
.
Now when i run the command
"Mount-DiskImage \\172.17.178.10\share\xyz.iso"
.
I get the following error:
MOUNT-DISKIMAGE : Access is denied.
+ CategoryInfo : PermissionDenied: (MSFT_DiskImage:ROOT/Microsoft/.../MSFT_DiskImage) [Mount-DiskImage],
CimException
+ FullyQualifiedErrorId : HRESULT 0x80070005,Mount-DiskImage
I have provided full permissions to the
share
folder.
The issue here is that powershell remoting will not allow for a second-hop authentication unless credssp is enabled. Basically what happens is that when when authenticate to the server you are remoting to it only verifies that you have access to it, it does not actually store your credentials for security reasons, so it is not able to connect to any other server in your environment. I've attached some links below with info on setting up CredSSP, which will allow you to perform second-hop remoting once it is configured.
https://support.microsoft.com/en-us/kb/951608
https://technet.microsoft.com/en-us/library/hh849872.aspx
you could also probably set your share/NTFS permissions to allow everyone read permissions but I have not tested that.

unable to ping any sites in command line/powershell windows 7

Does windows command line requires any proxy setting to ping websites?
I can access all websites in my browser but when I try to ping the same from commandline or powershell I get "Request timed out" error. How to resolve this error?
In IE browser I've set a automatic proxy detection script as the network is company LAN. Tried most of solutions provided in web without any luck.
Due to this I am unable to run the chef commands to install gems and receiving error Unable to download data from https://rubygems.org/ - Errno::ETIMEDOUT:
A connection attempt failed because the connected party did not properly respon
d after a period of time, or established connection failed because connected hos
t has failed to respond. - connect(2) for "api.rubygems.org" port 443 (https://a
pi.rubygems.org/specs.4.8.gz)
Getting a ping reply or HTTP response are two entirely different things. That is, any server can honor either of those just as well as it pleases. In addition, there might be proxies and firewalls on the route that change the results. Even if a server is willing to reply on ping, corporate firewall might block it.
You might have some success with setting Chef's proxy settings via environment variables, as per documentation. As how to find out the proxy settings, ask your network admin. If that doesn't work, retrieve the proxy settings from IE's registry key. In case of link rot, here's the function:
function Get-InternetProxy {
<#
.SYNOPSIS
Determine the internet proxy address
.DESCRIPTION
This function allows you to determine the the internet proxy address used by your computer
.EXAMPLE
Get-InternetProxy
.Notes
Author : Antoine DELRUE
WebSite: http://obilan.be
#>
$proxies = (Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings').proxyServer
if ($proxies) {
if ($proxies -ilike "*=*") {
$proxies -replace "=","://" -split(';') | Select-Object -First 1
} else {
"http://" + $proxies
}
}
}

Powershell Session to one remote host then on to another

Is there a way to use Powershell to remote onto one machine (let's called it hub) and then from within that session remote onto another (a "spoke")? I need to connect to the hub touchdown server in our VPN before I can connect on to another machine.
Or is there another way to proxy the session via the hub machine?
From within the session to the HUB I can create the new PSSession, but I get an error when trying to enter it:
[HUB]: PS C:\Users\idlemind\Documents> New-PSSession remotehost.domain.com -Credential idlemind#domain.com
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
1 Session1 remotehost.d... Opened Microsoft.PowerShell Available
[HUB]: PS C:\Users\idlemind\Documents> Enter-PSSession 1
Enter-PSSession : You are currently in a Windows PowerShell PSSession and cannot use the Enter-PSSession cmdlet to enter another PSSession.
+ CategoryInfo : InvalidArgument: (:) [Enter-PSSession], ArgumentException
+ FullyQualifiedErrorId : RemoteHostDoesNotSupportPushRunspace,Microsoft.PowerShell.Commands.EnterPSSessionCommand
You'd need to enable Multihop Remoting on Hub.
Enable-WSManCredSSP –Role Client –DelegateComputer spoke
And this on Spoke. Enable-WSManCredSSP –Role Server
Please read
http://blogs.technet.com/b/heyscriptingguy/archive/2013/04/04/enabling-multihop-remoting.aspx
http://technet.microsoft.com/en-us/magazine/jj853299.aspx
http://blogs.msdn.com/b/clustering/archive/2009/06/25/9803001.aspx
Since your runnig a 2012 server, I'd investigate installing Powershell Web Access on that 'Hub' machine. It will give you very fine-grained access control, and act as a "gateway" to remote sessions on other machines once your are connected to it.

Security of running PowerShell command remotely?

I'm new to PowerShell. I'm looking to run PowerShell command on a remote PC running Windows 7.
On the remote PC, I ran the following PowerShell commands:
Enable-PSRemoting -Force
Set-Item WSMAN:\localhost\client\trustedhosts <host_ip>
Restart-Service WinRM
I performed the last two commands on the host PC (but using <remote_ip>).
I confirmed this worked OK with:
Invoke-Command -ComputerName <name> -Credential <username> -ScriptBlock { Get-ChildItem C:\ }
My question: Is this secure on a public network? Should I be doing something else? Or should I be using SSL? If so, how do I go about this?
If you use the default authentication when using Invoke-Command the user is authenticated on the remote host using either NTLM or Kerberos. So I don't think you need to worry too much about the password being sniffed out on the network. Also, by default, remoting endpoints can only be used by administrators on that machine. Finally, if you need to allow non-admins access, you can configure a remoting endpoint that is restricted. It can be restricted in the cmdlets available and it can be restricted in language capability. This tutorial on remoting covers setting up a restricted session.

Resources