【问题标题】:powershell one liner to download file with credentialspowershell 一班轮下载带有凭据的文件
【发布时间】:2017-07-12 20:42:03
【问题描述】:

我目前正在尝试指示新创建的 Windows shell 通过 autounattend.xml 文件下载 powershell 脚本。使用这种技术,我需要一个班轮来完成工作。

我以前可以使用这种单线从公共环境下载它们:

<Path>powershell -NoLogo -Command "((new-object System.Net.WebClient).DownloadFile('https://some.remote.public.location/myfile.ps1', 'c:\Windows\Temp\myfile.ps1')"</Path>

但现在我需要提供适当的凭据才能从私人位置下载我的文件。我尝试了以下方法,但它不起作用:

<Path>powershell -NoLogo -Command "((new-object System.Net.WebClient).Credentials = new-object System.Net.NetworkCredential("user123", "password123")).DownloadFile('https://some.remote.private.location/myfile.ps1', 'c:\Windows\Temp\myfile.ps1')"</Path>

(我是powershell的菜鸟:/)

我怎样才能在一行中为 DownloadFile 方法提供正确的凭据?

或者还有其他更适合这项工作的命令吗?

谢谢。

【问题讨论】:

    标签: windows powershell automation


    【解决方案1】:

    如果您使用的是 PowerShell 3.0 或更新版本,您可以试试这个:

    <Path>powershell -NoLogo -Command "Invoke-WebRequest -Uri 'https://some.remote.private.location/myfile.ps1' -OutFile 'c:\Windows\Temp\myfile.ps1' -UseBasicParsing -Credential (New-Object PSCredential('user123', (ConvertTo-SecureString -AsPlainText -Force -String 'password123')))"</Path>
    

    在 PowerShell 2.0 中:

    <Path>powershell -NoLogo -Command "$webClient = new-object System.Net.WebClient; $webClient.Credentials = new-object System.Net.NetworkCredential('user123', 'password123'); $webClient.DownloadFile('https://some.remote.private.location/myfile.ps1', 'c:\Windows\Temp\myfile.ps1')"</Path>
    

    【讨论】:

    • 嗨。感谢您的快速回复。我怎么知道我正在使用哪个 powershell? (顺便说一下,它与 windows server 2012 R2 一起使用)。我也可以将此命令与“-EncodedCommand”一起使用吗?谢谢。
    • @Quardah Server 2012 R2 预装了 PowerShell 4.0 版(您可以通过打印$PSVersionTable 变量查看版本)。是的,您可以对这个命令进行编码并将其传递给-EncodedCommand
    • 非常非常感谢乔治,我非常感谢您的帮助。祝你有美好的一天!
    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2013-08-05
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多