Showing posts with label windows. Show all posts
Showing posts with label windows. Show all posts

Saturday, July 2, 2011

Check your ip/computername with nslookup in powershell

Nslookup is a great tool for testing and troubleshooting. However, if you need to check a large range of IP/Computername in mass, nslookup is not the better choice. So, this below script could help you to do the same in powershell. (Download script)


#
# NSLookup
#
# by F.Richard 2011-05
#


# ***********************************************

Function NSlookup {
Param($hostname)
#$iphostEntry = [System.Net.Dns]::GetHostEntry($hostname)
# Rexolve obsolete but better than GetHostEntry
$iphostEntry = [System.Net.Dns]::Resolve($hostname)
$line = $iphostEntry.HostName

$strSeparator = ";"
foreach ($addr in $iphostEntry.AddressList) {
$line = $line + $strSeparator + $Addr.IPAddressToString
$strSeparator = "|"
}

$strSeparator = ";"
foreach ($alias in $iphostEntry.aliases) {
$line = $line + $strSeparator + $alias
$strSeparator = "|"
}

return $line
}



# ***********************************************

Function TestFile {
Param(
[String] $strFilename,
[String] $strCurDir
)
if ($strFilename) {
$strCurDir = $(if ($strCurDir) {$strCurDir} else {if ($MyInvocation.MyCommand.CommandType -eq "Function") {(Get-Location).Path} else {Split-Path -parent $MyInvocation.MyCommand.Path} })
If ((Test-Path("$strFilename")) -eq $False){
If ($strFilename.ToUpper().Contains($strCurDir.ToUpper()) ) {
Write-Host "ERROR: file $strFilename NOT exist"
return
} Else {
If ((Test-Path("$strCurDir\$strFilename")) -eq $False){
Write-Host "ERROR: file $strFilename NOT exist"
Write-Host "ERROR: file $strCurDir\$strFilename NOT exist"
return
} Else {
$strFilename = "$strCurDir\$strFilename"
}
}
}
return $strFilename
}
}


# ***********************************************

Function GetFileIntoArr {
Param(
[String] $strFilename,
[String] $strCurDir,
[Ref]$arrFile,
[String] $strComment
)
$strComment = $(if ($strComment) {$strComment} else {"#"})
$strCurDir = $(if ($strCurDir) {$strCurDir} else {if ($MyInvocation.MyCommand.CommandType -eq "Function") {(Get-Location).Path} else {Split-Path -parent $MyInvocation.MyCommand.Path} })

$retFilename = TestFile -strFilename $strFilename -strCurDir $strCurDir
if ($retFilename) {
$Content = Get-Content "$retFilename"
Foreach ($line in $Content) {
$comment = $False
If ($line.Trim().length -gt 0) { # take only line with data and without # at begininng of the line
# if we do not want to use comment
If ($strComment -eq "#") {
If ($line.substring(0,1) -eq "#") {
$comment = $True
}
}
If ($comment -eq $False) {
# Get Search & Replace
$arrFile.Value += $line.Trim()
}
}
}
return $True
} else {
return $False
}
}

# ***********************************************

#
# MAIN PROGRAM
#

# Verify Arguments Number
If($Args.Count -lt 2) {
Write-Host "Syntax:"$MyInvocation.MyCommand.Name "inputfilename outputfilename"
Write-Host " Example:"$MyInvocation.MyCommand.Name" 'inputfile.txt' 'outputfile.txt' "
Write-Host " Example:"$MyInvocation.MyCommand.Name" -inputfile 'inputfile.txt' -outputfile 'outputfile.txt' "
Write-Host
Break
}

$inputfile = $args[0]
$outputfile = $args[1]
$date = get-date -format "yyyy-MM-dd"
$Content = "#Date;Computer;Hostname;IP`r`n"
$Content | Out-File -encoding ASCII $outputfile
[Array] $arrComputers = @( )

if ($inputfile) {
if (!(GetFileIntoArr -strFilename $inputfile -arrFile ([Ref]$arrComputers))) {
Break
}
} else {
Write-Host "ERROR: you need a filename.txt as second parameter inputfile"
Break
}
Foreach ($computer in $arrComputers) {
$nslookup = NSlookup($computer)
$line = $date + ";" + $computer + ";" + $nslookup
#+ "`r`n"
Write-Host $line
$line | Out-File -append -encoding ASCII $outputfile
}


Example of Result:

#Date;Computer;Hostname;IP
2011-06-01;COMPUTER1;computer1.dns1.my.net;192.1.1.45;COMPUTER1.dns2.my.net
2011-06-01;COMPUTER2;COMPUTER2.si.net;192.1.1.100
2011-06-01;COMPUTER3;COMPUTER3.si.net;192.1.1.101
2011-06-01;COMPUTER4;COMPUTER4.si.net;192.1.102

