【问题标题】:Running Compress-Archive with Read-Host使用 Read-Host 运行 Compress-Archive
【发布时间】:2021-03-25 02:47:42
【问题描述】:

我将从我希望将压缩文件放置在指定路径中的机器上运行脚本。我想从 UNC 路径(从第一个读取主机)压缩文件夹,并将生成的 .zip 文件的副本放入计算机上的指定目录(从第二个读取主机)。

我需要一些帮助,将必要的组件添加到这段 Powershell 代码中(假设我在这里的工作)。

我知道我可以运行类似的东西:

Compress-Archive \\tommc-pc\c$\users\tommc -DestinationPath c:\windows\temp\tommc_windows_home.zip

但我想让它更加用户友好,因此用户将输入要压缩的源路径和文件夹的 UNC 路径,以及 .zip 的完整目标路径和文件名的提示运行脚本的机器上的文件。

能否请您提供一些关于我如何完成此任务的指导?

【问题讨论】:

  • 您回答了自己的问题。您使用Read-Host 设置一个变量以接受两个位置的输入,如下所示:$SourcePath = Read-Host -Prompt "Enter Remote Path" 然后$DestPath = Read-Host -Prompt "Enter Local Path"
  • Compress-Archive $SourcePath -DestinationPath $DestPath。我不熟悉那个 cmdlet,如果它接受远程功能,我会调查。

标签: powershell compress-archive


【解决方案1】:

Compress-Archive 不支持远程计算机上的操作。要远程执行相同的操作,您应该使用Invoke-CommandPS-Session。以下是您可以使用的示例:

Read-host -assecurestring | convertfrom-securestring | out-file C:\path\to\the\file\Credentials_encrypted.txt
$user = "domain\username"
$pass = Get-ChildItem "C:\path\to\the\file\Credentials_encrypted.txt" | ConvertTo-SecureString
$creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $user, $pass

## Below command will execute the command in the remote system. Means that Compress-Archive is now running locally on the remote machine. 
Invoke-Command -ComputerName Remote_Computer_IP -ScriptBlock { Compress-Archive -Path C:\Reference\* -DestinationPath C:\Destination\Destination_file.zip } -credential $cred

## Once the compression is done, you can simply use `copy-item` to pull the same file into your local system. 
Copy-Item -Path \\Remote_Computer_IP\C$\Destination\Destination_file.zip -Destination C:\localsystem\path\destination_file.zip

除此之外,请记住要在远程计算机上调用命令,您需要启用 PSRemoting。所以,请通过我在问题最后的回答:ENABLE-PSRemoting 来查看详细信息。

注意:如果您在脚本块内使用@param并将变量作为-argumentlistInvoke-command中传递,您也可以从外部将源和目标的路径传递到远程计算机中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 2019-05-02
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    相关资源
    最近更新 更多