【问题标题】:WriteAllBytes method throws error in Windows Power Shell version 2.0WriteAllBytes 方法在 Windows Powershell 2.0 版中引发错误
【发布时间】:2018-04-12 02:02:38
【问题描述】:

我是 powershell 的新手,在遍历目录中具有特定扩展名的文件名之后,我试图解析 WriteAllBytes 方法中的值。我收到错误“使用“2”参数调用“WriteAllBytes”的异常:“空路径名不合法。”

目标是读取主机中的文件名和文件内容,并在远程系统的不同目录下创建具有相同名称和内容的文件。

以下是我正在使用的示例代码。非常感谢您提出宝贵的建议。

    #Powershell Version 2.0     
    $path = $Env:userprofile+"\AppData\Local\Temp\Test_Data\"

    $servers = @("server.xyz")
    foreach($server in $servers) 
    {
            $username = 'TestUser'
            $password = 'TestPassword'
            $pw   = ConvertTo-SecureString $password -AsPlainText -Force
            $cred = New-Object Management.Automation.PSCredential ($username, $pw)

            foreach ($file in Get-ChildItem $path -Filter *.txt)
            {
                $TextFileName = $file.Name

                $FileToCreateCopyInRemote = "D:\Logs\" + $TextFileName

                $myfile = [System.IO.File]::ReadAllBytes($path+$file)
                $s = New-PSSession -computerName $server -credential $cred

                Enter-PSSession $s
                Invoke-Command -Session $s -ArgumentList $myfile -Scriptblock {[System.IO.File]::WriteAllBytes($FileToCreateCopyInRemote, $args)} 
                Remove-PSSession $s
            }
    }
    Write-Host "Completed"

注意: 调用命令 -Session $s -ArgumentList $myfile -Scriptblock {[System.IO.File]::WriteAllBytes("D:\Logs\Dest.txt", $args)}

这种方法在远程系统中创建单个文件,但我必须在 Dest.txt 的位置解析每个文件名值

【问题讨论】:

    标签: powershell-2.0


    【解决方案1】:

    你必须真正了解PowerShell远程,我建议你执行Get-Help about_Remote_Troubleshooting

    在这里,我认为您只需要将文件从一台机器复制到另一台机器。 您只需要使用Copy-Item cmdlet。

    Copy-Item -Path c:\localPath\File.txt -Destination \\Server\c$\RemotePath\ -Force
    

    如果当前运行的用户无权访问,请将目标路径映射为 PSDrive 并使用相同的复制命令,这是必需的,因为 Copy-Item cmdlet 不支持凭据。

    $username = 'TestUser'
    $password = 'TestPassword'
    $pw   = ConvertTo-SecureString $password -AsPlainText -Force
    $cred = New-Object Management.Automation.PSCredential ($username, $pw)
    
    New-PSDrive -Root \\Server\c$\RemotePath -Name T -PSPRovider FileSystem -Credential $Cred
    
    Copy-Item -Path c:\localPath\File.txt -Destination \\Server\c$\RemotePath\ -Force
    

    您在此处使用的远程处理方法不正确。 Enter-PSSession 只能用于交互式远程处理,不能在脚本中使用。脚本将始终使用Invoke-Command

    【讨论】:

    • 您好 Prasoon,我没有将远程目标路径映射为 PSDrive 或管理员共享。但我在本地和远程都拥有本地管理员权限。所以,我使用 Invoke command 方法和 Write all bytes 方法。你能推荐一下吗?
    • 我通过 Chollid 解决方案使用了上​​述方法,该方法适用于单个文件。 stackoverflow.com/questions/27719439/…
    • 如果你有访问权限,那么你可以直接使用copy-item而不用映射作为驱动器
    猜你喜欢
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 2012-09-25
    相关资源
    最近更新 更多