Monday, May 23, 2011

Remote assistance in Windows 2003/2008 without activate it

An old information which can interest some people. Sometimes I need to have user or account service rights on a server to make some actions. A remote desktop connection or a "Runas" in command line can help me for this, but that means I must to know user's password. This information can be critical, so, when user is not in the same building or in an other country than me, remote assistance is a good way to resolve this problem. But, on a server, this feature is generally not activated. So the trick is to use Task Manager.

Actions:
Connect your server using remote desktop connection (mstsc.exe) then run task manager (taskmgr.exe in command line or start / Windows security / Task manager).



User or service account which you need to control is already connected on this server. So in "Users" tab in task manager you can see it. Select user then click on right button. Click on "Remote Control"







A new window appears asking you hotkey for closing your session. Use default (ctrl+*) or define your own hotkey then click on OK button


















Now user to control have a window which permit to your user to control his session. User click on Yes button, and you can control his session now. Terminate your session using hotkey define above.







For information, you can do the same with "Terminal Services Manager"

Sunday, May 15, 2011

findstr does not support unicode

I often use findstr command on my windows XP to find some informations in text files (grep for unix)

For example with this command

findstr /i "PC2K01" *.*

you will have something like:

File_WIN_PC01_20110414.csv:2011-04-14;PC2K01;;G:;72;62;WINDOWS
File_WIN_PC01_20110414.csv:2011-04-14;PC2K01;;H:;54;49;WINDOWS


I don't remember having problems to find something with findstr command. Except today, when I try to find a computer name in some files. I was completely sure this computer exist in my files and findstr doesn't find this computer...
Finally, I found manually the file containing my computer. So I decided to understand why findstr didn't work. 2 reasons appears to me immediatly: 1st-findstr is bugged. 2nd-there is an encoding problem. To verify this 2nd reason I tested all my files with Get-FileEncoding.ps1
like this

Import-Module .\Get-FileEncoding.ps1
Get-ChildItem | select name, @{n='Encoding';e={Get-FileEncoding $_.FullName}}


Then it appears some file are in Unicode

Name Encoding
---- --------
1.csv ASCII
2.csv Unicode UTF-16 Little-Endian
3.csv ASCII
4.csv ASCII
5.csv ASCII
6.csv ASCII


To verify my idea was good, I just tested something that exist in unicode file 2.csv. In file 2.csv there is the string mystring and only in this file.

findstr /i "mystring" 2.csv

and nothing appears. Findstr does not support unicode....

The solution: convert all your files to ansi.
For this, use this command to create files ANSI_1.csv ANSI_2.csv ...

Get-ChildItem | Foreach-Object { Get-Content -Path $_.Fullname | Out-File ANSI_$_ -Encoding Default }

(for information, you can also do it manually by using notepad / file save as / and changing encoding)

some other ideas if you don't want to convert your files to ansi:
- use find command which is unicode (yes find is unicode / not findstr...)

- use Microsoft sysinternals strings utility
http://technet.microsoft.com/en-us/sysinternals/bb897439

- use powershell

Select-String *.* -pattern "string" | Select-Object filename,pattern,line

Wednesday, November 3, 2010

Extend Windows system volume disk easily

A great tool from Dell which permit on Windows XP, 2000 & 2003 to extend system volume:
Dell Extpart (Alternative Download)

Work on physical and virtual disk.

Tuesday, October 26, 2010

Get Windows Network configuration Remotely

Today a 1 hour script. We need to know some network informations on a lot of computers, especially DNS search order.

In powershell, that's easy done by using

$strComputername = "localhost"
$NICs = Get-WmiObject Win32_NetworkAdapterConfiguration -Computername $strComputername | Where {$_.IPEnabled -eq "TRUE"}
foreach ($nic in $nics) {
$nic.DNSServerSearchOrder
}



Unfortunately, for a lot of reason, I can't use powershell. No time to lose. So I use one of my old vbscript and adapt it using information coming from Microsoft Site(Automating TCP/IP Networking on Clients - Part 2: Scripting Basic TCP/IP Networking on Clients)

That's the result that you can download too



'
' Get All Network Configuration
'
'
' F.RICHARD
' 2010 October
'

Option Explicit
Const ForReading = 1, ForWriting = 2, ForAppending = 8


' Detect WScript or CScript
'
If InStr(LCase(WScript.FullName), "wscript")>0 Then ' ex: FullName = C:\WINNT\system32\wscript.exe
WScript.Echo "This script must be run under CScript."
WScript.Quit
End If


