WriteAllBytes方法在Windows Power Shell 2.0版中引发错误

时间:2018-04-11 07:10:55

标签: powershell-v2.0

我是PowerShell的新手,在循环浏览目录中具有特定扩展名的文件名后,尝试解析WriteAllBytes方法中的值。我收到错误'异常调用'WriteAllBytes“和”2“参数:”空路径名称不合法。“'

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

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

    #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"

注意: Invoke-Command -Session $ s -ArgumentList $ myfile -Scriptblock {[System.IO.File] :: WriteAllBytes(“D:\ Logs \ Dest.txt”,$ args)}

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

1 个答案:

答案 0 :(得分:0)

您必须真正了解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