Monthly Archives: August 2013

How to Get The Logged On User on a Remote Windows Machine

This one is super cool and you will amaze your boss. Many times, I’m asked if I can find who is logged into a machine.

As long as you have PSRemoting enabled across your network you can run this:

Also replace IP or name with the IP address or computer name of the computer

get-wmiobject win32_computersystem -computer IP or name | select username

or you can do a | select * and it will give you more info.

How to Search Files Recursivly and Replace content in files

I was tasked to search many files in a directory structure and find content in each file and replace that content. The directory has MANY types of files in it so I had to search for a certain type of file, then search inside that file and replace a string if found.

So, I did this:

Get-ChildItem | ForEach-Object Get-Content -replace and then Set-Content

change *File.Type* with the filetype you want to search for. It could be a *.log or a *.bak

Change string1 to what you’re looking for and string2 to what you want to change it to.

NOTE: This code will save the file with a new date even if it doesn’t replace the string. One minor issue that you must be aware of because if you later want to search for all old files and delete them, it wont find old ones that you’ve touched with this script because of the date change. I’m working on a new version that only saves the file if the string is found in it. Feel free to comment if you got the answer to this 🙂

Here is the code:

Get-ChildItem -include *File.Type* -Recurse | ForEach-Object { ( Get-Content -Path $_.FullName ) -replace 'string1', 'string2' | set-content $_.fullname }