Invoke-webrequest error - the underlying connection was closed

Hi all,

I have a requirement like test the url in the remote server from local.
I have used invoke-webrequest inside the invoke -command. But it’s not working. Can anyone help me.
$sessionOption = New-PsSessionOption –SkipCACheck -SkipCNCheck
$session = New-PsSession -ComputerName $source -UseSSL -SessionOption $sessionOption -Credential $cred -ErrorAction Continue

If($session -ne $null) {

$response = Invoke-Command -Session $session -ScriptBlock {
Invoke-WebRequest -URI $using:Uri

The code you’ve provided seems to be attempting to test a URL on a remote server from a local machine using PowerShell’s remoting capabilities. The primary issue in the code is that it’s not defining the variable $using:Uri correctly, and there’s also a potential issue with the way the session is created.

# Define the URL you want to test
$Uri = ""  # Replace with your desired URL

# Define the session options and credentials
$sessionOption = New-PSSessionOption –SkipCACheck -SkipCNCheck
$cred = Get-Credential  # Replace with your credentials
$source = "RemoteServerNameOrIP"  # Replace with the remote server's name or IP address

# Create a remote PowerShell session
$session = New-PSSession -ComputerName $source -UseSSL -SessionOption $sessionOption -Credential $cred -ErrorAction Continue

# Check if the session was created successfully
If ($session -ne $null) {
    try {
        # Execute the web request on the remote server
        $response = Invoke-Command -Session $session -ScriptBlock {
            param (
            Invoke-WebRequest -URI $Uri
        } -ArgumentList $Uri

        # Output the response
    catch {
        Write-Host "Error: $_"
    finally {
        # Close the session
        Remove-PSSession $session
else {
    Write-Host "Failed to create the remote session."