How to use sudo in powershell

Well this is not exactly same as sudo.

However it is very annoying when I want to run something in powershell and it gives me access denied. And then  I need to go to start menu, or task bar, right click, select run as administrator etc just to run one command. As someone who likes to use commands over GUI, had to find a way to improve this.

The following command will open a powershell window with admin privilages.

start-process powershell -verb runas

However I find this as also a long command. So I just put this inside a function called sudo and put inside my powershell profile.

So my powershell profile looked like this.

function sudo {
start-process powershell -verb runas
}

Now, I can just run sudo from my normal powershell window and it will open an elevated prompt. Much faster, much efficient.

sudo

Although this works, ultimately this is not what I want. I want to be able to do the below without installing third party tools:

1) run within the same window ( without opening another window)

2) able to run certain commands as elevated without opening a whole powershell window – just like sudo

Will look forward to work on this, and if I get to do it, will update here.

TIL how to disable the timeout of mapped drives in Windows

I was trying to copy some big files over the network to another server, and I mapped the destination drives in the local server for easy copying. However I kept getting errors in my script, which I suspected because the drives getting disconnected. Here is how to set it to not disconnect.

Run as administrator in a command prompt, where -1 means disable.

net config server /autodisconnect:-1

TIL how to check the bandwidth between 2 servers

We subscribed for a dedicated line between 2 datacenters, and when we were trying to copy some files over, it was really slow.
We were supposed to get few MB/s transfer rate, but were getting only 20KB/s which was unacceptable. We needed to make a clear case with the service provider to get their support on fixing this. Simple google searches showed me the tool called iperf, and it provided me what I wanted. It is a shame that I never knew this tool existed.

In the destination server, I ran the iperf server by below command:

.\iperf3.exe -s -p 136 (I only have few ports open in between, and that is not currently in use)

and in the source, I ran the iperf client:

.\iperf3.exe -c <Destination IP> -p 136

The results were enough to convince the service provider to fix their network.

This is probably the most basic test that can be done using the tool, but there are plenty of other options as documented here.

How to fix the error “an authentication error has occurred(code 0x80004005)” when connecting through RDP.

<<This site is migrated to https://ebinissac.me. Please click here to see the updated post>>

Ever since the policy to disable TLS 1.0 was pushed down to the local machines, we started getting the error “an authentication error has occurred(code 0x80004005)”  when accessing few of our Windows 2008 R2 servers. It was interesting because we have a bunch of other servers with no problems accessing. This seems to be a very generic error code as google results were showing multiple problems and multiple solutions for this.

Apparently, in my case, the patch to add RDS support for TLS 1.1 and TLS 1.2 was not installed in 3 of the servers with this problem. So I had to download the patch from this Microsoft website and install and reboot them remotely. Once installed and rebooted, voila!!

Edit: There are multiple reasons for this problem, and there are multiple ways to fix it. I am just sharing what worked for me, and it may not work for all. Saying this because this post is now in the first page of google results and I am getting lot of traffic to this, and I do not want to disappoint you. Thanks

Fix “Failed to open Group Policy Object. You might not have the appropriate rights” error

I was facing this error in one of my servers while trying to open gpedit, with additional message “The volume for a file has been externally altered so that the opened file is no longer valid”.

Here is how  I fixed it.

1) Enable view hidden files from explorer.

2) Navigate to C:\Windows\System32\GroupPolicy\Machine

3)Rename the file Registry.pol to something else.

4) Run gpupdate

By now, I was able to open gpedit normally.

Note that by doing this, whatever polices in the local group policy settings will be gone. There will only be settings from the domain policy. So if you have made any local policy changes, they need to be re-done.

Fix problems in trusting files from a DFS namespace

So we migrated our fileshare to a DFS namespace and we started facing a lot of problems. One of the most annoying one was, no matter how we trust the source, the powershell scripts from the DFS namspaces were not able to run, as they give warning.

Interestingly, problem was that the FQDN of the DFS namespace is considered as an internet location by windows, causing it to not trust the location. This can be fixed by editing the local group policy.

Group policy editor -Computer configuration- Administrative templates – Windows components -Internet Explorer – Internet Control Panel – Security Page – Site to Zone Assignment List.

fqdn

How to export services and their users into csv

