1

我正在尝试在当前目录中输出 CSV,但在与 $ComputerName 匹配的文件夹中,该文件夹已经存在。我定期为机器列表执行此操作,而不是手动将它们放在他们的文件夹中,在脚本中执行此操作会很棒。

这是当前代码,写入脚本目录。

#writing file to 
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath 
Write-Host ("Saving CSV Files at " + [Environment]::CurrentDirectory + " Named the following.")
Write-Host $PritnersFilename

我尝试将 $ComputerName 添加到各个位置,但没有运气。

例子:

Write-Host ("Saving CSV Files at " + [Environment]::CurrentDirectory\$ComputerName + " Named the following.")
Write-Host ("Saving CSV Files at " + [Environment]::(CurrentDirectory\$ComputerName) + " Named the following.")

编辑: $ComputerName 是目标的变量,而不是本地主机

4

2 回答 2

1

[Environment]::CurrentDirectory\$ComputerName,由于在里面(...),作为算子的操作数+,被解析为表达式模式,导致语法错误

有关 PowerShell 解析模式的概述,请参阅我的这个答案

您需要"..."(可扩展的字符串)执行字符串连接,使用子表达式运算符$(...)嵌入表达式[Environment]::CurrentDirectory并直接嵌入对变量的引用$ComputerName

"$([Environment]::CurrentDirectory)\$ComputerName"

有关 PowerShell 中字符串扩展(字符串插值)的概述,请参阅我的这个答案

或者,您也可以使用表达式 with+(甚至混合使用这两种方法):

# Enclose the whole expression in (...) if you want to use it as a command argument.
[Environment]::CurrentDirectory + '\' + $ComputerName

注意:构建文件系统路径的最可靠(尽管速度较慢)的方法是使用Join-Pathcmdlet

# Enclose the whole command in (...) to use it as part of an expression.
Join-Path ([Environment]::CurrentDirectory) $ComputerName

注意需要(...)around[Environment]::CurrentDirectory以确保它被识别为一个表达式。否则,由于命令是在参数模式下解析的,[Environment]::CurrentDirectory因此将被视为文字

于 2018-03-01T17:22:57.310 回答
1

如果我看到整个代码会更容易。但是我做了一个例子,因为我觉得这样解释会更容易,因为我不知道你从哪里得到你的变量。

非常简单,它循环遍历计算机,如果当前文件夹中没有名为 $computername 的文件夹,它会创建一个。然后,您的导出代码进入将计算机数据导出到我们刚刚创建的文件夹的位置。

关键部分:使用“.\”与当前文件夹相同。

cd C:\Scriptfolder\

# computer variables for example
$computers = @()
$computers += "HOST1"
$computers += "HOST2"
$computers += "HOST3"

# looping through all objects
Foreach($computer in $computers){

    # creating folder named after computername if one doesn't exist
    if(!(Test-Path ".\$computer")){
        New-Item -ItemType Directory -Name $computer -Path ".\"
    }
    # output path with computername in it
    $outputpath = ".\$computer\output.csv"

    # your export code
    $computer | Export-CSV $outputpath
}
于 2018-03-01T17:14:48.783 回答