我正在开发一个 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 或更高版本,则为已接受的版本。