variables - 带变量的 Powershell 复制文件

标签 variables powershell

我正在尝试运行我认为非常简单的以下脚本。我在这里干什么……

[Environment]::UserName = $username

Write-Host "The user is $username"
$from = "c:\Users\" + $username + "\favourites\*.*" 
$to = "c:\test"

Write-Host "This is from dir: $from"
Write-Host "This is to dir: $to"

Copy-Item $from $to

脚本似乎不喜欢 + $username + ...

最佳答案

我认为你的第一行写错了。目前,您正在将一个空变量(它的值应该是 $null)分配给 $Env:UserName,从而覆盖用户名,而不是读取它。

我觉得应该是

$username = [Environment]::Username

或者,如上所述,您可以通过特殊的 Env: 驱动器访问环境变量:

$username = $Env:Username

与您的问题无关,只是更好的代码问题:

  1. 您可以将用户名直接放入字符串中(您似乎知道这一点,如上一行所示 - 不过在这种情况下您不需要字符串):

    $from = "C:\Users\$username\favourites\*"
    
  2. 你根本不需要获取用户名,你可以使用

    $Env:UserProfile
    

    [Environment]::GetFolderPath([Environment+SpecialFolder]::UserProfile)
    

    甚至

    [Environment]::GetFolderPath([Environment+SpecialFolder]::Favorites)
    

    这可能最终就是您想要的,在这里。

关于variables - 带变量的 Powershell 复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9937371/

相关文章:

powershell - 如何使用 azure CLI 和 power shell 脚本实现自动登录,无需用户交互从 VSTS 进入 azure 门户

c++ - char *name 和 char* name 有什么区别?

谁能解释一下C语言中的变量声明

vba - 循环遍历行并将单元格值存储为变量以运行公式,最终结果在另一个单元格中

电源外壳 : The given path's format is not supported

powershell - 使用PowerShell创建类库并将其添加到解决方案

powershell - 使用安装包时是否跳过确认?

ruby - 如何将类名作为变量传递给ruby中的另一个类

javascript - 通过动态变量访问 Json 值

c# - 有没有办法在不使用 System.Management.Automation 的情况下捕获 powershell 脚本执行的输出