windows - 如何在 Powershell 中使用 New-Item cmdlet 将 SSH 私钥写入文件?

标签 windows powershell

<分区>

我正在开发一个 Powershell 脚本,它从文件中读取 ssh key 和已知主机并将其写入另一个文件。

我读了 key

$SshPrivateKey = Get-Content 'ssh-keys\id_rsa'

然后我写新文件

New-Item -path $SshKeysDir -Name $SshPrivateKeyFile -Value $SshPrivateKey -ItemType file -force

这适用于公钥。但由于某些奇怪的原因,它不适用于私钥。新文件以

结尾
System.Object[]

作为我目前正在使用的解决方法

$SshPrivateKey > $testpath

正确写入文件。同时将内容写入控制台呈现预期的私钥

Write-Output $SshPrivateKey

最让我困扰的是它适用于其他文件,例如公钥或已知主机。只是不适用于私钥文件。 公钥的工作命令如下所示

New-Item -path $SshKeysDir -Name $SshPublicKeyFile -Value $SshPublicKey -ItemType file -force

我看到的一个区别是公钥是多行与单行的公钥。

任何人都可以阐明这个谜团吗?

最佳答案

这里的问题完全在于您将文件读入变量的方式。

Get-Content 的工作方式(详细 here )是它将文件作为行数组读取。引用以上链接:

It reads the content one line at a time and returns a collection of objects, each of which represents a line of content.

对于单行文件,这最终被简化以便于使用。打印此数组最终会以您期望的方式打印,因为在 Powershell 中打印并不像 New-Item 那样只是将其转换为字符串。

一种简单的检查方法是调用对象的 GetType() 方法:

PS > $singleLineFileContent.GetType();

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

PS > $multiLineFileContent.GetType();

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

所以要解决你的实际问题,你只需要 make sure you read the file as a string properly.也就是说,更喜欢 this answer如果您运行的是 3.0 或更高版本,则为已接受的版本。

关于windows - 如何在 Powershell 中使用 New-Item cmdlet 将 SSH 私钥写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43240488/

相关文章:

powershell - 在自定义 VSTS PowerShell 脚本任务中使用特殊字符

linux - 使用browserfiy的watchify观看多个文件

windows - 更新 Windows 资源管理器中显示的可用空间量

windows - 获取 "netsh dhcp server ..."命令的输出

powershell - 在 PowerShell 中更改第一个输入单词的颜色

powershell - 通过 Cmd 将换行符传递给 PowerShell

c++ - 在进程外调用时 MiniDumpWriteDump 中的访问冲突

windows - 在 PowerShell 中创建 VPN 连接

powershell - 从工作中触发事件

powershell - Powershell:Start-Transcript仅记录命令而不记录结果