Upload a file using API in PowerShell
AnsweredHello everybody,
I am quite new in BOX api. Trying to accomplish simple task: Upload File, but using PowerShell instead of offered cURL.
# get Token from Registry and refresh if it's expired. It works well, as other requests, like get file info or create folder works fine $TokenObj = Get-ItemProperty -Path $RegKey if ((Get-Date) -ge [datetime]$TokenObj.expires_in){ $TokenObj = Register-BoxApp -AppName $AppName -ClientID $ClientID -ClientSecret $ClientSecret -Mode Refresh } # Prepare Header $headers = @{Authorization = "Bearer $($TokenObj.access_token)"} # This doesn't work $json ="{ ""name"": ""test.txt"", ""parent"": {""id"": ""2***phone number removed for privacy***""}, ""file"": ""$(get-content C:\Temp\Box\test.txt -Enc Byte -raw)""}" Invoke-RestMethod -Headers $headers -Uri 'https://upload.box.com/api/2.0/files/content' -Method Post -Body $JSON -ContentType "multipart/form-data" # This doesn't work either $json = '{"name": "test.txt", "parent":{"id":"0"}, "file":"C:\Temp\Box\test.txt"}' Invoke-RestMethod -Headers $headers -Uri 'https://upload.box.com/api/2.0/files/content' -Method Post -Body $JSON -ContentType "multipart/form-data" # This doesn't work either by Powershell design (Body and InFile self excluding parameters..) $json = '{"name": "test.txt", "parent":{"id":"0"}}' Invoke-RestMethod -Headers $headers -Uri 'https://upload.box.com/api/2.0/files/content' -Method Post -Body $JSON -InFile "C:\Temp\Box\test.txt" -ContentType "multipart/form-data"
Please Advice, if someone knows, HOW to upload file to Box using API in PowerShell?
-
This StackOverflow question has an example showing how to upload a file using PowerShell.
-
Hi Boris,
I was able to use this code in Powershell to upload a file . Do not worry about the first function get-I contenttype. this is just used for getting the contenttype of the file. not100% sure even if we need this.
I hope this works for you as well. You might get error due to bad formatting of "payload". If you do let me know and I will share the file with you.
thanks,
Bibek
code starts here:
cls
#function that returns the content type based on the file extension
function Get-ContentType
{
param([System.IO.FileInfo]$file = $null);
$contentType = $null;
$contentTypeMap = @{
".323"= "text/h323";
".3g2"= "video/3gpp2";
".3gp"= "video/3gpp";
".3gp2"= "video/3gpp2";
".3gpp"= "video/3gpp";
".7z"= "application/x-7z-compressed";
".aa"= "audio/audible";
".AAC"= "audio/aac";
".aaf"= "application/octet-stream";
".aax"= "audio/vnd.audible.aax";
".ac3"= "audio/ac3";
".aca"= "application/octet-stream";
".accda"= "application/msaccess.addin";
".accdb"= "application/msaccess";
".accdc"= "application/msaccess.cab";
".accde"= "application/msaccess";
".accdr"= "application/msaccess.runtime";
".accdt"= "application/msaccess";
".accdw"= "application/msaccess.webapplication";
".accft"= "application/msaccess.ftemplate";
".acx"= "application/internet-property-stream";
".AddIn"= "text/xml";
".ade"= "application/msaccess";
".adobebridge"= "application/x-bridge-url";
".adp"= "application/msaccess";
".ADT"= "audio/vnd.dlna.adts";
".ADTS"= "audio/aac";
".afm"= "application/octet-stream";
".ai"= "application/postscript";
".aif"= "audio/aiff";
".aifc"= "audio/aiff";
".aiff"= "audio/aiff";
".air"= "application/vnd.adobe.air-application-installer-package+zip";
".amc"= "application/mpeg";
".anx"= "application/annodex";
".apk"= "application/vnd.android.package-archive" ;
".application"= "application/x-ms-application";
".art"= "image/x-jg";
".asa"= "application/xml";
".asax"= "application/xml";
".ascx"= "application/xml";
".asd"= "application/octet-stream";
".asf"= "video/x-ms-asf";
".ashx"= "application/xml";
".asi"= "application/octet-stream";
".asm"= "text/plain";
".asmx"= "application/xml";
".aspx"= "application/xml";
".asr"= "video/x-ms-asf";
".asx"= "video/x-ms-asf";
".atom"= "application/atom+xml";
".au"= "audio/basic";
".avi"= "video/x-msvideo";
".axa"= "audio/annodex";
".axs"= "application/olescript";
".axv"= "video/annodex";
".bas"= "text/plain";
".bcpio"= "application/x-bcpio";
".bin"= "application/octet-stream";
".bmp"= "image/bmp";
".c"= "text/plain";
".cab"= "application/octet-stream";
".caf"= "audio/x-caf";
".calx"= "application/vnd.ms-office.calx";
".cat"= "application/vnd.ms-pki.seccat";
".cc"= "text/plain";
".cd"= "text/plain";
".cdda"= "audio/aiff";
".cdf"= "application/x-cdf";
".cer"= "application/x-x509-ca-cert";
".cfg"= "text/plain";
".chm"= "application/octet-stream";
".class"= "application/x-java-applet";
".clp"= "application/x-msclip";
".cmd"= "text/plain";
".cmx"= "image/x-cmx";
".cnf"= "text/plain";
".cod"= "image/cis-cod";
".config"= "application/xml";
".contact"= "text/x-ms-contact";
".coverage"= "application/xml";
".cpio"= "application/x-cpio";
".cpp"= "text/plain";
".crd"= "application/x-mscardfile";
".crl"= "application/pkix-crl";
".crt"= "application/x-x509-ca-cert";
".cs"= "text/plain";
".csdproj"= "text/plain";
".csh"= "application/x-csh";
".csproj"= "text/plain";
".css"= "text/css";
".csv"= "text/csv";
".cur"= "application/octet-stream";
".cxx"= "text/plain";
".dat"= "application/octet-stream";
".datasource"= "application/xml";
".dbproj"= "text/plain";
".dcr"= "application/x-director";
".def"= "text/plain";
".deploy"= "application/octet-stream";
".der"= "application/x-x509-ca-cert";
".dgml"= "application/xml";
".dib"= "image/bmp";
".dif"= "video/x-dv";
".dir"= "application/x-director";
".disco"= "text/xml";
".divx"= "video/divx";
".dll"= "application/x-msdownload";
".dll.config"= "text/xml";
".dlm"= "text/dlm";
".doc"= "application/msword";
".docm"= "application/vnd.ms-word.document.macroEnabled.12";
".docx"= "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
".dot"= "application/msword";
".dotm"= "application/vnd.ms-word.template.macroEnabled.12";
".dotx"= "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
".dsp"= "application/octet-stream";
".dsw"= "text/plain";
".dtd"= "text/xml";
".dtsConfig"= "text/xml";
".dv"= "video/x-dv";
".dvi"= "application/x-dvi";
".dwf"= "drawing/x-dwf";
".dwp"= "application/octet-stream";
".dxr"= "application/x-director";
".eml"= "message/rfc822";
".emz"= "application/octet-stream";
".eot"= "application/vnd.ms-fontobject";
".eps"= "application/postscript";
".etl"= "application/etl";
".etx"= "text/x-setext";
".evy"= "application/envoy";
".exe"= "application/octet-stream";
".exe.config"= "text/xml";
".fdf"= "application/vnd.fdf";
".fif"= "application/fractals";
".filters"= "application/xml";
".fla"= "application/octet-stream";
".flac"= "audio/flac";
".flr"= "x-world/x-vrml";
".flv"= "video/x-flv";
".fsscript"= "application/fsharp-script";
".fsx"= "application/fsharp-script";
".generictest"= "application/xml";
".gif"= "image/gif";
".gpx"= "application/gpx+xml";
".group"= "text/x-ms-group";
".gsm"= "audio/x-gsm";
".gtar"= "application/x-gtar";
".gz"= "application/x-gzip";
".h"= "text/plain";
".hdf"= "application/x-hdf";
".hdml"= "text/x-hdml";
".hhc"= "application/x-oleobject";
".hhk"= "application/octet-stream";
".hhp"= "application/octet-stream";
".hlp"= "application/winhlp";
".hpp"= "text/plain";
".hqx"= "application/mac-binhex40";
".hta"= "application/hta";
".htc"= "text/x-component";
".htm"= "text/html";
".html"= "text/html";
".htt"= "text/webviewhtml";
".hxa"= "application/xml";
".hxc"= "application/xml";
".hxd"= "application/octet-stream";
".hxe"= "application/xml";
".hxf"= "application/xml";
".hxh"= "application/octet-stream";
".hxi"= "application/octet-stream";
".hxk"= "application/xml";
".hxq"= "application/octet-stream";
".hxr"= "application/octet-stream";
".hxs"= "application/octet-stream";
".hxt"= "text/html";
".hxv"= "application/xml";
".hxw"= "application/octet-stream";
".hxx"= "text/plain";
".i"= "text/plain";
".ico"= "image/x-icon";
".ics"= "application/octet-stream";
".idl"= "text/plain";
".ief"= "image/ief";
".iii"= "application/x-iphone";
".inc"= "text/plain";
".inf"= "application/octet-stream";
".ini"= "text/plain";
".inl"= "text/plain";
".ins"= "application/x-internet-signup";
".ipa"= "application/x-itunes-ipa";
".ipg"= "application/x-itunes-ipg";
".ipproj"= "text/plain";
".ipsw"= "application/x-itunes-ipsw";
".iqy"= "text/x-ms-iqy";
".isp"= "application/x-internet-signup";
".ite"= "application/x-itunes-ite";
".itlp"= "application/x-itunes-itlp";
".itms"= "application/x-itunes-itms";
".itpc"= "application/x-itunes-itpc";
".IVF"= "video/x-ivf";
".jar"= "application/java-archive";
".java"= "application/octet-stream";
".jck"= "application/liquidmotion";
".jcz"= "application/liquidmotion";
".jfif"= "image/pjpeg";
".jnlp"= "application/x-java-jnlp-file";
".jpb"= "application/octet-stream";
".jpe"= "image/jpeg";
".jpeg"= "image/jpeg";
".jpg"= "image/jpeg";
".js"= "application/javascript";
".json"= "application/json";
".jsx"= "text/jscript";
".jsxbin"= "text/plain";
".latex"= "application/x-latex";
".library-ms"= "application/windows-library+xml";
".lit"= "application/x-ms-reader";
".loadtest"= "application/xml";
".lpk"= "application/octet-stream";
".lsf"= "video/x-la-asf";
".lst"= "text/plain";
".lsx"= "video/x-la-asf";
".lzh"= "application/octet-stream";
".m13"= "application/x-msmediaview";
".m14"= "application/x-msmediaview";
".m1v"= "video/mpeg";
".m2t"= "video/vnd.dlna.mpeg-tts";
".m2ts"= "video/vnd.dlna.mpeg-tts";
".m2v"= "video/mpeg";
".m3u"= "audio/x-mpegurl";
".m3u8"= "audio/x-mpegurl";
".m4a"= "audio/m4a";
".m4b"= "audio/m4b";
".m4p"= "audio/m4p";
".m4r"= "audio/x-m4r";
".m4v"= "video/x-m4v";
".mac"= "image/x-macpaint";
".mak"= "text/plain";
".man"= "application/x-troff-man";
".manifest"= "application/x-ms-manifest";
".map"= "text/plain";
".master"= "application/xml";
".mda"= "application/msaccess";
".mdb"= "application/x-msaccess";
".mde"= "application/msaccess";
".mdp"= "application/octet-stream";
".me"= "application/x-troff-me";
".mfp"= "application/x-shockwave-flash";
".mht"= "message/rfc822";
".mhtml"= "message/rfc822";
".mid"= "audio/mid";
".midi"= "audio/mid";
".mix"= "application/octet-stream";
".mk"= "text/plain";
".mmf"= "application/x-smaf";
".mno"= "text/xml";
".mny"= "application/x-msmoney";
".mod"= "video/mpeg";
".mov"= "video/quicktime";
".movie"= "video/x-sgi-movie";
".mp2"= "video/mpeg";
".mp2v"= "video/mpeg";
".mp3"= "audio/mpeg";
".mp4"= "video/mp4";
".mp4v"= "video/mp4";
".mpa"= "video/mpeg";
".mpe"= "video/mpeg";
".mpeg"= "video/mpeg";
".mpf"= "application/vnd.ms-mediapackage";
".mpg"= "video/mpeg";
".mpp"= "application/vnd.ms-project";
".mpv2"= "video/mpeg";
".mqv"= "video/quicktime";
".ms"= "application/x-troff-ms";
".msi"= "application/octet-stream";
".mso"= "application/octet-stream";
".mts"= "video/vnd.dlna.mpeg-tts";
".mtx"= "application/xml";
".mvb"= "application/x-msmediaview";
".mvc"= "application/x-miva-compiled";
".mxp"= "application/x-mmxp";
".nc"= "application/x-netcdf";
".nsc"= "video/x-ms-asf";
".nws"= "message/rfc822";
".ocx"= "application/octet-stream";
".oda"= "application/oda";
".odb"= "application/vnd.oasis.opendocument.database";
".odc"= "application/vnd.oasis.opendocument.chart";
".odf"= "application/vnd.oasis.opendocument.formula";
".odg"= "application/vnd.oasis.opendocument.graphics";
".odh"= "text/plain";
".odi"= "application/vnd.oasis.opendocument.image";
".odl"= "text/plain";
".odm"= "application/vnd.oasis.opendocument.text-master";
".odp"= "application/vnd.oasis.opendocument.presentation";
".ods"= "application/vnd.oasis.opendocument.spreadsheet";
".odt"= "application/vnd.oasis.opendocument.text";
".oga"= "audio/ogg";
".ogg"= "audio/ogg";
".ogv"= "video/ogg";
".ogx"= "application/ogg";
".one"= "application/onenote";
".onea"= "application/onenote";
".onepkg"= "application/onenote";
".onetmp"= "application/onenote";
".onetoc"= "application/onenote";
".onetoc2"= "application/onenote";
".opus"= "audio/ogg";
".orderedtest"= "application/xml";
".osdx"= "application/opensearchdescription+xml";
".otf"= "application/font-sfnt";
".otg"= "application/vnd.oasis.opendocument.graphics-template";
".oth"= "application/vnd.oasis.opendocument.text-web";
".otp"= "application/vnd.oasis.opendocument.presentation-template";
".ots"= "application/vnd.oasis.opendocument.spreadsheet-template";
".ott"= "application/vnd.oasis.opendocument.text-template";
".oxt"= "application/vnd.openofficeorg.extension";
".p10"= "application/pkcs10";
".p12"= "application/x-pkcs12";
".p7b"= "application/x-pkcs7-certificates";
".p7c"= "application/pkcs7-mime";
".p7m"= "application/pkcs7-mime";
".p7r"= "application/x-pkcs7-certreqresp";
".p7s"= "application/pkcs7-signature";
".pbm"= "image/x-portable-bitmap";
".pcast"= "application/x-podcast";
".pct"= "image/pict";
".pcx"= "application/octet-stream";
".pcz"= "application/octet-stream";
".pdf"= "application/pdf";
".pfb"= "application/octet-stream";
".pfm"= "application/octet-stream";
".pfx"= "application/x-pkcs12";
".pgm"= "image/x-portable-graymap";
".pic"= "image/pict";
".pict"= "image/pict";
".pkgdef"= "text/plain";
".pkgundef"= "text/plain";
".pko"= "application/vnd.ms-pki.pko";
".pls"= "audio/scpls";
".pma"= "application/x-perfmon";
".pmc"= "application/x-perfmon";
".pml"= "application/x-perfmon";
".pmr"= "application/x-perfmon";
".pmw"= "application/x-perfmon";
".png"= "image/png";
".pnm"= "image/x-portable-anymap";
".pnt"= "image/x-macpaint";
".pntg"= "image/x-macpaint";
".pnz"= "image/png";
".pot"= "application/vnd.ms-powerpoint";
".potm"= "application/vnd.ms-powerpoint.template.macroEnabled.12";
".potx"= "application/vnd.openxmlformats-officedocument.presentationml.template";
".ppa"= "application/vnd.ms-powerpoint";
".ppam"= "application/vnd.ms-powerpoint.addin.macroEnabled.12";
".ppm"= "image/x-portable-pixmap";
".pps"= "application/vnd.ms-powerpoint";
".ppsm"= "application/vnd.ms-powerpoint.slideshow.macroEnabled.12";
".ppsx"= "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
".ppt"= "application/vnd.ms-powerpoint";
".pptm"= "application/vnd.ms-powerpoint.presentation.macroEnabled.12";
".pptx"= "application/vnd.openxmlformats-officedocument.presentationml.presentation";
".prf"= "application/pics-rules";
".prm"= "application/octet-stream";
".prx"= "application/octet-stream";
".ps"= "application/postscript";
".psc1"= "application/PowerShell";
".psd"= "application/octet-stream";
".psess"= "application/xml";
".psm"= "application/octet-stream";
".psp"= "application/octet-stream";
".pub"= "application/x-mspublisher";
".pwz"= "application/vnd.ms-powerpoint";
".qht"= "text/x-html-insertion";
".qhtm"= "text/x-html-insertion";
".qt"= "video/quicktime";
".qti"= "image/x-quicktime";
".qtif"= "image/x-quicktime";
".qtl"= "application/x-quicktimeplayer";
".qxd"= "application/octet-stream";
".ra"= "audio/x-pn-realaudio";
".ram"= "audio/x-pn-realaudio";
".rar"= "application/x-rar-compressed";
".ras"= "image/x-cmu-raster";
".rat"= "application/rat-file";
".rc"= "text/plain";
".rc2"= "text/plain";
".rct"= "text/plain";
".rdlc"= "application/xml";
".reg"= "text/plain";
".resx"= "application/xml";
".rf"= "image/vnd.rn-realflash";
".rgb"= "image/x-rgb";
".rgs"= "text/plain";
".rm"= "application/vnd.rn-realmedia";
".rmi"= "audio/mid";
".rmp"= "application/vnd.rn-rn_music_package";
".roff"= "application/x-troff";
".rpm"= "audio/x-pn-realaudio-plugin";
".rqy"= "text/x-ms-rqy";
".rtf"= "application/rtf";
".rtx"= "text/richtext";
".ruleset"= "application/xml";
".s"= "text/plain";
".safariextz"= "application/x-safari-safariextz";
".scd"= "application/x-msschedule";
".scr"= "text/plain";
".sct"= "text/scriptlet";
".sd2"= "audio/x-sd2";
".sdp"= "application/sdp";
".sea"= "application/octet-stream";
".searchConnector-ms"= "application/windows-search-connector+xml";
".setpay"= "application/set-payment-initiation";
".setreg"= "application/set-registration-initiation";
".settings"= "application/xml";
".sgimb"= "application/x-sgimb";
".sgml"= "text/sgml";
".sh"= "application/x-sh";
".shar"= "application/x-shar";
".shtml"= "text/html";
".sit"= "application/x-stuffit";
".sitemap"= "application/xml";
".skin"= "application/xml";
".sldm"= "application/vnd.ms-powerpoint.slide.macroEnabled.12";
".sldx"= "application/vnd.openxmlformats-officedocument.presentationml.slide";
".slk"= "application/vnd.ms-excel";
".sln"= "text/plain";
".slupkg-ms"= "application/x-ms-license";
".smd"= "audio/x-smd";
".smi"= "application/octet-stream";
".smx"= "audio/x-smd";
".smz"= "audio/x-smd";
".snd"= "audio/basic";
".snippet"= "application/xml";
".snp"= "application/octet-stream";
".sol"= "text/plain";
".sor"= "text/plain";
".spc"= "application/x-pkcs7-certificates";
".spl"= "application/futuresplash";
".spx"= "audio/ogg";
".src"= "application/x-wais-source";
".srf"= "text/plain";
".SSISDeploymentManifest"= "text/xml";
".ssm"= "application/streamingmedia";
".sst"= "application/vnd.ms-pki.certstore";
".stl"= "application/vnd.ms-pki.stl";
".sv4cpio"= "application/x-sv4cpio";
".sv4crc"= "application/x-sv4crc";
".svc"= "application/xml";
".svg"= "image/svg+xml";
".swf"= "application/x-shockwave-flash";
".step"= "application/step";
".stp"= "application/step";
".t"= "application/x-troff";
".tar"= "application/x-tar";
".tcl"= "application/x-tcl";
".testrunconfig"= "application/xml";
".testsettings"= "application/xml";
".tex"= "application/x-tex";
".texi"= "application/x-texinfo";
".texinfo"= "application/x-texinfo";
".tgz"= "application/x-compressed";
".thmx"= "application/vnd.ms-officetheme";
".thn"= "application/octet-stream";
".tif"= "image/tiff";
".tiff"= "image/tiff";
".tlh"= "text/plain";
".tli"= "text/plain";
".toc"= "application/octet-stream";
".tr"= "application/x-troff";
".trm"= "application/x-msterminal";
".trx"= "application/xml";
".ts"= "video/vnd.dlna.mpeg-tts";
".tsv"= "text/tab-separated-values";
".ttf"= "application/font-sfnt";
".tts"= "video/vnd.dlna.mpeg-tts";
".txt"= "text/plain";
".u32"= "application/octet-stream";
".uls"= "text/iuls";
".user"= "text/plain";
".ustar"= "application/x-ustar";
".vb"= "text/plain";
".vbdproj"= "text/plain";
".vbk"= "video/mpeg";
".vbproj"= "text/plain";
".vbs"= "text/vbscript";
".vcf"= "text/x-vcard";
".vcproj"= "application/xml";
".vcs"= "text/plain";
".vcxproj"= "application/xml";
".vddproj"= "text/plain";
".vdp"= "text/plain";
".vdproj"= "text/plain";
".vdx"= "application/vnd.ms-visio.viewer";
".vml"= "text/xml";
".vscontent"= "application/xml";
".vsct"= "text/xml";
".vsd"= "application/vnd.visio";
".vsi"= "application/ms-vsi";
".vsix"= "application/vsix";
".vsixlangpack"= "text/xml";
".vsixmanifest"= "text/xml";
".vsmdi"= "application/xml";
".vspscc"= "text/plain";
".vss"= "application/vnd.visio";
".vsscc"= "text/plain";
".vssettings"= "text/xml";
".vssscc"= "text/plain";
".vst"= "application/vnd.visio";
".vstemplate"= "text/xml";
".vsto"= "application/x-ms-vsto";
".vsw"= "application/vnd.visio";
".vsx"= "application/vnd.visio";
".vtx"= "application/vnd.visio";
".wav"= "audio/wav";
".wave"= "audio/wav";
".wax"= "audio/x-ms-wax";
".wbk"= "application/msword";
".wbmp"= "image/vnd.wap.wbmp";
".wcm"= "application/vnd.ms-works";
".wdb"= "application/vnd.ms-works";
".wdp"= "image/vnd.ms-photo";
".webarchive"= "application/x-safari-webarchive";
".webm"= "video/webm";
".webp"= "image/webp";
".webtest"= "application/xml";
".wiq"= "application/xml";
".wiz"= "application/msword";
".wks"= "application/vnd.ms-works";
".WLMP"= "application/wlmoviemaker";
".wlpginstall"= "application/x-wlpg-detect";
".wlpginstall3"= "application/x-wlpg3-detect";
".wm"= "video/x-ms-wm";
".wma"= "audio/x-ms-wma";
".wmd"= "application/x-ms-wmd";
".wmf"= "application/x-msmetafile";
".wml"= "text/vnd.wap.wml";
".wmlc"= "application/vnd.wap.wmlc";
".wmls"= "text/vnd.wap.wmlscript";
".wmlsc"= "application/vnd.wap.wmlscriptc";
".wmp"= "video/x-ms-wmp";
".wmv"= "video/x-ms-wmv";
".wmx"= "video/x-ms-wmx";
".wmz"= "application/x-ms-wmz";
".woff"= "application/font-woff";
".wpl"= "application/vnd.ms-wpl";
".wps"= "application/vnd.ms-works";
".wri"= "application/x-mswrite";
".wrl"= "x-world/x-vrml";
".wrz"= "x-world/x-vrml";
".wsc"= "text/scriptlet";
".wsdl"= "text/xml";
".wvx"= "video/x-ms-wvx";
".x"= "application/directx";
".xaf"= "x-world/x-vrml";
".xaml"= "application/xaml+xml";
".xap"= "application/x-silverlight-app";
".xbap"= "application/x-ms-xbap";
".xbm"= "image/x-xbitmap";
".xdr"= "text/plain";
".xht"= "application/xhtml+xml";
".xhtml"= "application/xhtml+xml";
".xla"= "application/vnd.ms-excel";
".xlam"= "application/vnd.ms-excel.addin.macroEnabled.12";
".xlc"= "application/vnd.ms-excel";
".xld"= "application/vnd.ms-excel";
".xlk"= "application/vnd.ms-excel";
".xll"= "application/vnd.ms-excel";
".xlm"= "application/vnd.ms-excel";
".xls"= "application/vnd.ms-excel";
".xlsb"= "application/vnd.ms-excel.sheet.binary.macroEnabled.12";
".xlsm"= "application/vnd.ms-excel.sheet.macroEnabled.12";
".xlsx"= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
".xlt"= "application/vnd.ms-excel";
".xltm"= "application/vnd.ms-excel.template.macroEnabled.12";
".xltx"= "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
".xlw"= "application/vnd.ms-excel";
".xml"= "text/xml";
".xmta"= "application/xml";
".xof"= "x-world/x-vrml";
".XOML"= "text/plain";
".xpm"= "image/x-xpixmap";
".xps"= "application/vnd.ms-xpsdocument";
".xrm-ms"= "text/xml";
".xsc"= "application/xml";
".xsd"= "text/xml";
".xsf"= "text/xml";
".xsl"= "text/xml";
".xslt"= "text/xml";
".xsn"= "application/octet-stream";
".xss"= "application/xml";
".xspf"= "application/xspf+xml";
".xtp"= "application/octet-stream";
".xwd"= "image/x-xwindowdump";
".z"= "application/x-compress";
".zip"= "application/zip";
}
if ( $file )
{
$contentType = $contentTypeMap[$file.Extension.ToLower()];
}
$contentType;
}
#uploads file to box
function uploadFile {
param(
[System.IO.FileInfo] $filename = $null,
[string] $folderid = $null
);$boundary = [guid]::NewGuid().ToString()
$contenttype = Get-ContentType -file $filename$headers = @{}
$headers.Add("ServerHost", "https://upload.box.com")
$headers.Add("Authorization", "Bearer $accessToken")
$headers.Add("cache-control","no-cache")
$filebody = [System.IO.File]::ReadAllBytes($filename)
$enc = [System.Text.Encoding]::GetEncoding("utf-8")
$filebodytemplate = $enc.GetString($filebody)#creating the formdata manually
$template = "
--$boundary
Content-Disposition: form-data; name=""file""; filename="""+$filename.Name+""""+$filebodytemplate+"
--$boundary
Content-Type: "+$contenttype+"; charset=utf-8
Content-Disposition: form-data; name=""metadata""{""name"":"""+$filename.Name+""",""parent"":{""id"":"""+$folderid+"""}}
--$boundary--"
#mail upload process beins with Invoke-RestMethod
try{
$upload_file = Invoke-RestMethod -Uri "https://upload.box.com/api/2.0/files/content" -Method POST -Headers $headers -Body $template -ContentType "multipart/form-data;boundary =$boundary" -Verbose
if($upload_file.total_count -eq 1){
$size = $upload_file.Entries.size
write-host $upload_file.Entries.name " ($size bytes) uploaded successfully"
}Write-Host $upload_file
}catch [Exception] {
Write-Host $_.Exception
$exception = $_.ErrorDetails | ConvertFrom-Json
switch ($exception.status) {
409 { Write-Host "name exists"}
}
}
}
#accesstoken
$accessToken = "paste accesstoken here"#provide file full path and the parent folder ID
uploadFile -filename c:\testfile.csv -folderid 123456 -
Thank you, this looks almost correct.
it's exactly what mentioned in this reference articles:
http://stackoverflow.com/questions/23059945/upload-a-file-to-box-com-using-powershellhttp://joe-pruitt.ulitzer.com/node/1006737/mobile
but this is specificly for the BOX.
Unfortunatelly, it's still doesn't want to work for me...
It's failing on the:
$upload_file = Invoke-RestMethod -Uri 'https://upload.box.com/api/2.0/files/content' -Method POST -Headers $headers -Body $template -ContentType "multipart/form-data; boundary=$boundary" -Verbose
Error:
System.FormatException: The specified content type is invalid.
at System.Net.Mime.ContentType.ParseValue()
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.SetRequestContent(WebRequest request, String content)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()Could you share file as you mentioned please?
-
Hi Boris,
It could be becuase of copy-paste from web.
Try this link:
https://app.box.com/s/46hwgi48n31g42vuqjk67d01abceypij
Let me know if it works. Also, check if the type of file that you are trying to upload is listed in content-type function.
Good luck.
thanks,
Bibek
-
Thank you!
I have downloaded file you provided. Refreshed Token and assigned value to the $accessTokenthen edited this:
uploadFile -filename "C:\Temp\Box\test.txt" -folderid 0
simple test.txt - listed in the content-type function.
Continue to get error:
System.FormatException: The specified content type is invalid.
at System.Net.Mime.ContentType.ParseValue()
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.SetRequestContent(WebRequest request, String content)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()I am really confused with this....
-
I am not sure why you are getting that error. This is working for me.
Could you try this command in powershell prompt to get the version:
$PSVersionTable.PSVersion
just wanted to see the version. Also, make sure you have latest .NET framework (4.5) installed.
let me know what you find.
-
Interesting... if it's working for you, i'll try to figure out, what's going on.
I have latest PowerShell installed.PS C:\WINDOWS\system32>> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.***number removed for privacy***
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.***number removed for privacy***
CLRVersion 4.0.***number removed for privacy***0
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
.Net version is 4.6.01586
-
You seem to have latest versions. Sometimes closing powershell entirely and reopening works becuase of the cache.
You may try to hard-code content-type in this line:
Content-Type: "+$contenttype+"; charset=utf-8
e.g. Content-Type: text/plain; charset=utf-8
and see how it goes.
thanks,
Bibek
-
Thank you for advice!
Yes, of course, I’ve checked if variable
"+$contenttype+"
resolves successfully.
The core of issue was actually different.
This string has error:
$upload_file = Invoke-RestMethod -Uri "https://upload.box.com/api/2.0/files/content" -Method POST -Headers $headers -Body $template -ContentType "multipart/form-data;boundary =$boundary" -Verbose
There should be NO SPACE before equal sign here…
-ContentType "multipart/form-data;boundary =$boundary"
So CORRECT wil be: (I didn't expect that initially)
$upload_file = Invoke-RestMethod -Uri "https://upload.box.com/api/2.0/files/content" -Method POST -Headers $headers -Body $template -ContentType "multipart/form-data;boundary=$boundary" -Verbose
For those, who will have same issue:
It’s very important to format $template exactly like in your script, as ANY additional space or EMPTY String or TAB may cause issue.
The correct format:
$template = " --$boundary Content-Disposition: form-data; name=""file""; filename="""+$filename.Name+""" "+$filebodytemplate+" --$boundary Content-Type:text/plain; charset=utf-8 Content-Disposition: form-data; name=""metadata"" {""name"":"""+$filename.Name+""",""parent"":{""id"":"""+$folderid+"""}} --$boundary--"
-OR
Alternative way of creating Template body, to prevent formatting issues may be:
[System.Text.StringBuilder]$contents = New-Object System.Text.StringBuilder $contents.AppendLine() $contents.AppendLine("--$boundary") $contents.AppendLine("Content-Disposition: form-data; name=""file""; filename=""$($filename.Name)""") $contents.AppendLine() $contents.AppendLine($filebodytemplate) $contents.AppendLine("--$boundary") $contents.AppendLine("Content-Type: $contenttype; charset=utf-8") $contents.AppendLine("Content-Disposition: form-data; name=""metadata""") $contents.AppendLine() $contents.AppendLine("{""name"":""$($filename.Name)"",""parent"":{""id"":""$folderid""}}") $contents.AppendLine() $contents.AppendLine("--$boundary--") $template = $contents.ToString()
I think it might be less visible, but more safe to format and copy paste.
THANK YOU BIBEK_K!
So full solution with Token Generation may look like this:
function Register-BoxApp { <# .Synopsis Register the Box application in workstation's registry, Get new Token and Refresh Token. .DESCRIPTION In order to perform actions on BOX API, a security token required to be recieved. Function has 2 modes: NEW for the 1st time execution and Refresh for the Update of the Token. Function will create Windows registry keys with the key properties and values to work with Tokens. Token is valid ~1 hour To issue New token a user itteraction required: - IE will be opened and PopUP message, dont's click OK until you finish with all steps. - Enter credentials of BOX API account - Grant Access - Enter Credentials again if required - Press OK on the Pop up window .PARAMETER AppName Application Name - could be anything. This is application, create on BOX developer pane to perdorm operations with BOX .PARAMETER ClientID ID of the Client, something like UserName, could be retrieved from https://app.box.com/developers/console/app/ Configuration Tab .PARAMETER ClientSecret Something like Client password, could be retrieved from https://app.box.com/developers/console/app/ Configuration Tab .PARAMETER Mode New Token or Refresh Existing .EXAMPLE PS C:\WINDOWS\system32> Register-BoxApp -AppName VrgSync -ClientID xxxxxxxxxxxxxxxxxxxx -ClientSecret xxxxxxxxxxxxx -Mode New OK access_token : xxxxxxxxxxxxxxxxxxxxxxxxxxxx expires_in : 4020 restricted_to : {} refresh_token : xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx token_type : bearer .INPUTS System.String .OUTPUTS System.Object, System.Bool #> [CmdletBinding()] param ( [Parameter(Mandatory=$true)] $AppName, # Name of your Application in Box, could be anything, this registry key will be created and store Token [Parameter(Mandatory=$true)] $ClientID, # Client ID - (Something like user name) you may grab it from developers console of the BOX (https://app.box.com/developers/console) [Parameter(Mandatory=$true)] $ClientSecret, # Client Secret - (Something like user password) you may grab it from developers console of the BOX (https://app.box.com/developers/console) [Parameter(Mandatory=$true)] [ValidateSet('New', 'Refresh')] $Mode = 'New' # you will need to generate a New at first time with user interaction and later Refresh without ) begin { $ScriptName = 'Register-BoxApp' $LogFile = Join-Path -Path $env:SystemDrive -ChildPath "Scripts\Log\$ScriptName.log" Write-Verbose -Message "Start execution $ScriptName" $RegKey = "HKLM:\SOFTWARE\Box.com\$AppName" $State = ([guid]::NewGuid()).guid # Some script I found uses this instead $sec_token_sent = "security_token%3DKnhMJatFipTAnM0nHlZA" , where 3DKnhMJatFipTAnM0nHlZA - always the same and is on public we site $URI = "https://account.box.com/api/oauth2/authorize?response_type=code&client_id=$ClientID&state=$State" } process { # Register the Box application in workstation's registry if (Test-Path -Path $RegKey){ Write-Verbose -Message "Registry Key $RegKey Exists." } else { Write-Verbose -Message "Registry Key $RegKey does NOT exist. Creating it." $null = New-Item -Path $RegKey -Force } if ($Mode -eq 'New') { # Go get grant access to Box application via Internet Explorer Write-Verbose -Message 'Create Internet Explorer object and go to URL' $ie = New-Object -ComObject internetexplorer.application $ie.Visible = $true $ie.Navigate2($URI) # Inform user that there is an interactive process in IE that needs to be completed before continuing. [System.Windows.Forms.MessageBox]::Show("Once you've completed the interactive authorzation process within Internet Explorer, then click 'OK' here to continue." , "Authorizing Box API") # After Credentials entered and Access granted, it should redirect you to specified redirect URI, if not specified it will throw page not found, # but we don't care about page, as we need a code if ($ie.Locationurl -match 'code='){ # Split IE URL by 'code=' and Grab the authorization code(the last one if multiple) from address bar in IE and close IE $AuthCode = ($ie.Locationurl -split 'code=')[-1] $ie.Quit() Write-Verbose -Message "Grabbed code from URI: $AuthCode. It is valid for 30 seconds only!" } else { Write-Warning -Message 'Failed to find code= in the ie url! Check if you Entered into your account and granted access to your application' } $BoxTokenRequest = @{ 'grant_type' = 'authorization_code'; 'code' = $AuthCode; 'client_id' = $ClientID; 'client_secret' = $ClientSecret } #HashTable containing the information needed to obtain an access code. $URI = 'https://www.box.com/api/oauth2/token' # RESTful call to Box Content API to retrieve access token. Write-Verbose -Message 'Invoke-RestMethod with Generated HashTable' $AccessToken = Invoke-RestMethod -Method Post -Uri $URI -Body $BoxTokenRequest } else { # Refresh Token $URI = 'https://www.box.com/api/oauth2/token' if ((Test-Path -Path $RegKey) -and (Get-ItemProperty -Path $RegKey).refresh_token){ Write-Verbose -Message 'Retrieve Referesh Token to generate New Token' $RefreshToken = (Get-ItemProperty -Path $RegKey).refresh_token Write-Verbose -Message 'Generate BoxTokenRequest HashTable to request token' $BoxTokenRequest = @{ 'grant_type' = 'refresh_token'; 'refresh_token' = $RefreshToken; 'client_id' = $ClientID; 'client_secret' = $ClientSecret } Write-Verbose -Message 'Invoke-RestMethod with Generated HashTable' $AccessToken = Invoke-RestMethod -Method Post -Uri $URI -Body $BoxTokenRequest } else { Write-Verbose -Message 'refresh_token does not exist yet, please use New mode!' } } } end { if ($AccessToken){ Set-ItemProperty -Path $RegKey -Name 'access_token' -Value $AccessToken.access_token -Type String -Force Set-ItemProperty -Path $RegKey -Name 'expires_in' -Value "$((get-date).AddSeconds($AccessToken.expires_in))" -Type String -Force Set-ItemProperty -Path $RegKey -Name 'restricted_to' -Value $AccessToken.restricted_to -Type String -Force Set-ItemProperty -Path $RegKey -Name 'refresh_token' -Value $AccessToken.refresh_token -Type String -Force Set-ItemProperty -Path $RegKey -Name 'token_type' -Value $AccessToken.token_type -Type String -Force Write-Verbose -Message "Token Registered! $ScriptName completed Successfully" return $AccessToken } else { Write-Warning -Message "Failed to get AccessToken using Invoke-RestMethod to $URI" return $false } } } # function that returns the content type based on the file extension function Get-ContentType { param([System.IO.FileInfo]$file) $contentType = $null $contentTypeMap = @{ ".323"= "text/h323"; ".3g2"= "video/3gpp2"; ".3gp"= "video/3gpp"; ".3gp2"= "video/3gpp2"; ".3gpp"= "video/3gpp"; ".7z"= "application/x-7z-compressed"; ".aa"= "audio/audible"; ".AAC"= "audio/aac"; ".aaf"= "application/octet-stream"; ".aax"= "audio/vnd.audible.aax"; ".ac3"= "audio/ac3"; ".aca"= "application/octet-stream"; ".accda"= "application/msaccess.addin"; ".accdb"= "application/msaccess"; ".accdc"= "application/msaccess.cab"; ".accde"= "application/msaccess"; ".accdr"= "application/msaccess.runtime"; ".accdt"= "application/msaccess"; ".accdw"= "application/msaccess.webapplication"; ".accft"= "application/msaccess.ftemplate"; ".acx"= "application/internet-property-stream"; ".AddIn"= "text/xml"; ".ade"= "application/msaccess"; ".adobebridge"= "application/x-bridge-url"; ".adp"= "application/msaccess"; ".ADT"= "audio/vnd.dlna.adts"; ".ADTS"= "audio/aac"; ".afm"= "application/octet-stream"; ".ai"= "application/postscript"; ".aif"= "audio/aiff"; ".aifc"= "audio/aiff"; ".aiff"= "audio/aiff"; ".air"= "application/vnd.adobe.air-application-installer-package+zip"; ".amc"= "application/mpeg"; ".anx"= "application/annodex"; ".apk"= "application/vnd.android.package-archive" ; ".application"= "application/x-ms-application"; ".art"= "image/x-jg"; ".asa"= "application/xml"; ".asax"= "application/xml"; ".ascx"= "application/xml"; ".asd"= "application/octet-stream"; ".asf"= "video/x-ms-asf"; ".ashx"= "application/xml"; ".asi"= "application/octet-stream"; ".asm"= "text/plain"; ".asmx"= "application/xml"; ".aspx"= "application/xml"; ".asr"= "video/x-ms-asf"; ".asx"= "video/x-ms-asf"; ".atom"= "application/atom+xml"; ".au"= "audio/basic"; ".avi"= "video/x-msvideo"; ".axa"= "audio/annodex"; ".axs"= "application/olescript"; ".axv"= "video/annodex"; ".bas"= "text/plain"; ".bcpio"= "application/x-bcpio"; ".bin"= "application/octet-stream"; ".bmp"= "image/bmp"; ".c"= "text/plain"; ".cab"= "application/octet-stream"; ".caf"= "audio/x-caf"; ".calx"= "application/vnd.ms-office.calx"; ".cat"= "application/vnd.ms-pki.seccat"; ".cc"= "text/plain"; ".cd"= "text/plain"; ".cdda"= "audio/aiff"; ".cdf"= "application/x-cdf"; ".cer"= "application/x-x509-ca-cert"; ".cfg"= "text/plain"; ".chm"= "application/octet-stream"; ".class"= "application/x-java-applet"; ".clp"= "application/x-msclip"; ".cmd"= "text/plain"; ".cmx"= "image/x-cmx"; ".cnf"= "text/plain"; ".cod"= "image/cis-cod"; ".config"= "application/xml"; ".contact"= "text/x-ms-contact"; ".coverage"= "application/xml"; ".cpio"= "application/x-cpio"; ".cpp"= "text/plain"; ".crd"= "application/x-mscardfile"; ".crl"= "application/pkix-crl"; ".crt"= "application/x-x509-ca-cert"; ".cs"= "text/plain"; ".csdproj"= "text/plain"; ".csh"= "application/x-csh"; ".csproj"= "text/plain"; ".css"= "text/css"; ".csv"= "text/csv"; ".cur"= "application/octet-stream"; ".cxx"= "text/plain"; ".dat"= "application/octet-stream"; ".datasource"= "application/xml"; ".dbproj"= "text/plain"; ".dcr"= "application/x-director"; ".def"= "text/plain"; ".deploy"= "application/octet-stream"; ".der"= "application/x-x509-ca-cert"; ".dgml"= "application/xml"; ".dib"= "image/bmp"; ".dif"= "video/x-dv"; ".dir"= "application/x-director"; ".disco"= "text/xml"; ".divx"= "video/divx"; ".dll"= "application/x-msdownload"; ".dll.config"= "text/xml"; ".dlm"= "text/dlm"; ".doc"= "application/msword"; ".docm"= "application/vnd.ms-word.document.macroEnabled.12"; ".docx"= "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; ".dot"= "application/msword"; ".dotm"= "application/vnd.ms-word.template.macroEnabled.12"; ".dotx"= "application/vnd.openxmlformats-officedocument.wordprocessingml.template"; ".dsp"= "application/octet-stream"; ".dsw"= "text/plain"; ".dtd"= "text/xml"; ".dtsConfig"= "text/xml"; ".dv"= "video/x-dv"; ".dvi"= "application/x-dvi"; ".dwf"= "drawing/x-dwf"; ".dwp"= "application/octet-stream"; ".dxr"= "application/x-director"; ".eml"= "message/rfc822"; ".emz"= "application/octet-stream"; ".eot"= "application/vnd.ms-fontobject"; ".eps"= "application/postscript"; ".etl"= "application/etl"; ".etx"= "text/x-setext"; ".evy"= "application/envoy"; ".exe"= "application/octet-stream"; ".exe.config"= "text/xml"; ".fdf"= "application/vnd.fdf"; ".fif"= "application/fractals"; ".filters"= "application/xml"; ".fla"= "application/octet-stream"; ".flac"= "audio/flac"; ".flr"= "x-world/x-vrml"; ".flv"= "video/x-flv"; ".fsscript"= "application/fsharp-script"; ".fsx"= "application/fsharp-script"; ".generictest"= "application/xml"; ".gif"= "image/gif"; ".gpx"= "application/gpx+xml"; ".group"= "text/x-ms-group"; ".gsm"= "audio/x-gsm"; ".gtar"= "application/x-gtar"; ".gz"= "application/x-gzip"; ".h"= "text/plain"; ".hdf"= "application/x-hdf"; ".hdml"= "text/x-hdml"; ".hhc"= "application/x-oleobject"; ".hhk"= "application/octet-stream"; ".hhp"= "application/octet-stream"; ".hlp"= "application/winhlp"; ".hpp"= "text/plain"; ".hqx"= "application/mac-binhex40"; ".hta"= "application/hta"; ".htc"= "text/x-component"; ".htm"= "text/html"; ".html"= "text/html"; ".htt"= "text/webviewhtml"; ".hxa"= "application/xml"; ".hxc"= "application/xml"; ".hxd"= "application/octet-stream"; ".hxe"= "application/xml"; ".hxf"= "application/xml"; ".hxh"= "application/octet-stream"; ".hxi"= "application/octet-stream"; ".hxk"= "application/xml"; ".hxq"= "application/octet-stream"; ".hxr"= "application/octet-stream"; ".hxs"= "application/octet-stream"; ".hxt"= "text/html"; ".hxv"= "application/xml"; ".hxw"= "application/octet-stream"; ".hxx"= "text/plain"; ".i"= "text/plain"; ".ico"= "image/x-icon"; ".ics"= "application/octet-stream"; ".idl"= "text/plain"; ".ief"= "image/ief"; ".iii"= "application/x-iphone"; ".inc"= "text/plain"; ".inf"= "application/octet-stream"; ".ini"= "text/plain"; ".inl"= "text/plain"; ".ins"= "application/x-internet-signup"; ".ipa"= "application/x-itunes-ipa"; ".ipg"= "application/x-itunes-ipg"; ".ipproj"= "text/plain"; ".ipsw"= "application/x-itunes-ipsw"; ".iqy"= "text/x-ms-iqy"; ".isp"= "application/x-internet-signup"; ".ite"= "application/x-itunes-ite"; ".itlp"= "application/x-itunes-itlp"; ".itms"= "application/x-itunes-itms"; ".itpc"= "application/x-itunes-itpc"; ".IVF"= "video/x-ivf"; ".jar"= "application/java-archive"; ".java"= "application/octet-stream"; ".jck"= "application/liquidmotion"; ".jcz"= "application/liquidmotion"; ".jfif"= "image/pjpeg"; ".jnlp"= "application/x-java-jnlp-file"; ".jpb"= "application/octet-stream"; ".jpe"= "image/jpeg"; ".jpeg"= "image/jpeg"; ".jpg"= "image/jpeg"; ".js"= "application/javascript"; ".json"= "application/json"; ".jsx"= "text/jscript"; ".jsxbin"= "text/plain"; ".latex"= "application/x-latex"; ".library-ms"= "application/windows-library+xml"; ".lit"= "application/x-ms-reader"; ".loadtest"= "application/xml"; ".lpk"= "application/octet-stream"; ".lsf"= "video/x-la-asf"; ".lst"= "text/plain"; ".lsx"= "video/x-la-asf"; ".lzh"= "application/octet-stream"; ".m13"= "application/x-msmediaview"; ".m14"= "application/x-msmediaview"; ".m1v"= "video/mpeg"; ".m2t"= "video/vnd.dlna.mpeg-tts"; ".m2ts"= "video/vnd.dlna.mpeg-tts"; ".m2v"= "video/mpeg"; ".m3u"= "audio/x-mpegurl"; ".m3u8"= "audio/x-mpegurl"; ".m4a"= "audio/m4a"; ".m4b"= "audio/m4b"; ".m4p"= "audio/m4p"; ".m4r"= "audio/x-m4r"; ".m4v"= "video/x-m4v"; ".mac"= "image/x-macpaint"; ".mak"= "text/plain"; ".man"= "application/x-troff-man"; ".manifest"= "application/x-ms-manifest"; ".map"= "text/plain"; ".master"= "application/xml"; ".mda"= "application/msaccess"; ".mdb"= "application/x-msaccess"; ".mde"= "application/msaccess"; ".mdp"= "application/octet-stream"; ".me"= "application/x-troff-me"; ".mfp"= "application/x-shockwave-flash"; ".mht"= "message/rfc822"; ".mhtml"= "message/rfc822"; ".mid"= "audio/mid"; ".midi"= "audio/mid"; ".mix"= "application/octet-stream"; ".mk"= "text/plain"; ".mmf"= "application/x-smaf"; ".mno"= "text/xml"; ".mny"= "application/x-msmoney"; ".mod"= "video/mpeg"; ".mov"= "video/quicktime"; ".movie"= "video/x-sgi-movie"; ".mp2"= "video/mpeg"; ".mp2v"= "video/mpeg"; ".mp3"= "audio/mpeg"; ".mp4"= "video/mp4"; ".mp4v"= "video/mp4"; ".mpa"= "video/mpeg"; ".mpe"= "video/mpeg"; ".mpeg"= "video/mpeg"; ".mpf"= "application/vnd.ms-mediapackage"; ".mpg"= "video/mpeg"; ".mpp"= "application/vnd.ms-project"; ".mpv2"= "video/mpeg"; ".mqv"= "video/quicktime"; ".ms"= "application/x-troff-ms"; ".msi"= "application/octet-stream"; ".mso"= "application/octet-stream"; ".mts"= "video/vnd.dlna.mpeg-tts"; ".mtx"= "application/xml"; ".mvb"= "application/x-msmediaview"; ".mvc"= "application/x-miva-compiled"; ".mxp"= "application/x-mmxp"; ".nc"= "application/x-netcdf"; ".nsc"= "video/x-ms-asf"; ".nws"= "message/rfc822"; ".ocx"= "application/octet-stream"; ".oda"= "application/oda"; ".odb"= "application/vnd.oasis.opendocument.database"; ".odc"= "application/vnd.oasis.opendocument.chart"; ".odf"= "application/vnd.oasis.opendocument.formula"; ".odg"= "application/vnd.oasis.opendocument.graphics"; ".odh"= "text/plain"; ".odi"= "application/vnd.oasis.opendocument.image"; ".odl"= "text/plain"; ".odm"= "application/vnd.oasis.opendocument.text-master"; ".odp"= "application/vnd.oasis.opendocument.presentation"; ".ods"= "application/vnd.oasis.opendocument.spreadsheet"; ".odt"= "application/vnd.oasis.opendocument.text"; ".oga"= "audio/ogg"; ".ogg"= "audio/ogg"; ".ogv"= "video/ogg"; ".ogx"= "application/ogg"; ".one"= "application/onenote"; ".onea"= "application/onenote"; ".onepkg"= "application/onenote"; ".onetmp"= "application/onenote"; ".onetoc"= "application/onenote"; ".onetoc2"= "application/onenote"; ".opus"= "audio/ogg"; ".orderedtest"= "application/xml"; ".osdx"= "application/opensearchdescription+xml"; ".otf"= "application/font-sfnt"; ".otg"= "application/vnd.oasis.opendocument.graphics-template"; ".oth"= "application/vnd.oasis.opendocument.text-web"; ".otp"= "application/vnd.oasis.opendocument.presentation-template"; ".ots"= "application/vnd.oasis.opendocument.spreadsheet-template"; ".ott"= "application/vnd.oasis.opendocument.text-template"; ".oxt"= "application/vnd.openofficeorg.extension"; ".p10"= "application/pkcs10"; ".p12"= "application/x-pkcs12"; ".p7b"= "application/x-pkcs7-certificates"; ".p7c"= "application/pkcs7-mime"; ".p7m"= "application/pkcs7-mime"; ".p7r"= "application/x-pkcs7-certreqresp"; ".p7s"= "application/pkcs7-signature"; ".pbm"= "image/x-portable-bitmap"; ".pcast"= "application/x-podcast"; ".pct"= "image/pict"; ".pcx"= "application/octet-stream"; ".pcz"= "application/octet-stream"; ".pdf"= "application/pdf"; ".pfb"= "application/octet-stream"; ".pfm"= "application/octet-stream"; ".pfx"= "application/x-pkcs12"; ".pgm"= "image/x-portable-graymap"; ".pic"= "image/pict"; ".pict"= "image/pict"; ".pkgdef"= "text/plain"; ".pkgundef"= "text/plain"; ".pko"= "application/vnd.ms-pki.pko"; ".pls"= "audio/scpls"; ".pma"= "application/x-perfmon"; ".pmc"= "application/x-perfmon"; ".pml"= "application/x-perfmon"; ".pmr"= "application/x-perfmon"; ".pmw"= "application/x-perfmon"; ".png"= "image/png"; ".pnm"= "image/x-portable-anymap"; ".pnt"= "image/x-macpaint"; ".pntg"= "image/x-macpaint"; ".pnz"= "image/png"; ".pot"= "application/vnd.ms-powerpoint"; ".potm"= "application/vnd.ms-powerpoint.template.macroEnabled.12"; ".potx"= "application/vnd.openxmlformats-officedocument.presentationml.template"; ".ppa"= "application/vnd.ms-powerpoint"; ".ppam"= "application/vnd.ms-powerpoint.addin.macroEnabled.12"; ".ppm"= "image/x-portable-pixmap"; ".pps"= "application/vnd.ms-powerpoint"; ".ppsm"= "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"; ".ppsx"= "application/vnd.openxmlformats-officedocument.presentationml.slideshow"; ".ppt"= "application/vnd.ms-powerpoint"; ".pptm"= "application/vnd.ms-powerpoint.presentation.macroEnabled.12"; ".pptx"= "application/vnd.openxmlformats-officedocument.presentationml.presentation"; ".prf"= "application/pics-rules"; ".prm"= "application/octet-stream"; ".prx"= "application/octet-stream"; ".ps"= "application/postscript"; ".psc1"= "application/PowerShell"; ".psd"= "application/octet-stream"; ".psess"= "application/xml"; ".psm"= "application/octet-stream"; ".psp"= "application/octet-stream"; ".pub"= "application/x-mspublisher"; ".pwz"= "application/vnd.ms-powerpoint"; ".qht"= "text/x-html-insertion"; ".qhtm"= "text/x-html-insertion"; ".qt"= "video/quicktime"; ".qti"= "image/x-quicktime"; ".qtif"= "image/x-quicktime"; ".qtl"= "application/x-quicktimeplayer"; ".qxd"= "application/octet-stream"; ".ra"= "audio/x-pn-realaudio"; ".ram"= "audio/x-pn-realaudio"; ".rar"= "application/x-rar-compressed"; ".ras"= "image/x-cmu-raster"; ".rat"= "application/rat-file"; ".rc"= "text/plain"; ".rc2"= "text/plain"; ".rct"= "text/plain"; ".rdlc"= "application/xml"; ".reg"= "text/plain"; ".resx"= "application/xml"; ".rf"= "image/vnd.rn-realflash"; ".rgb"= "image/x-rgb"; ".rgs"= "text/plain"; ".rm"= "application/vnd.rn-realmedia"; ".rmi"= "audio/mid"; ".rmp"= "application/vnd.rn-rn_music_package"; ".roff"= "application/x-troff"; ".rpm"= "audio/x-pn-realaudio-plugin"; ".rqy"= "text/x-ms-rqy"; ".rtf"= "application/rtf"; ".rtx"= "text/richtext"; ".ruleset"= "application/xml"; ".s"= "text/plain"; ".safariextz"= "application/x-safari-safariextz"; ".scd"= "application/x-msschedule"; ".scr"= "text/plain"; ".sct"= "text/scriptlet"; ".sd2"= "audio/x-sd2"; ".sdp"= "application/sdp"; ".sea"= "application/octet-stream"; ".searchConnector-ms"= "application/windows-search-connector+xml"; ".setpay"= "application/set-payment-initiation"; ".setreg"= "application/set-registration-initiation"; ".settings"= "application/xml"; ".sgimb"= "application/x-sgimb"; ".sgml"= "text/sgml"; ".sh"= "application/x-sh"; ".shar"= "application/x-shar"; ".shtml"= "text/html"; ".sit"= "application/x-stuffit"; ".sitemap"= "application/xml"; ".skin"= "application/xml"; ".sldm"= "application/vnd.ms-powerpoint.slide.macroEnabled.12"; ".sldx"= "application/vnd.openxmlformats-officedocument.presentationml.slide"; ".slk"= "application/vnd.ms-excel"; ".sln"= "text/plain"; ".slupkg-ms"= "application/x-ms-license"; ".smd"= "audio/x-smd"; ".smi"= "application/octet-stream"; ".smx"= "audio/x-smd"; ".smz"= "audio/x-smd"; ".snd"= "audio/basic"; ".snippet"= "application/xml"; ".snp"= "application/octet-stream"; ".sol"= "text/plain"; ".sor"= "text/plain"; ".spc"= "application/x-pkcs7-certificates"; ".spl"= "application/futuresplash"; ".spx"= "audio/ogg"; ".src"= "application/x-wais-source"; ".srf"= "text/plain"; ".SSISDeploymentManifest"= "text/xml"; ".ssm"= "application/streamingmedia"; ".sst"= "application/vnd.ms-pki.certstore"; ".stl"= "application/vnd.ms-pki.stl"; ".sv4cpio"= "application/x-sv4cpio"; ".sv4crc"= "application/x-sv4crc"; ".svc"= "application/xml"; ".svg"= "image/svg+xml"; ".swf"= "application/x-shockwave-flash"; ".step"= "application/step"; ".stp"= "application/step"; ".t"= "application/x-troff"; ".tar"= "application/x-tar"; ".tcl"= "application/x-tcl"; ".testrunconfig"= "application/xml"; ".testsettings"= "application/xml"; ".tex"= "application/x-tex"; ".texi"= "application/x-texinfo"; ".texinfo"= "application/x-texinfo"; ".tgz"= "application/x-compressed"; ".thmx"= "application/vnd.ms-officetheme"; ".thn"= "application/octet-stream"; ".tif"= "image/tiff"; ".tiff"= "image/tiff"; ".tlh"= "text/plain"; ".tli"= "text/plain"; ".toc"= "application/octet-stream"; ".tr"= "application/x-troff"; ".trm"= "application/x-msterminal"; ".trx"= "application/xml"; ".ts"= "video/vnd.dlna.mpeg-tts"; ".tsv"= "text/tab-separated-values"; ".ttf"= "application/font-sfnt"; ".tts"= "video/vnd.dlna.mpeg-tts"; ".txt"= "text/plain"; ".u32"= "application/octet-stream"; ".uls"= "text/iuls"; ".user"= "text/plain"; ".ustar"= "application/x-ustar"; ".vb"= "text/plain"; ".vbdproj"= "text/plain"; ".vbk"= "video/mpeg"; ".vbproj"= "text/plain"; ".vbs"= "text/vbscript"; ".vcf"= "text/x-vcard"; ".vcproj"= "application/xml"; ".vcs"= "text/plain"; ".vcxproj"= "application/xml"; ".vddproj"= "text/plain"; ".vdp"= "text/plain"; ".vdproj"= "text/plain"; ".vdx"= "application/vnd.ms-visio.viewer"; ".vml"= "text/xml"; ".vscontent"= "application/xml"; ".vsct"= "text/xml"; ".vsd"= "application/vnd.visio"; ".vsi"= "application/ms-vsi"; ".vsix"= "application/vsix"; ".vsixlangpack"= "text/xml"; ".vsixmanifest"= "text/xml"; ".vsmdi"= "application/xml"; ".vspscc"= "text/plain"; ".vss"= "application/vnd.visio"; ".vsscc"= "text/plain"; ".vssettings"= "text/xml"; ".vssscc"= "text/plain"; ".vst"= "application/vnd.visio"; ".vstemplate"= "text/xml"; ".vsto"= "application/x-ms-vsto"; ".vsw"= "application/vnd.visio"; ".vsx"= "application/vnd.visio"; ".vtx"= "application/vnd.visio"; ".wav"= "audio/wav"; ".wave"= "audio/wav"; ".wax"= "audio/x-ms-wax"; ".wbk"= "application/msword"; ".wbmp"= "image/vnd.wap.wbmp"; ".wcm"= "application/vnd.ms-works"; ".wdb"= "application/vnd.ms-works"; ".wdp"= "image/vnd.ms-photo"; ".webarchive"= "application/x-safari-webarchive"; ".webm"= "video/webm"; ".webp"= "image/webp"; ".webtest"= "application/xml"; ".wiq"= "application/xml"; ".wiz"= "application/msword"; ".wks"= "application/vnd.ms-works"; ".WLMP"= "application/wlmoviemaker"; ".wlpginstall"= "application/x-wlpg-detect"; ".wlpginstall3"= "application/x-wlpg3-detect"; ".wm"= "video/x-ms-wm"; ".wma"= "audio/x-ms-wma"; ".wmd"= "application/x-ms-wmd"; ".wmf"= "application/x-msmetafile"; ".wml"= "text/vnd.wap.wml"; ".wmlc"= "application/vnd.wap.wmlc"; ".wmls"= "text/vnd.wap.wmlscript"; ".wmlsc"= "application/vnd.wap.wmlscriptc"; ".wmp"= "video/x-ms-wmp"; ".wmv"= "video/x-ms-wmv"; ".wmx"= "video/x-ms-wmx"; ".wmz"= "application/x-ms-wmz"; ".woff"= "application/font-woff"; ".wpl"= "application/vnd.ms-wpl"; ".wps"= "application/vnd.ms-works"; ".wri"= "application/x-mswrite"; ".wrl"= "x-world/x-vrml"; ".wrz"= "x-world/x-vrml"; ".wsc"= "text/scriptlet"; ".wsdl"= "text/xml"; ".wvx"= "video/x-ms-wvx"; ".x"= "application/directx"; ".xaf"= "x-world/x-vrml"; ".xaml"= "application/xaml+xml"; ".xap"= "application/x-silverlight-app"; ".xbap"= "application/x-ms-xbap"; ".xbm"= "image/x-xbitmap"; ".xdr"= "text/plain"; ".xht"= "application/xhtml+xml"; ".xhtml"= "application/xhtml+xml"; ".xla"= "application/vnd.ms-excel"; ".xlam"= "application/vnd.ms-excel.addin.macroEnabled.12"; ".xlc"= "application/vnd.ms-excel"; ".xld"= "application/vnd.ms-excel"; ".xlk"= "application/vnd.ms-excel"; ".xll"= "application/vnd.ms-excel"; ".xlm"= "application/vnd.ms-excel"; ".xls"= "application/vnd.ms-excel"; ".xlsb"= "application/vnd.ms-excel.sheet.binary.macroEnabled.12"; ".xlsm"= "application/vnd.ms-excel.sheet.macroEnabled.12"; ".xlsx"= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; ".xlt"= "application/vnd.ms-excel"; ".xltm"= "application/vnd.ms-excel.template.macroEnabled.12"; ".xltx"= "application/vnd.openxmlformats-officedocument.spreadsheetml.template"; ".xlw"= "application/vnd.ms-excel"; ".xml"= "text/xml"; ".xmta"= "application/xml"; ".xof"= "x-world/x-vrml"; ".XOML"= "text/plain"; ".xpm"= "image/x-xpixmap"; ".xps"= "application/vnd.ms-xpsdocument"; ".xrm-ms"= "text/xml"; ".xsc"= "application/xml"; ".xsd"= "text/xml"; ".xsf"= "text/xml"; ".xsl"= "text/xml"; ".xslt"= "text/xml"; ".xsn"= "application/octet-stream"; ".xss"= "application/xml"; ".xspf"= "application/xspf+xml"; ".xtp"= "application/octet-stream"; ".xwd"= "image/x-xwindowdump"; ".z"= "application/x-compress"; ".zip"= "application/zip"; } if ($file){ $contentType = $contentTypeMap[$file.Extension.ToLower()] } return $contentType } # uploads file to box function Start-UploadFileToBox { param ( [System.IO.FileInfo] $filename, [string] $folderid, $accessToken ) $boundary = [guid]::NewGuid().ToString() $contenttype = Get-ContentType -file $filename $headers = @{} $headers.Add("ServerHost", "https://upload.box.com") $headers.Add("Authorization", "Bearer $accessToken") $headers.Add("cache-control","no-cache") $filebody = [System.IO.File]::ReadAllBytes($filename) $enc = [System.Text.Encoding]::GetEncoding('utf-8') $filebodytemplate = $enc.GetString($filebody) # creating the formdata manually [System.Text.StringBuilder]$contents = New-Object System.Text.StringBuilder [void]$contents.AppendLine() [void]$contents.AppendLine("--$boundary") [void]$contents.AppendLine("Content-Disposition: form-data; name=""file""; filename=""$($filename.Name)""") [void]$contents.AppendLine() [void]$contents.AppendLine($filebodytemplate) [void]$contents.AppendLine("--$boundary") [void]$contents.AppendLine("Content-Type: $contenttype; charset=utf-8") [void]$contents.AppendLine("Content-Disposition: form-data; name=""metadata""") [void]$contents.AppendLine() [void]$contents.AppendLine("{""name"":""$($filename.Name)"",""parent"":{""id"":""$folderid""}}") [void]$contents.AppendLine() [void]$contents.AppendLine("--$boundary--") $body = $contents.ToString() # mail upload process beins with Invoke-RestMethod try { $upload_file = Invoke-RestMethod -Uri 'https://upload.box.com/api/2.0/files/content' -Method POST -Headers $headers -Body $body -ContentType "multipart/form-data;boundary=$boundary" -Verbose if ($upload_file){ Write-Verbose -Message 'File uploaded successfully!' } else { Write-Warning -Message 'File failed to upload, unexpected error!' } return $upload_file } catch { Write-Warning -Message $_.Exception if ($_.Exception -match '(409)'){ Write-Warning -Message "File with the name: $filename in the folder id:$folderid Already Exists on the BOX server!" } return $false } } # main script [string]$AppName = 'ENTER APPLICATION NAME' [string]$ClientID = 'ENTER CLIENT ID' [string]$ClientSecret = 'ENTER CLIENT SECRET' [string]$RegKey = "HKLM:\SOFTWARE\Box.com\$AppName" [string]$FilePath = 'C:\Temp\Box\test.txt' [string]$FolderID = '0' if (Test-Path -Path $RegKey){ if ($TokenObj = Get-ItemProperty -Path $RegKey){ if ((Get-Date) -ge [datetime]$TokenObj.expires_in){ Write-Verbose -Message 'Refresh Token and save it back to registry' $TokenObj = Register-BoxApp -AppName $AppName -ClientID $ClientID -ClientSecret $ClientSecret -Mode Refresh } else { Write-Verbose -Message 'Token is valid, no need to Refresh it.' } } else { Write-Verbose -Message 'Create New Token and save it to registry' $TokenObj = Register-BoxApp -AppName $AppName -ClientID $ClientID -ClientSecret $ClientSecret -Mode New } } else { Write-Verbose -Message 'Create New Token and save it to registry' $TokenObj = Register-BoxApp -AppName $AppName -ClientID $ClientID -ClientSecret $ClientSecret -Mode New } # provide file full path and the parent folder ID Start-UploadFileToBox -filename $FilePath -folderid $FolderID -accessToken $TokenObj.access_token
-
I am getting the following errors:
WARNING: Failed to find code= in the ie url! Check if you Entered into your account and granted access to your application
Invoke-RestMethod : {"error":"unauthorized_client","error_description":"The grant type is unauthorized for this client_id"}
At C:\Users\krhodes\Desktop\MFT\box\API\Upload.ps1:91 char:28
+ ... cessToken = Invoke-RestMethod -Method Post -Uri $URI -Body $BoxTokenR ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
WARNING: Failed to get AccessToken using Invoke-RestMethod to https://www.box.com/api/oauth2/token
VERBOSE: POST https://upload.box.com/api/2.0/files/content with -1-byte payload
WARNING: System.Net.WebException: The remote server returned an error: (400) Bad Request.
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
False -
Hello all,
Thanks for sharing your script.
I have modified it so that it loops through a specific local directory and uploads all of the files found to the Box directory.
If anyone else want to do that you only need to make a small change to the main script; the code looks like this...
$files = Get-ChildItem "C:\PATH\TH\DIRECTORY\" for ($i=0; $i -lt $files.Count; $i++) { # main script [string]$AppName = 'ENTER APPLICATION NAME' [string]$ClientID = 'ENTER CLIENT ID' [string]$ClientSecret = 'ENTER CLIENT SECRET' [string]$RegKey = "HKLM:\SOFTWARE\Box.com\$AppName" [string]$FilePath = $files[$i].FullName [string]$FolderID = '0' if (Test-Path -Path $RegKey){ if ($TokenObj = Get-ItemProperty -Path $RegKey){ if ((Get-Date) -ge [datetime]$TokenObj.expires_in){ Write-Verbose -Message 'Refresh Token and save it back to registry' $TokenObj = Register-BoxApp -AppName $AppName -ClientID $ClientID -ClientSecret $ClientSecret -Mode Refresh } else { Write-Verbose -Message 'Token is valid, no need to Refresh it.' } } else { Write-Verbose -Message 'Create New Token and save it to registry' $TokenObj = Register-BoxApp -AppName $AppName -ClientID $ClientID -ClientSecret $ClientSecret -Mode New } } else { Write-Verbose -Message 'Create New Token and save it to registry' $TokenObj = Register-BoxApp -AppName $AppName -ClientID $ClientID -ClientSecret $ClientSecret -Mode New } # provide file full path and the parent folder ID Start-UploadFileToBox -filename $FilePath -folderid $FolderID -accessToken $TokenObj.access_token }
I can get it to upload all of the files as desired, the only thing is that I want to schedule it to run every night.
Sometimes files uploaded one night will be changed and then need to be uploaded the next night.
Right now when it tries to upload a file that has already been uploaded I get an error 409 name conflict.
So the files that I want to be updated or replaced do not get updated, and I spend a lot of time and system resources attempting to upload files that have not changed since last time.
Is anyone good enough with PowerShell and the Box APIs to help me figure out how to upload a new version of a document if it has been modified?
I am sure it could be done using either update-file or update-folder & the if-match header with etags - but I am not good enough to figure it out.
Any gurus think they could help me out here?
Thank you,
David C. Johnson
-
This was corrupting any non text files for me. The encoding seemed to be changing some non ascii bytes. The fix below could probably be written better but it worked for me.
I commented these two lines
#$enc = [System.Text.Encoding]::GetEncoding("utf-8")
#$filebodytemplate = $enc.GetString($filebody)And replaced them with these
$filestring = New-Object System.Text.StringBuilder
$filebody | foreach {$null = $filestring.Append([char]$_)}
$filebodytemplate = $filestring.ToString()
Please sign in to leave a comment.
Comments
16 comments