' Get Path
'
Dim strScriptFullName, strScriptPath, strScriptName
strScriptName = WScript.ScriptName
strScriptFullName = WScript.ScriptFullName ' ex: C:\Program Files\MyFolder\MyProg.exe
strScriptPath = Left(strScriptFullName, InStrRev(strScriptFullName, "\") - 1) ' ex: C:\Program Files\MyFolder


' Variables For File
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")


' Input parameter
'
Dim objInputFile, strInputFile
If WScript.Arguments.Named.Exists("input") Then
strInputFile = WScript.Arguments.Named("input")

If Not isFileExist(strInputFile) Then
If Not isFileExist(strScriptPath & "\" & strInputFile) Then
WScript.Echo strInputFile & " File Not Exist !"
WScript.Echo strScriptPath & "\" & strInputFile & " File Not Exist !"
WScript.Quit
End If
strInputFile = strScriptPath & "\" & strInputFile
End If
Set objInputFile = objFso.OpenTextFile(strInputFile, ForReading)
Else
WScript.Echo "You must defined an argument /input ex: /input:input.txt !"
WScript.Quit

End If


' Output parameter
Dim strOutputFile, objOutputFile
If WScript.Arguments.Named.Exists("output") Then
strOutputFile = WScript.Arguments.Named("output")
Else
WScript.Echo "You must defined an argument /output ex: /input:output.txt !"
WScript.Quit

End If
On Error Resume Next
Set objOutputFile = objFSO.CreateTextFile(strOutputFile, ForWriting, True) ' delete file
If (Err.Number <> 0) Then
WScript.Echo strOutputFile & " file - permission denied or file already opened"
On Error GoTo 0
WScript.Quit
End If
On Error GoTo 0




' Put servers in Dictionary
'
Dim objItem, objDictionary, objTextFile, strNextLine, i
Set objDictionary = CreateObject("Scripting.Dictionary")
Set objTextFile = objFSO.OpenTextFile (strInputFile, ForReading)
i = 0
Do Until objTextFile.AtEndOfStream
strNextLine = Trim(objTextFile.Readline)
If (Len(strNextLine)>1) Then
If Not Left(strNextLine, 1) = "#" Then
objDictionary.Add i, strNextLine
i = i + 1
End If
End If
Loop

Dim line
line = "Hostname;NICDescription;MACAddress;IPAddress;IPSubnet;DefaultIPGateway;DHCPEnabled;DHCPServer;DNSDomain;DNSDomainSuffixSearchOrder;WINSPrimaryServer;WINSSecondaryServer;DNSServerSearchOrder1;DNSServerSearchOrder2"
WScript.Echo line
objOutputFile.WriteLine(line)

Dim objWMIService, objWMIServiceRemote, colAdapters, objAdapter
Dim strComputerName, computers, objComputer
Dim DNSHostname, NICDescription, MACAddress, IPAddress, IPSubnet, DefaultIPGateway
Dim DHCPEnabled, DHCPServer, DNSDomain, DNSDomainSuffixSearchOrder, WINSPrimaryServer, WINSSecondaryServer
Dim DNSServerSearchOrder
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
For Each objItem in objDictionary
strComputerName = objDictionary.Item(objItem)
WScript.Echo strComputerName
Set Computers = objWMIService.ExecQuery ("Select * from Win32_PingStatus Where Address = '" & strComputerName & "'")
For Each objComputer in Computers
If objComputer.StatusCode = 0 Then
' suppress errors in case of errors
On Error Resume Next
Set objWMIServiceRemote = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputerName & "\root\cimv2")

' Only query Enabled NIC
Set colAdapters = objWMIServiceRemote.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
'Wscript.echo Err.Number & ";" & Err.Description

Select Case Err.number
'Case "-2147022676" :
' line = strComputerName & ";" & strGroupToCheck & " group NOT EXIST"
' WScript.Echo line
' objOutputFile.WriteLine(line)

Case "-2147024843" :
line = strComputerName & ";INVALID Network Path OR insufficient access rights"
WScript.Echo line
objOutputFile.WriteLine(line)

'Case "-2147463168" :
' line = strComputerName & ";INVALID ADSI WinNT://" & strComputerName & "/" & strGroupToCheck & ",group"
' WScript.Echo line
' objOutputFile.WriteLine(line)

Case Else :
For Each objAdapter in colAdapters
' DNS Host name
DNSHostname =""
DNSHostname = objAdapter.DNSHostName


' NIC Description
NICDescription = objAdapter.Description


' MAC Address
MACAddress = ""
MACAddress = objAdapter.MACAddress


' IP Address
IPAddress = ""
If Not IsNull(objAdapter.IPAddress) Then
For i = 0 To UBound(objAdapter.IPAddress)
If (IPAddress = "") Then
IPAddress = objAdapter.IPAddress(i)
Else
IPAddress = IPAddress & "_" & objAdapter.IPAddress(i)
End If
Next
End If


' IP Subnet
IPSubnet = ""
If Not IsNull(objAdapter.IPSubnet) Then
For i = 0 To UBound(objAdapter.IPSubnet)
If (IPSubnet = "") Then
IPSubnet = objAdapter.IPSubnet(i)
Else
IPSubnet = IPSubnet & "_" & objAdapter.IPSubnet(i)
End If
Next
End If


' Default Gateway
DefaultIPGateway = ""
If Not IsNull(objAdapter.DefaultIPGateway) Then
For i = 0 To UBound(objAdapter.DefaultIPGateway)
If (DefaultIPGateway = "") Then
DefaultIPGateway = objAdapter.DefaultIPGateway(i)
Else
DefaultIPGateway = DefaultIPGateway & "_" & objAdapter.DefaultIPGateway(i)
End If
Next
End If


' DHCP Enabled
DHCPEnabled = ""
DHCPEnabled = objAdapter.DHCPEnabled


' DHCP server
DHCPServer = ""
DHCPServer = objAdapter.DHCPServer


' DNS Domain
DNSDomain = objAdapter.DNSDomain


' DNS Domain Suffix Search Order
DNSDomainSuffixSearchOrder = ""
If Not IsNull(objAdapter.DNSDomainSuffixSearchOrder) Then
For i = 0 To UBound(objAdapter.DNSDomainSuffixSearchOrder)
If (DNSDomainSuffixSearchOrder = "") Then
DNSDomainSuffixSearchOrder = objAdapter.DNSDomainSuffixSearchOrder(i)
Else
DNSDomainSuffixSearchOrder = DNSDomainSuffixSearchOrder & "_" & objAdapter.DNSDomainSuffixSearchOrder(i)
End If
Next
End If

WINSPrimaryServer = objAdapter.WINSPrimaryServer
WINSSecondaryServer = objAdapter.WINSSecondaryServer

' DNS Search Order
DNSServerSearchOrder = ""
If Not IsNull(objAdapter.DNSServerSearchOrder) Then
For i = 0 To UBound(objAdapter.DNSServerSearchOrder)
DNSServerSearchOrder = DNSServerSearchOrder & ";" & objAdapter.DNSServerSearchOrder(i)
Next
End If


line = DNSHostname & ";" & NICDescription & ";" & MACAddress & ";" & IPAddress & ";" & IPSubnet & ";" & DefaultIPGateway & ";" & DHCPEnabled & ";" & DHCPServer & ";" & DNSDomain & ";" & DNSDomainSuffixSearchOrder & ";" & WINSPrimaryServer & ";" & WINSSecondaryServer & DNSServerSearchOrder
WScript.Echo line
objOutputFile.WriteLine(line)
Next

End Select
On Error Goto 0
Else
line = strComputerName & ";NOT available"
WScript.Echo line
objOutputFile.WriteLine(line)
End If
Next
Next


'--------------------


' Help
'
' Help File
'

Sub Help(ByRef strScriptName)
WScript.Echo strScriptName & " Arguments" & vbCrLf _
& vbTab & "/input:""filename_for_server_list""" & vbCrLf _
& vbTab & "/output:""filename_for_output""" & vbCrLf _
& vbTab & "/? or nothing for this" & vbCrLf _
& vbCrLf & "Example:" & vbCrLf _
& "cscript " & strScriptName & " /input:""servers.txt"" /input:""result.csv"" " & vbCrLf
WScript.Quit(0)
End Sub


'--------------------

' isFileExist
'
' Test if File Exist
'
Function IsFileExist(ByRef strInputFile)
Dim iReturn
iReturn = False

Dim objFSO
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strInputFile) Then
iReturn = True
End If
Set objFSO = Nothing
On Error Goto 0

IsFileExist = iReturn
End Function


'--------------------

' pingComputer
'
' Ping Test
'
Function pingComputer(strComputerName)

Dim pingStatus, objPing, objStatus
pingStatus = false
Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}")
Set objPing = objPing.ExecQuery("select * from Win32_PingStatus where address = '" & strComputerName & "'")
For Each objStatus in objPing
If IsNull(objStatus.StatusCode) or objStatus.StatusCode<>0 Then
pingComputer = false
Else
pingComputer = true
End If
Next


End Function

'--------------------