如果Get-ChildItem:找不到路径那么连接到其他路径

时间:2013-10-22 12:54:00

标签: powershell unc get-childitem

我试图弄清楚如何编写powershell脚本,如果powershell无法连接到\ 10.10.10.10 \ C $ \ Users,它应该尝试连接到\ 10.10.10.10 \ C $ \ Documents and Settings

到目前为止,我有以下代码

$Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName '10.10.10.10'
$SysDrv = $Win32OS.SystemDrive
$SysDrv = $SysDrv.Replace(":","$")
$ProfDrv = "\\" + '10.10.10.10' + "\" + $SysDrv
$ProfLoc = Join-Path -Path $ProfDrv -ChildPath "User"

try
{
    Get-ChildItem $ProfLoc | ? { $_.PsIsContainer} | Sort LastWriteTime -Descending | Select -expand  Name -First 1
}
catch [Exception]
{
     return "CannotFindLastUser"
}

如果路径\ 10.10.10.10 \ C $ \ Users不存在则会出错

Get-ChildItem : Cannot find path '\\10.10.10.10\C$\Users' because it does not exist.

如何更改代码,使其尝试连接到\ 10.10.10.10 \ C $ \ Documents and Settings,否则会抛出用户友好的消息

修改

以下是整个脚本,其中参数的格式为'sender-ip = 10.10.10.10'

$line_array = @()
$multi_array = @()
[hashtable]$my_hash = @{}
$Sender_IP = $NULL
$Win32OS = $NULL
$Build = $NULL
$folder = $NULL
$SysDrv = $NULL

foreach ($i in $args){
   $line_array+= $i.split(" ")
}

foreach ($j in $line_array){
    $multi_array += ,@($j.split("="))
}

foreach ($k in $multi_array){
    $my_hash.add($k[0],$k[1])
}


$Sender_IP = $my_hash.Get_Item("sender-ip")

try{
    Test-Connection $Sender_IP -count 1 -ErrorAction Stop | out-null
}
catch [Exception]
{
    $userId = "userId=CannotPing"
    return $userId 
}

try{
    $OS = (Get-WmiObject Win32_OperatingSystem -ComputerName $Sender_IP).Name
}
catch [Exception]{
    $userId = "userId=CannotConnectToWMI"
    return $userId
}


$Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Sender_IP
$SysDrv = $Win32OS.SystemDrive
$SysDrv = $SysDrv.Replace(":","$")
$ProfDrv = "\\" + $Sender_IP + "\" + $SysDrv
$ProfLoc = Join-Path -Path $ProfDrv -ChildPath "Users"

try{
    $userId = Get-ChildItem $ProfLoc | ? { $_.PsIsContainer} | Sort LastWriteTime -Descending | Select -expand  Name -First 1
    $userId = "userId="+$userId
    return $userId
}catch [Exception]
{
    $userId = "userId=CannotFindLastUser"
    return $userId
}

1 个答案:

答案 0 :(得分:1)

使用Test-Path cmdlet确定路径是否存在和/或是否可用。

在测试路径之前,您可能希望使用Test-Connection ping服务器。