I need to export the services and their ‘run as’ users in a number of servers. This is how I did it.

#Ebin Issac 6/3/2018
#This will read a list of servers from a text file, and extract the services which are not run by localsystem, and save into a csv file. Need to be run from a server with elevated permissions

$ComputerList = Get-Content serverlist.txt
ForEach ($Server In $ComputerList) {
    Write-Host "Processing $($Server) ... " -ForegroundColor White -NoNewline
    Get-wmiobject -computername $Server win32_service | where { $_.startname -notmatch "localsystem"}| select-object pscomputername,Displayname,name,startname | Export-Csv "$Server.csv" -NoTypeInformation 
   # write-host $?
    If ($? -eq 'True') {
			Write-Host "OK." -ForegroundColor Green
    }
     Else {
			Write-Host "Failed." -ForegroundColor Red
    }
}

You can find the download link here.

So this will take a list of servers, and extract the services, but excludes those run by localsystem, and export into a csv. You can filter that part based on your requirements. The output will look similar to this.

ServiceUsers

How to export group memberships of Active Directory users into CSV format..

So I started a new job recently, and I am working on a as-is migration. I needed to export the list of AD users and their group memberships into human readable format. So this is how I did it.

$users = Get-ADUser -Filter *
foreach ($user in $users) {

$Groups = (Get-ADPrincipalGroupMembership -Identity $user.SamAccountName | Select-Object -ExpandProperty name) -join ','
get-aduser $user.SamAccountName -properties memberof,samaccountname,givenname,surname | select samaccountname, @{name="Groups";expression={$Groups}} | export-csv -append "ADUsers.csv" -Delimiter "," -NoTypeInformation -Encoding UTF8
}

You can find it in github here.

Basically, it just get all users from AD, and find their memberships and save only their names and memberships.

How to export the last login details of all users in a Windows server using Powershell

So one of our clients want to get a monthly report on the last login details of all users in the Windows servers in our environment. So we came up with this powershell script which is scheduled to run end of every month. This will extract the data, and upload them to an S3 bucket. It makes use of awscli for uploading to s3. We can even include SNS notification, but right now it is not implemented.

Below is the script:

Disclaimer : I do not know if this is the best way to do it just like all my other scripts, but this works [ At least for me ]

$currentMonth = Get-Date -Format MM
$currentYear = Get-Date -UFormat %Y
$hostname = hostname
$filename = $currentYear+""+$currentMonth+""+$hostname+"_login.csv"
$([ADSI]"WinNT://$env:COMPUTERNAME").Children | where {$_.SchemaClassName -eq 'user'} | select @{l='name';e={$_.name}},@{l='LastLogin';e={$_.lastlogin}} | export-csv C:/temp/$filename

(gc C:/temp/$filename) -replace (gc C:/temp/$filename)[0],"" | sc C:/temp/$filename -Force
(gc C:/temp/$filename) -replace (gc C:/temp/$filename)[1],"" | sc C:/temp/$filename -Force
(gc C:/temp/$filename) | ? {$_.trim() -ne "" } | set-content C:/temp/$filename

aws s3 cp C:/temp/$filename s3://YourBucket/$currentYear/$currentMonth/

This will create a csv file in the following format.
windows_last_login

How to display a pop up message in a remote computer using powershell

In my daily work, there are times which I need to contact a user who is using a particular PC, but they don’t respond. Mostly, I need to contact them to inform about something, or get them to reboot, or install something etc. There are some cases which it is not possible, such as :

  • They use a generic account which is shared, so we can’t find who exactly is using that PC
  • They are logged off from IM
  • They don’t respond to IM or just ignore them.

In these kind of cases, it is easier if we have some way to forcefully push a message to the PC. I found an easy solution from internet that can do this in every computer that you have admin access.

Open a text editor and add the following in it, then save it with .ps1 extension.

Function remote_message{

$server = read-host -prompt ‘Input PC name’;
$message = read-host -prompt ‘Enter the message’;

Invoke-WmiMethod -Class win32_process -ComputerName $server -Name create -ArgumentList  “c:\windows\system32\msg.exe * $message” }

remote_message

To run this, open powershell, then navigate to the saved location and run. And follow the input prompt.

remote_message

No matter who is logged in the remote PC, they will get the message pop up on top of all their windows.

remote_message_2