0

我对“New-PSDrive -Root”有疑问

当我尝试使用数组映射 New-PSDrive -Root $patch 和 $path 时,cmd 不会映射驱动器但给我一个错误:“找不到网络路径”。

如果我在 Windows 中使用资源管理器,则该路径有效。

我该如何解决?

非常感谢

例子:

foreach ($s in $serverlist) 
{
    $path = "\\$s\e$\Updates\file\
    New-PSDrive -Name "S" -Root $path -Persist -PSProvider "FileSystem" -Credential $cred
}

问题

这是整个脚本:

Get-Date -Format "dddd MM/dd/yyyy HH:mm K">> "C:\file\results.txt"
$cred = Get-Credential -Credential domain\name

$serverlist = @(get-content -Path "C:\file\serverlist.txt") 
foreach ($s in $serverlist) 
{
    $path = "\\$s\e$\Updates\file\"
    New-PSDrive -Name "S" -Root $path -Persist -PSProvider "FileSystem" -Credential $cred
    $path2 = "\\$s\e$\Updates\file\errors.txt"
    $file = Get-Content $path2
    $containsWord = $file | %{$_ -match "0"}
    if ($containsWord -contains $true) {
        Out-File -FilePath  "C:\file\results.txt" -Append -InputObject "$s : ok"
    } else {
        Out-File -FilePath  "C:\file\results.txt" -Append -InputObject "$s : nok"
    }
    Remove-PSDrive -Name "S"
}

编辑1:如果我尝试通过具有相同凭据的Windows资源管理器直接访问该文件,然后我运行脚本,它就可以工作

4

1 回答 1

0

正如所评论的,用户$cred可能有权访问服务器上路径中的文件,但您似乎没有。

尝试使用Invoke-Command,您可以使用与您自己的凭据不同的凭据执行脚本块:

$cred = Get-Credential -Credential domain\name

$serverlist = Get-Content -Path "C:\file\serverlist.txt"
# loop through the list of servers and have these perform the action in the scriptblock
$result = foreach ($s in $serverlist) {
    Invoke-Command -ComputerName $s -Credential $cred -ScriptBlock {
        # you're running this on the server itself, so now use the LOCAL path
        $msg = if ((Get-Content 'E:\Updates\file\errors.txt' -Raw) -match '0') { 'ok' } else { 'nok' }
        # output 'ok' or 'nok'
        '{0} : {1}' -f $env:COMPUTERNAME, $msg
    }
}

# write to the results.txt file
# change 'Add-Content' in the next line to 'Set-Content' if you want to create a new, blank file
Get-Date -Format "dddd MM/dd/yyyy HH:mm K" | Add-Content -Path 'C:\file\results.txt'
$result | Add-Content -Path 'C:\file\results.txt'

实际上,您甚至不需要 foreach 循环,因为参数-ComputerName可以接收服务器名称数组:

$result = Invoke-Command -ComputerName $serverlist -Credential $cred -ScriptBlock {
    # you're running this on the server itself, so now use the LOCAL path
    $msg = if ((Get-Content 'E:\Updates\file\errors.txt' -Raw) -match '0') { 'ok' } else { 'nok' }
    # output 'ok' or 'nok'
    '{0} : {1}' -f $env:COMPUTERNAME, $msg
}
于 2021-11-26T16:26:07.877 回答