Я испробовал миллион комбинаций, чтобы исправить и создать нужный мне каталог, и он работает, когда я запускаю PowerShell IDE и когда я запускаю запланированную задачу, но она не выполняется в одночасье при запланированном запуске.
Прямо сейчас, это то, что я делаю, что крайне избыточно, чтобы попытаться уловить проблему.Я не могу сказать, где именно происходит сбой, в моем скрипте, так как он не дает номер строки, но я думаю, что это первоначальное создание директории (см. #Create расположение подпапки). Все, что я могу думать, это то, что это первый раз, когда скрипт запускается в последовательности, и он не завершил создание устаревшего родительского каталога, когда он попадает в субдиректор. Родительский каталог в хорошем форматетакже мудро.
Сообщение об ошибке:
"Alert: Disaster Backup failed on workstation DT2. Error Message: Error in Privilege script. Length error The given path's format is not supported.The given path's format is not supported.The given path's format is not supported.Exception: System.Management.Automation.ItemNotFoundException: Cannot find path 'E:\DisasterBackup\toLoc_2019-01-30\Privileges\Privileges_1_Bak.csv' because it does not exist.
at System.Management.Automation.LocationGlobber.ExpandMshGlobPath(String path, Boolean allowNonexistingPaths, PSDriveInfo drive, ContainerCmdletProvider provider, CmdletProviderContext context)
at System.Management.Automation.LocationGlobber.ResolveDriveQualifiedPath(String path, CmdletProviderContext context, Boolean allowNonexistingPaths, CmdletProvider& providerInstance)
at System.Management.Automation.LocationGlobber.GetGlobbedMonadPathsFromMonadPath(String path, Boolean allowNonexistingPaths, CmdletProviderContext context, CmdletProvider& providerInstance)
at System.Management.Automation.LocationGlobber.GetGlobbedProviderPathsFromMonadPath(String path, Boolean allowNonexistingPaths, CmdletProviderContext context, ProviderInfo& provider, CmdletProvider& providerInstance)
"
Сценарий:
function SQLQueryWriteToFile([string]$SQLquery, [string]$extractFile, [string]$facility)
{
#one last check that the dir exists for destination
$to_loc_final = Split-Path $extractFile
if(-Not (Test-Path $to_loc_final ))
{
write-output " Creating folder $to_loc_final because it does not exist "
$global:ErrorStrings.Add("Creating folder $to_loc_final fourth time ")
New-Item -ItemType directory -Path $to_loc_final -force
if(-Not (Test-Path $to_loc_final )) ##############
{
write-output " Creating folder $to_loc_final because it does not exist second "
$global:ErrorStrings.Add("Creating folder $to_loc_final fifth time ")
New-Item -ItemType directory -Path $to_loc_final -force
if(-Not (Test-Path $to_loc_final ))
{
write-output " Creating folder $to_loc_final because it does not exist third "
$global:ErrorStrings.Add("Creating folder $to_loc_final sixth time ")
New-Item -ItemType directory -Path $to_loc_final -force
}
}
}
[System.Data.SqlClient.SqlConnection] $sqlConnection=$null
[System.Data.SqlClient.SqlCommand] $sqlCmd=$null
try
{
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=sqlm;Database=DB;User ID=user;Password=pw" #db
$sqlConnection.Open()
#Create a SqlCommand object to define the query
$sqlCmd = New-Object System.Data.SqlClient.SqlCommand
$sqlCmd.Connection = $sqlConnection
$sqlCmd.CommandText = $SQLquery
$sqlCmd.Parameters.Add('@facility',$facility)
if($sqlConnection.State -ne 'Open'){
$global:ErrorStrings.Add("Exception: $("Couldn't connect to DB with connection string given");; ")
} #if
elseif($sqlConnection.State -eq 'Open'){
#create a SqlAdapter that actually does the work and manages everything
$sqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$sqlAdapter.SelectCommand = $sqlCmd
$sqlAdapter.SelectCommand.CommandTimeout=300 #set timeout for query execution to 5 minutes (60x5=300)
#create an empty dataSet for the query to fill with its results
$dataSet = New-Object System.Data.DataSet
#execute the query and fill the dataSet (then disconnect)
$sqlAdapter.Fill($dataSet)
$sqlConnection.Close()
#dump the data to csv
$DataSet.Tables[0] | Export-Csv $extractFile ##this is where the path error is first thrown
if($DataSet.Tables[0].Rows.Count -eq 0)
{
$result = ($SQLquery -split '[\n]')[0] #first line of query gives enough identifying info
$global:ErrorStrings.Add("Exception: $("DataSet returned empty results for query $result") ")
} #if
} #elseif
}#try
catch
{ ##I found out this is where the error is caught about path in question title
$tempMsg = "caught an error in SQL Query method:" + $_.Exception.Message
$global:ErrorStrings.Add($tempMsg)
}
finally
{
if($sqlConnection -ne $null)
{
$sqlConnection.Close()
$sqlConnection.Dispose()
}
} #finally
}
#create dated folder to put backup files in
function CreateDatedFolder([string]$name){
$datedDir = ""
$datedDir = "$name" + "_" + "$((Get-Date).ToString('yyyy-MM-dd'))"
New-Item -ItemType Directory -Path $datedDir
return $datedDir
}
################################## start here #########################################################################
$SQLquery_Privilege = @"
SELECT *
FROM "TABLEName
WHERE
Status in ('Active')
and Facility = @facility
and Last not like ('%test%')
and Last not like ('%Test%')
--ORDER BY Last
"@
$parentDirBaseName = "E:\DisasterBackup\toLoc"
$toLocParent = CreateDatedFolder $parentDirBaseName
$to_loc_final = Join-Path -Path $toLocParent -ChildPath "Privileges"
#create sub-folder location
if(-Not (Test-Path $to_loc_final ))
{
write-output " Creating folder $to_loc_final because it does not exist "
$global:ErrorStrings.Add("Creating folder $to_loc_final first time ")
New-Item -ItemType directory -Path $to_loc_final -force
if(-Not (Test-Path $to_loc_final ))
{
write-output " Creating folder $to_loc_final because it does not exist second "
$global:ErrorStrings.Add("Creating folder $to_loc_final second time ")
New-Item -ItemType directory -Path $to_loc_final -force
if(-Not (Test-Path $to_loc_final ))
{
write-output " Creating folder $to_loc_final because it does not exist third "
$global:ErrorStrings.Add("Creating folder $to_loc_final third time ")
New-Item -ItemType directory -Path $to_loc_final -force
}
}
}
$global:IT = "\\DRIVE\IT\DisasterRecovery\Privileges\"
$global:ErrorStrings = New-Object System.Collections.Generic.List[System.String]
$extractFiles = @("Privileges_0_Bak.csv","Privileges_1_Bak.csv","Privileges_2_Bak.csv")
$facCode = @("H0","H1","H2")
#Loop through list of files and facilities for Practitioner Privileges
for($i=0; $i -lt ($facCode.Length); $i++) {
$tempToLoc = Join-Path -Path $to_loc_final -ChildPath $extractFiles[$i]
SQLQueryWriteToFile $SQLquery_Privilege $tempToLoc $facCode[$i]
}
[string] $errorCodeAsString = ""
foreach ($item in $global:ErrorStrings){
$errorCodeAsString += $item
}
if($errorCodeAsString -ne "")
{
$errorCodeAsString = [string]$errorCodeAsString
$errorCodeAsString = "Error in Privilege script. Length error $errorCodeAsString.length " + $errorCodeAsString
$ScriptPath = Split-Path $MyInvocation.InvocationName
$ScriptPathFilename = Join-Path -Path $ScriptPath -Child "\EmailAlertFailure.ps1"
& $ScriptPathFilename $errorCodeAsString
Exit 99
}
Exit 0
Я смотрел на формат пути не поддерживается , но яу меня нет пути: в моем каталоге dir, кроме c: или e :, что нормально.
Например, вчера вечером был каталог toLoc:
'E:\DisasterBackup\toLoc_2019-01-30\Privileges
Когда я смотрю, E: \ DisasterBackup \ toLoc_2019-01-30 есть, а привилегий dir нет.Это единственный скрипт, который у меня не получается создать в этой папке его subdir, и он делает это так же.Сегодня я скопировал код точно (для создания каталога), чтобы убедиться, что он был таким же.Он отлично работает в IDE и запускает запланированное задание, но я гарантирую, что сегодня вечером у меня будут те же сообщения об ошибках для сценария резервного копирования Privilege.Я проверил, и имя скрипта является правильным в диспетчере задач, что я ожидал, так как он запускается, когда я запускаю его вручную.Запланированный запуск ночью имеет ошибку, указанную выше, в результате чего запись файла SQL завершается с ошибкой, потому что нет подкаталога.Любые идеи?
Обновление Я выяснил, где ошибка пути выбрасывается и перехватывается.См. Добавленные ## комментарии в функции SQLQueryWriteToFile.