I just want to get the hostname of IP 192.168.1.10, using [System.Net.Dns]::BeginGetHostEntry(), like the code example of Microsoft on C#, but on Powershell.
I've done this in the file getlan.ps1
:
#
$GetHostEntryFinished = [System.Threading.ManualResetEvent]::new($false);
class ResolveState
{
hidden $hostname;
hidden $resolvedIPs;
ResolveState($host1)
{
$this.hostname = $host1;
#
# add getter and setter for the member IPs:
#
$this | Add-Member -Name IPs -MemberType ScriptProperty -Value {
# This is the getter
return $this.resolvedIPs
} -SecondValue {
param($value)
# This is the setter
$this.resolvedIPs = $value
}
#
# add getter and setter for the member host:
#
$this | Add-Member -Name host -MemberType ScriptProperty -Value {
# This is the getter
return $this.hostname
} -SecondValue {
param($value)
# This is the setter
$this.hostname = $value
}
}
}
#
# Record the IPs in the state object for later use.
#
function GetHostEntryCallback($ar)
{
$ioContext = $ar.AsyncState;
$ioContext.IPs = [System.Net.Dns]::EndGetHostEntry($ar);
$GetHostEntryFinished.Set();
}
#
# Determine the Internet Protocol (IP) addresses for
# this host asynchronously.
#
function DoGetHostEntryAsync($hostname)
{
#
$ioContext = [ResolveState]::new($hostname)
#
#
$GetHostEntryFinished.Reset();
#
[System.Net.Dns]::BeginGetHostEntry($ioContext.host, `
[AsyncCallback]$function:GetHostEntryCallback, $ioContext);
#
# Wait here until the resolve completes (the callback
# calls .Set())
#
$GetHostEntryFinished.WaitOne();
#
Write-Output("EndGetHostEntry($($ioContext.host)) returns:");
foreach ($address in $ioContext.IPs.AddressList)
{
Write-Output($address);
}
}
#
# main():
#
DoGetHostEntryAsync "192.168.1.10"
Powershell console was even killed.
What's wrong in the code? It seems I've some memory access error. I need your help.
I cite a part of text message to be clearer:
An error has occurred that was not properly handled. Additional information is shown below. The PowerShell process will exit. Unhandled exception. System.Management.Automation.PSInvalidOperationException: There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: param($ar)