PowerShell로 Office 프로그램 실행(제어)하는 방법

[주의 사항]

본 블로그에 게시된 정보의 내용 (첨부 문서, 링크 등)은 작성일 현재 기준이며 예고없이 변경 될 수 있습니다.

또한, 참고용으로만 제공됨으로 Microsoft에 책임이 없음을 알려 드립니다. 반드시 적용 전 충분한 테스트를 진행하시기 바랍니다.

 

[요약]

PowerShell로 Office 프로그램 실행(제어)하는 방법

 

[원인 또는 해결 방법]

Office가 설치되어 있는 PC에서 PowerShell 명령어를 통하여 자동으로 실행하여 Office 프로그램을 실행 또는 제어 할 수 있습니다. 스크립트를 Windows 작업으로 등록하는 경우 사용자가 없이도 자동으로 특정 작업을 실행할 수 있는 장점이 있습니다.

아래 스크립트는 그에 대한 예시로 다음 동작을 수행합니다.

  1. Excel 프로그램을 실행한 후 특정 위치에 있는 문서를 Open
  2. 10초 대기
  3. 현재 시간을 파일명에 추가한 뒤 다른 이름으로 저장
  4. 현재 문서를 닫고, Excel 프로세스를 종료

 

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Excel")

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Core")

[Microsoft.Office.Interop.Excel.Application] $xl = new-object Microsoft.Office.Interop.Excel.ApplicationClass

$xl.visible = $true

$xl.DisplayAlerts = $false

$xl.AskToUpdateLinks = $false

$file="C:\Users\test\Desktop\test.xlsx"

$wb=$xl.Workbooks.Open($file)

Start-Sleep -S 10

$date = Get-date

$wb.SaveAs("C:\Users\test\Desktop\test" + ([string]$date).replace(" ","_").Replace(":","_").Replace("/","-")  + ".xlsx")

$wb.Close()

$xl.Quit()


아래 3줄의 스크립트를 사용하면 Excel을 객체로 선언할 수 있습니다.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Excel")

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Core")

[Microsoft.Office.Interop.Excel.Application] $xl = new-object Microsoft.Office.Interop.Excel.ApplicationClass

 

또한, $xl 명령어를 실행하여 제어 가능한 Excel 속성 들을 아래와 같이 확인할 수 있습니다.

Application
Creator
Parent
ActiveCell
ActiveChart
ActiveDialog
ActiveMenuBar
ActivePrinter
ActiveSheet
ActiveWindow
ActiveWorkbook
AddIns
Assistant
Cells
Charts
Columns
CommandBars
DDEAppReturnCode
DialogSheets
MenuBars
Modules
Names
Rows
Selection
Sheets
ThisWorkbook
Toolbars
Windows
Workbooks
WorksheetFunction
Worksheets
Excel4IntlMacroSheets
Excel4MacroSheets
AlertBeforeOverwriting
AltStartupPath
AskToUpdateLinks
EnableAnimations
AutoCorrect
Build
CalculateBeforeSave
Calculation
CanPlaySounds
CanRecordSounds
Caption
CellDragAndDrop
DisplayClipboardWindow
ColorButtons
CommandUnderlines
ConstrainNumeric
CopyObjectsWithCells
Cursor
CustomListCount
CutCopyMode
DataEntryMode
_Default
DefaultFilePath
Dialogs
DisplayAlerts
DisplayFormulaBar
DisplayFullScreen
DisplayNoteIndicator
DisplayCommentIndicator
DisplayExcel4Menus
DisplayRecentFiles
DisplayScrollBars
DisplayStatusBar
EditDirectlyInCell
EnableAutoComplete
EnableCancelKey
EnableSound
EnableTipWizard
FileSearch
FileFind
FixedDecimal
FixedDecimalPlaces
Height
IgnoreRemoteRequests
Interactive
Iteration
LargeButtons
Left
LibraryPath
MailSession
MailSystem
MathCoprocessorAvailable
MaxChange
MaxIterations
MemoryFree
MemoryTotal
MemoryUsed
MouseAvailable
MoveAfterReturn
MoveAfterReturnDirection
RecentFiles
Name
NetworkTemplatesPath
ODBCErrors
ODBCTimeout
OnCalculate
OnData
OnDoubleClick
OnEntry
OnSheetActivate
OnSheetDeactivate
OnWindow
OperatingSystem
OrganizationName
Path
PathSeparator
PivotTableSelection
PromptForSummaryInfo
RecordRelative
ReferenceStyle
RollZoom
ScreenUpdating
SheetsInNewWorkbook
ShowChartTipNames
ShowChartTipValues
StandardFont
StandardFontSize
StartupPath
StatusBar
TemplatesPath
ShowToolTips
Top
DefaultSaveFormat
TransitionMenuKey
TransitionMenuKeyAction
TransitionNavigKeys
UsableHeight
UsableWidth
UserControl
UserName
Value
VBE
Version
Visible
Width
WindowsForPens
WindowState
UILanguage
DefaultSheetDirection
CursorMovement
ControlCharacters
EnableEvents
DisplayInfoWindow
ExtendList
OLEDBErrors
COMAddIns
DefaultWebOptions
ProductCode
UserLibraryPath
AutoPercentEntry
LanguageSettings
Dummy101
AnswerWizard
CalculationVersion
ShowWindowsInTaskbar
FeatureInstall
Ready
FindFormat
ReplaceFormat
UsedObjects
CalculationState
CalculationInterruptKey
Watches
DisplayFunctionToolTips
AutomationSecurity
DisplayPasteOptions
DisplayInsertOptions
GenerateGetPivotData
AutoRecover
Hwnd
Hinstance
ErrorCheckingOptions
AutoFormatAsYouTypeReplaceHyperlinks
SmartTagRecognizers
NewWorkbook
SpellingOptions
Speech
MapPaperSize
ShowStartupDialog
DecimalSeparator
ThousandsSeparator
UseSystemSeparators
ThisCell
RTD
DisplayDocumentActionTaskPane
ArbitraryXMLSupportAvailable
MeasurementUnit
ShowSelectionFloaties
ShowMenuFloaties
ShowDevTools
EnableLivePreview
DisplayDocumentInformationPanel
AlwaysUseClearType
WarnOnFunctionNameConflict
FormulaBarHeight
DisplayFormulaAutoComplete
GenerateTableRefs
Assistance
EnableLargeOperationAlert
LargeOperationCellThousandCount
DeferAsyncQueries
MultiThreadedCalculation
ActiveEncryptionSession
HighQualityModeForGraphics
FileExportConverters
SmartArtLayouts
SmartArtQuickStyles
SmartArtColors
AddIns2
PrintCommunication
UseClusterConnector
ClusterConnector
Quitting
Dummy22
Dummy23
ProtectedViewWindows
ActiveProtectedViewWindow
IsSandboxed
SaveISO8601Dates
HinstancePtr
FileValidation
FileValidationPivot
ShowQuickAnalysis
QuickAnalysis
FlashFill
EnableMacroAnimations
ChartDataPointTrack
FlashFillMode
MergeInstances
EnableCheckFileExtensions

감사합니다.