从批处理文件中调用以下脚本;一切都有效,除了'Get-ChildItem';这是最重要的部分。不知道为什么我能够创建文件夹和文件,但我不能遍历目录。我拥有该机器的管理员权限;我在批处理中使用'-NoProfile -ExecutionPolicy Bypass',我也拥有文件夹的完全权限。
给我带来麻烦的一行是:$ files = Get-ChildItem $ uploadFilePath错误输出后,它会错误地抛出其余的脚本。
我是PowerShell的业余爱好者;我设法将弗兰肯斯坦这个剧本一起用于其他多个例子;如果你看到任何看起来错误的东西,请原谅我。
非常感谢任何建议!
批处理文件:
set sninstancename=NAMEHERE
set snsuthorization=AUTHERE
set snstagingtable=TABLEHERE
set snrecordlimit=100
powershell -NoProfile -ExecutionPolicy Bypass -file "_sn_upload_files.ps1" -sninstancename "%sninstancename%" -snsuthorization "%snsuthorization%" -snstagingtable "%snstagingtable%" -snrecordlimit "%snrecordlimit%"
PS脚本:
<# Set global variables #>
param (
[string]$sninstancename,
[string]$snsuthorization,
[string]$snstagingtable,
[string]$snrecordlimit
);
$bulkUploadCount = 0;
$createBulkRecord = "true";
$bulkRecordSysID = "";
$bulkRecordNumber = "";
$logFileFolderName = Get-Date -format "yyyyMMdd";
$logFolderPath = "$($PSScriptRoot)\$($logFileFolderName)";
$uploadFilePath = "";
$sninstanceurl = "https://$($sninstancename).service-now.com/";
$snstagingurlpostfix = "api/now/table/$($snstagingtable)";
$snuploadapipostfix = "ecc_queue.do?JSONv2&sysparm_action=insert";
function makelog-folder () {
$logFolderExists = Test-Path "$logFolderPath";
if ($logFolderExists -eq $False) {
New-item "$logFolderPath" -type directory | Out-Null
}
}
function welcome-prompt () {
Write-host "`n";
Write-Host "ServiceNow - PowerShell Bulk Upload Utility. Version 1.0";
Write-host "`n";
Write-host "Please Enter the full file-path for the files you wish to upload.";
Write-host "Target files should not be in the same directory as PowerShell Script";
Write-host "`n";
$filePath = Read-Host -Prompt "Path";
$filePathExists = Test-Path "$filePath";
if ($filePathExists -eq $True) {
return $filePath
} else {
Write-host "The file-path: $($filePath) is invalid. ";
Write-host "Push any key to exit.";
$exit = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
exit;
}
}
function Get-MimeType() {
param([parameter(Mandatory=$true, ValueFromPipeline=$true)][ValidateNotNullorEmpty()][System.IO.FileInfo]$CheckFile)
begin {
Add-Type -AssemblyName "System.Web"
[System.IO.FileInfo]$check_file = $CheckFile
[sting]$mime_type = $null
}
process {
if ($check_file.Exists) {
$mime_type = [System.Web.MimeMapping]::GetMimeMapping($check_file.FullName)
}
else {
$mime_type = "false"
}
}
end { return $mime_type }
}
function create-staging-table(){
if ($sninstancename -And $snsuthorization -And $snstagingtable) {
$uri = "$($sninstanceurl)$($snstagingurlpostfix)";
$headers = @{"Authorization"=$snsuthorization};
try {
$answer = Invoke-RestMethod -Uri "$($uri)" -ContentType "application/json" -Method Post -Headers $headers;
if ($answer.result.number) {
$bulkRecordNumber = $answer.result.number;
$answer.result | ConvertTo-Json -depth 999 -Compress | Out-file "$($logFolderPath)\$($bulkRecordNumber).txt" -Encoding ASCII;
return $answer.result.sys_id;
}
} catch {
<#
$errorhandle = @{"Message"="Error";"StatusCode"=$_.Exception.Response.StatusCode.value__;"Description"=$_.Exception.Response.StatusDescription;"File"=$fileName}
$errorhandle | ConvertTo-Json -depth 999 -Compress | Out-file "$snlogfile" -Encoding ASCII -append
#>
Write-host "error";
Write-host "Push any key to exit.";
$exit = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
}
} else {
Write-host "Missing parameters:";
Write-host "Push any key to exit.";
$exit = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
exit;
}
}
function upload-files(){
if ($sninstancename -And $snsuthorization -And $snstagingtable -And $snrecordlimit) {
Write-Output "Transfering Files, please Wait...";
$files = Get-ChildItem $uploadFilePath;
for ($i=0; $i -lt $files.Count; $i++) {
$uri = "$($sninstanceurl)$($snuploadapipostfix)";
$headers = @{"Authorization"=$snsuthorization};
$fileContentEncoded = [convert]::ToBase64String((get-content "$($files[$i].FullName)" -encoding byte));
$mimeType = $(Get-MimeType -CheckFile "$files[$i].FullName");
$jsonbody = @{agent="AttachmentCreator";topic="AttachmentCreator";name="$($files[$i].BaseName)$($files[$i].Extension):$($mimeType)";source="$($snstagingtable):$($bulkRecordSysID)";payload=$fileContentEncoded} | ConvertTo-Json -Compress
Write-host "Uploading $($files[$i].FullName)";
Write-host "Please wait ...";
try {
$answer = Invoke-RestMethod -Uri "$uri" -ContentType "application/json" -Method Post -Headers $headers -Body $jsonbody;
if ($answer.records) {
$answer.result | ConvertTo-Json -depth 999 -Compress | Out-file "$($logFolderPath)\$($bulkRecordNumber).txt" -Encoding ASCII;
return $answer.result.sys_id;
}
} catch {
#$errorhandle = @{"Message"="Error";"StatusCode"=$_.Exception.Response.StatusCode.value__;"Description"=$_.Exception.Response.StatusDescription;"File"=$fileName}
#$errorhandle | ConvertTo-Json -depth 999 -Compress | Out-file "$snlogfile" -Encoding ASCII -append
Write-host "error";
Write-host "Push any key to exit.";
$exit = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
}
}
} else {
Write-host "Missing parameters:";
Write-host "Push any key to exit.";
$exit = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
exit;
}
}
cls
$(makelog-folder);
$uploadFilePath = $(welcome-prompt);
$bulkRecordSysID = $(create-staging-table);
$(upload-files);
错误:
Path: C:\Users\MYNAME\Desktop\Upload
get-content : Access to the path
'C:\Users\MYNAME\Desktop\Upload\Files are Here' is denied.
At C:\Users\MYNAME\Desktop\PSPOCNEW\_sn_upload_files.ps1:107 char:62
+ $fileContentEncoded = [convert]::ToBase64String((get-content
"$($fil ...
+
~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\Users\nick.g...\Files are
Here:String) [Get-Content], UnauthorizedAccessException
+ FullyQualifiedErrorId : GetContentReaderUnauthorizedAccessError,Microsof
t.PowerShell.Commands.GetContentCommand
Exception calling "ToBase64String" with "1" argument(s): "Value cannot be null.
Parameter name: inArray"
At C:\Users\MYNAME\Desktop\PSPOCNEW\_sn_upload_files.ps1:107 char:77
+ $fileContentEncoded = [convert]::ToBase64String((get-content
"$($fil ...
+
~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
Get-MimeType : Cannot process argument transformation on parameter
'CheckFile'. Cannot convert value "Files are Here OLD File Upload - Copy
(152).pdf File Upload - Copy (153).pdf File Upload - Copy (154).pdf File
Upload - Copy (155).pdf File Upload - Copy (156).pdf File Upload - Copy
(157).pdf File Upload - Copy (158).pdf File Upload - Copy (159).pdf File
Upload - Copy (160).pdf File Upload - Copy (161).pdf File Upload - Copy
(162).pdf File Upload - Copy (163).pdf File Upload - Copy (164).pdf File
Upload - Copy (165).pdf File Upload - Copy (166).pdf File Upload - Copy
(167).pdf File Upload - Copy (168).pdf File Upload - Copy (169).pdf File
Upload - Copy (170).pdf File Upload - Copy (171).pdf File Upload - Copy
(172).pdf File Upload - Copy (173).pdf File Upload - Copy (174).pdf File
Upload - Copy (175).pdf File Upload - Copy (176).pdf File Upload - Copy
(177).pdf File Upload - Copy (178).pdf File Upload - Copy (179).pdf File
Upload - Copy (180).pdf File Upload - Copy (181).pdf File Upload - Copy
(182).pdf File Upload - Copy (183).pdf File Upload - Copy (184).pdf File
Upload - Copy (185).pdf File Upload - Copy (186).pdf File Upload - Copy
(187).pdf File Upload - Copy (188).pdf File Upload - Copy (189).pdf File
Upload - Copy (190).pdf File Upload - Copy (191).pdf File Upload - Copy
(192).pdf File Upload - Copy (193).pdf File Upload - Copy (194).pdf File
Upload - Copy (195).pdf File Upload - Copy (196).pdf File Upload - Copy
(197).pdf File Upload - Copy (198).pdf File Upload - Copy (199).pdf File
Upload - Copy (200).pdf[0].FullName" to type "System.IO.FileInfo". Error:
"The specified path, file name, or both are too long. The fully qualified file
name must be less than 260 characters, and the directory name must be less
than 248 characters."
At C:\Users\MYNAME\Desktop\PSPOCNEW\_sn_upload_files.ps1:108 char:51
+ $mimeType = $(Get-MimeType -CheckFile "$files[$i].FullName");
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-MimeType], ParameterBindin
gArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-MimeTyp
e
答案 0 :(得分:0)
那里有很多代码但是从错误来看,这与PowerShell.exe交换机没有任何关系,更多的是不正确的变量扩展。这里可能存在更多问题,但我会从这开始。
您遇到的问题是您没有正确扩展您的媒体资源。
我看到你将部分的字符串扩展到他们喜欢的地方
$mimeType = $(Get-MimeType -CheckFile "$files[$i].FullName");
Subexpressions $()
对于将代码包装在字符串中非常有用,以确保变量得到正确扩展。在上面的情况下,他们没有必要。
$mimeType = Get-MimeType -CheckFile $files[$i].FullName
虽然在字符串"$files[$i].FullName"
中,但PowerShell无法知道您是从$files
的一个索引元素中提取属性的。所以你会看到整个$files
呈现为字符串,因此有关超出字符串长度的长消息。
你可以在其他地方正确地做到这一点
get-content "$($files[$i].FullName)"
此处不需要子表达式语法,但显示了如何在sting内部进行适当的扩展。
您可以阅读有关this concept on MSDN的更多信息。
答案 1 :(得分:0)
嗯,很明显我的剧本还有其他问题;我确实发现了什么给了我访问被拒绝的错误。我在我的Get-ChildItems行添加了'-file'。看起来像是在拉入目录然后尝试对它们进行编码之前。
所以至少那部分至少是固定的。 :)