New-pssession - Acces Denied

I have a issue with a script to dele the given path.

It selects the server from a csv file to make a new-pssession.
When I use a single line in a testing situation everything goes well and smooth.
However , the moment I run the full script and it needs to walk through the foreach loop to create a new-pssession I get a “Access Denied ” error.
( at the bottem of this topic)

The Winrm ports /policy’s are not the issue as far as I can tell, because a test connection outside the script, works well.

Perhaps it is simple , easy and straightforward, only I do not see it..

cls

# CSV-bestand met servernaamn
$csvPath = '\\HPOM-ciefs-25-05-25.csv'
$Exportpath = '\\Check-HPOM-path-02-06-25.csv' 

$servers = Import-Csv -Path $csvPath -Delimiter ";" 

#Group the domains to one line each and select only the Header "Name"
$domainlist = $servers.domain |Group-Object $_.domain |select -ExpandProperty name


#check for the servers to be found in AD
$NotFound = @()
     foreach($line in $servers){
     $server = $line.naam
     $domain = $line.domain

    $ADServer = Get-ADComputer $server -Server $domain -ErrorAction SilentlyContinue

    If(!$ADServer) {
    $Notfound += [pscustomobject]@{
     Server = $Server
     Domain = $domain
      }}}
       
              
# Ask for domain credentials and store for re-use
$credstore = @{}
foreach($domain in $domainlist) {
    # ask creadential
    $credential = Get-Credential -Message  "geeft credential voor domain $($domain)"
    if(-not($credential)) {
        # skip
    }
    # store credential
    $credstore[$domain] = $credential
}


#Start Scriptblok testpath#
     #Path HPOM  
     $testHPOM = {
            Test-Path -Path "C:\Program Files\HP\HP BTO Software"
            }

     #Path CissServ
     $testCisserv = {
            Test-Path -Path "C:\Program Files\HP\CISSSERV"
            }
         
#Start Scriptblock remove HPOMPath
        $RemoveHPOM = { 
             Remove-Item -Path "C:\Program Files\HP\HP BTO Software" -Recurse -Force 
             }
                        

# Resultaten opslaan
$result = @()

foreach ($server in $servers) {
    $serverInfo = [ordered]@{
        'servernaam'       = $server.ServerNaam
        'Fysiek\Virtueel'  = $server.fv
        'HPOMpath'         = ''
        'CISpath'          = ''
        'HPOMPadVerwijderd'= ''
        'CisServbehouden'  = ''

                 }

        $domain = $server.domain
    $cred = $credstore[$domain]
    

    try {
        Write-verbose -verbose "Processing: $($Server.servernaam)"

        # Verbinding maken met de server
        $session = New-PSSession -ComputerName $Server.servernaam -ErrorAction Stop -Credential $cred
               
        # Bestaan van paden controleren
        $Path_HPOV = Invoke-command -ComputerName $Session -ScriptBlock $testHPOM
        $serverInfo['HPOMpath'] = if ($Path_HPOV )  { 'Bestaat' } else { 'Niet Gevonden' }

        $CisServPath = Invoke-Command -ComputerName $Session -ScriptBlock $testCisserv
        $serverInfo['CISpath'] = if ($CisServPath ) { 'Bestaat' } else { 'Niet gevonden' }

        #Remove HPOM Path
        $HPOM_Remove= if($Path_HPOV -eq $True) {
                  Invoke-Command -ComputerName $Session -ScriptBlock $RemoveHPOM
                  } else { 
                  Write-Warning "Pad HPOM is niet gevonden"
                   }

        $CheckHPOM = Invoke-command -ComputerName $Session -ScriptBlock $testHPOM
        $serverInfo['HPOMPadVerwijderd'] = if ($CheckHPOM)  { 'Bestaat' } else { 'Verwijderd' }

        $CheckCis = Invoke-Command -ComputerName $Session -ScriptBlock $testCisserv
        $serverInfo['CisServbehouden'] = if ($CisServPath -and $server.fv -eq "F") { 'Bestaat' } else { 'NvT' }
                                  
        # Sessies sluiten
        Remove-PSSession -Session $session
    } catch {

        Write-Host "Fout bij het verbinden met $($server.servernaam): $_"
    }

    $result += New-Object PSObject -Property $serverInfo
}

# Resultaten weergeven in een tabel
$result | Format-Table -AutoSize

# Resultaten opslaan in een CSV-bestand
#$result | Export-Csv -Path $Exportpath -NoTypeInformation

Error message:
Connecting to remote server “serversname” failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic”

Your code seems a little convoluted to me. Do you really run this against multiple servers in multiple domains?
I’d try to get an account able to access all tartget computers at once.

You’re using the variable $Server in two different contexts. Could this cause an issue fopr you?

For the future: please format error messages or console output as code as well.

Thanks in advance

Are we sure this code even works? Invoke-Command with a -Computername should error out if given a session since it’s expecting a string. Instead it should be
Invoke-Command -Session $yourPSSession...

2 Likes

Great catch :+1: … I missed that … :man_shrugging:

Thx , I will check it out.

Strange though (I think)

The script loops through multiple domains.

The ’ acces denied’ occurs in the remote domains.

If the - computername is a issue, I would expect it would also produce a error in the “Starting domain” .

This code definately works.

It is possible that even if it works, it creates unexpected issues.

I will look into you’re suggestion.

Thankx

The solution was indeed the - session $session parameter.

After changing this the “Acces denied” error was gone.

thanx for the right direction :folded_hands: