从 CSV 文件中读取值并存储在 PowerShell 中的局部变量中

Reading values from CSV files and storing in local variable in PowerShell

我卡在了一点,要求是我必须将用户名、密码、主机名和主机密钥存储在一个 CSV 文件中,我必须读取并将这些值存储在可用于建立 SFTP 的本地变量中连接。

我的 CSV 如下所示:

HostName,Username,Password,SshHostKeyFingerprint
abc.com,Lear,qwert,ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx...

我用来读取和存储不同列值的代码是:

Add-Type -Path "WinSCPnet.dll"

$csv = Import-Csv c:\test\output.csv
$csv | ForEach-Object
{
    $Hostname = $_.hostname
    $username = $_.username
    $Password = $_.Password
    "$Hostname - $username -$Password"
}

# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = $Hostname
    UserName = $username
    Password = $Password
    SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
}

尝试显示值时未显示任何内容。

ForEach-Object cmdlet 之后的脚本块必须在同一行开始。否则 PowerShell 不会将它们连接在一起。

$csv | ForEach-Object {
    $HostName = $_.HostName
    $Username = $_.Username 
    $Password = $_.Password
    "$HostName - $Username - $Password"
}

您最终将面临的另一个问题是您的代码只处理 CSV 文件中的最后一行。

您很可能实际上想要在 ForEach-Object 脚本块中处理解析出的值 。像这样:

$csv | ForEach-Object {
    $HostName = $_.HostName
    $Username = $_.Username 
    $Password = $_.Password

    "$HostName - $Username - $Password"

    # Set up session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = $HostName
        UserName = $Username
        Password = $Password
        SshHostKeyFingerprint = ...
    }

    # ...
}