输入PSSession with Variable for ComputerName

时间:2017-07-17 15:09:19

标签: powershell foreach

我正在尝试使用先前定义的-Computername $Server输入PSSession,但我似乎无法使其工作。

我在变量周围尝试过单引号,双引号和引号。我做错了什么?

$Servers = Import-Csv "C:\Users\username\Desktop\DNS.csv"
$secpass = ConvertTo-SecureString 'mypassword' -AsPlainText -Force
$myCred = New-Object System.Management.Automation.PSCredential("username", $secpass)

foreach ($Object in $Servers) {
    $Server = $Object.Name

    Enter-PSSession -ComputerName "$Server" -Credential $myCred
    sl HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters
    Invoke-Command -ScriptBlock {Get-Item -Path HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters}
    Exit-PSSession
}

enter image description here

2 个答案:

答案 0 :(得分:1)

We use enter pssession for creating an interactive session with the remote computer.

In your case, you do not need to have an interaction with the remote system. You just need to fetch the details from the remote systems which are present in the csv file.

So, Instead of this:

foreach($Object in $Servers) {

$Server = $Object.Name

Enter-PSSession -ComputerName "$Server" -Credential $myCred

    sl HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters

        Invoke-Command -ScriptBlock {Get-Item -Path HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters}

Exit-PSSession

}

Do This:

foreach($Object in $Servers) 
{
$Server = $Object.Name
Invoke-Command -ComputerName $Server -ScriptBlock {Get-Item -Path HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters} -Credential $myCred
}

Note: I believe you have enabled PSRemoting and have edited trusted hosts.

答案 1 :(得分:0)

ComputerName的{​​{1}}参数将接受一系列服务器,因此您可以完全取消foreach循环并简化代码:

Invoke-Command