My powershell script yesterday stopped working. I have changed nothing in the code or in the path to files. It just stopped working. I can't explain it.
I've tested all path and all variables and its look fine.
function Gen-Doc($Replace, $dataToRaplace, $user_name, $austauch) {
$objWord = New-Object -comobject Word.Application
$objWord.Visible = $false
if ($austauch -eq $true) {
$objDoc = $objWord.Documents.Open("C:\Path\To\Docu\Vorlage\Doc1.docx")
} else {
$objDoc = $objWord.Documents.Open("C:\Path\To\\Docu\Vorlage\Doc2.docx")
}
$objSelection = $objWord.Selection
$n = 0
while ($n -ne $dataToRaplace.Length) {
$FindText = $Replace[$n]
$ReplaceWith = $dataToRaplace[$n]
$MatchCase = $False
$MatchWholeWord = $true
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $wdFindContinue
$Format = $False
$wdFindContinue = 1
$wdReplaceAll = 2
$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith,$wdReplaceAll)
$n++
}
$filename = $user_name
$objDoc.SaveAs("C:\Path\To\Docu\$filename.docx")
$objWord.Quit()
if ($checkbox2.Checked -eq $true) {
Start-Process -FilePath "C:\Path\To\Docu\$filename.docx" -Verb print
}
}
And here is error message
This command is not available.
At C:\Scripts\Done\Ausgabe.ps1:103 char:9
+ $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWh ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
Make sure you don't have your document opened before doing $objDoc.SaveAs.
Check process manager for orphan WINWORD.EXE processes running.
Related
I am creating views for multiple libraries in SharePoint. I am able to create view from below code successfully for one library. But I am stuck when I run the code in a loop. Below is my code
Code
Add-PSSnapin "Microsoft.SharePoint.Powershell" -EA SilentlyContinue
$subSiteURL = #("http://test.test.com/departments/Collections", "http://test.test.com/departments/Events")
$listName = #("Collections","Events")
for ($i=0; $i -lt $subSiteURL.length; $i++) {
$SPWeb = Get-SPWeb $subSiteURL[$i]
$ListName = $listName[$i]
$List = $SPWeb.Lists[$ListName]
$ViewTitle = "WebPart View"
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("DocIcon")
$viewFields.Add("LinkFilenameNoMenu")
$viewQuery = "<GroupBy Collapse='FALSE' GroupLimit='100'> <FieldRef Name='Category' Ascending='True'/> <FieldRef Name='Sub_x002d_Category' Ascending='True'/> </GroupBy> <OrderBy> <FieldRef Name='FileLeafRef' /></OrderBy> <Where><Or><Leq><FieldRef Name='Start_x0020_Date' /><Value Type='DateTime'>[Today]</Value></Leq><And><Geq><FieldRef Name='Expiry_x0020_Date' /><Value Type='DateTime'>[Today]</Value></Geq><Eq><FieldRef Name='Always_x0020_Display' /><Value Type='Boolean'>Yes</Value></Eq></And></Or></Where>"
$viewRowLimit = 999
$viewPaged = $false
$viewDefaultView = $false
$newView = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
$newView.TabularView = $False
$newView.Scope = "Recursive"
$newView.Update()
}
Error
You cannot call a method on a null-valued expression.
At D:\\CreateDocLibrariesViews.ps1:24 char:28
+ $newView = $list.Views.Add <<<< ($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Try below script:
Add-PSSnapin "Microsoft.SharePoint.Powershell" -EA SilentlyContinue
$subSiteURL = #("http://sp", "http://sp:12001")
$listNames = #("MyDoc")
for ($i=0; $i -lt $subSiteURL.length; $i++) {
Write-Host $subSiteURL[$i]
$SPWeb = Get-SPWeb $subSiteURL[$i]
for ($j=0; $j -lt $listNames.length; $j++) {
$ListName = $listNames[$j]
Write-Host $ListName
$List = $SPWeb.Lists[$ListName]
$ViewTitle = "WebPart View"
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("DocIcon")
$viewFields.Add("LinkFilenameNoMenu")
$viewQuery = "<GroupBy Collapse='FALSE' GroupLimit='100'> <FieldRef Name='Category' Ascending='True'/></GroupBy> <OrderBy> <FieldRef Name='FileLeafRef' /></OrderBy>"
$viewRowLimit = 999
$viewPaged = $false
$viewDefaultView = $false
$newView = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
$newView.TabularView = $False
$newView.Scope = "Recursive"
$newView.Update()
}
}
Write-Host "done"
I'm using this script to convert DOC to HTML
param([string]$docpath,[string]$htmlpath = $docpath)
$srcfiles = Get-ChildItem $docPath -filter "*.doc"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatFilteredHTML");
$word = new-object -comobject word.application
$word.Visible = $False
function saveas-filteredhtml
{
$opendoc = $word.documents.open($doc.FullName);
$opendoc.saveas([ref]"$htmlpath\$doc.fullname.html", [ref]$saveFormat);
$opendoc.close();
}
ForEach ($doc in $srcfiles)
{
Write-Host "Processing :" $doc.FullName
saveas-filteredhtml
$doc = $null
}
$word.quit();
Unfortunately when I run it for the first time in the ISE console I get this error
Unable to find type [Microsoft.Office.Interop.Word.WdSaveFormat].
In F:\PS\NEW\main.ps1:108 car:29
+ ... = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFor ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Offic...rd.WdSaveFormat:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
While if I run it from the same console again the second time it works fine.
How can I solve the problem? Thanks
In this forum they solve the problem:https://gallery.technet.microsoft.com/office/6f7eee4b-1f42-499e-ae59-1aceb26100de/view/Discussions
you add this lines at the beginning of your code:
$wdTypes = Add-Type -AssemblyName 'Microsoft.Office.Interop.Word' -Passthru
$wdSaveFormat = $wdTypes | Where {$_.Name -eq "wdSaveFormat"}
I have a script which I think is most of the way to being able to grab IE history for all of the users on a machine. My problem is it doesn't work for users other than myself because I get a permissions error when attempting open the folder. Does anyone have any ideas how I can fix the permissions problem?
I'm running this script on a Windows 2012r2 machine and I am an administrator on the box.
Thanks!
function Get-History
{
param
(
[string]$userName
)
$shell = New-Object -ComObject Shell.Application
if($username)
{
$users = $username
}
else
{
$users = Get-ChildItem C:\Users
}
if((([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")))
{
Foreach($user in $users)
{
$user = Split-Path $user -leaf
try
{
$ErrorActionPreference = 'Stop'
$hist = $shell.NameSpace("C:\Users\$user\AppData\Local\Microsoft\Windows\History")
}
catch
{
continue
}
$folder = $hist.Self
#$folder.Path
if($hist){
$hist.Items() | foreach {
#""; ""; $_.Name
if ($_.IsFolder) {
$siteFolder = $_.GetFolder
$siteFolder.Items() | foreach {
$site = $_
#""; $site.Name
if ($site.IsFolder) {
$pageFolder = $site.GetFolder
$pageFolder.Items() | foreach {
$url = $pageFolder.GetDetailsOf($_,0)
$date = $pageFolder.GetDetailsOf($_,2)
#"$user`: $date visited $url"
#Write-Output ("$user,$date,`"$url`"" | ConvertFrom-Csv)
New-Object -TypeName PSObject -Property #{
user=$user;
date = $date;
url = $url
}
}
}
}
}
}
}
}
}
else
{
Write-Host "Not Admin"
}
}
If I run just the small snippet:
$shell = New-Object -ComObject Shell.Application
$hist = $shell.NameSpace("C:\Users\MyOwnUsername\AppData\Local\Microsoft\Windows\History")
Then I successfully assign the $hist variable as a System.__ComObject
But if I run:
$shell = New-Object -ComObject Shell.Application
$hist = $shell.NameSpace("C:\Users\SomeOtherUser\AppData\Local\Microsoft\Windows\History")
I get:
Exception calling "NameSpace" with "1" argument(s): "Unspecified error (Exception from HRESULT: 0x80004005 (E_FAIL))"
At line:3 char:1
+ $hist = $shell.NameSpace("C:\Users\SomeOtherUser\AppData\Local\Microsoft\Windows\History ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Full Disclosure: it's a slight modification of the script at this blog post
I never solved the permissions problem. I changed strategy to use BrowsingHistoryViewer by Nirsoft.
$execPath = "C:\BrowsingHistoryView.exe"
$computers = 'computer1','computer2','computer3','computer4'
$outPath = "c:\"
$computers |
ForEach-Object{ `
Start-Process $execPath `
-argumentList "/HistorySource 3",
"/HistorySourceFolder ""\\$_\c$\Users""",
"/scomma ""$outpath\history_$_.txt"""
}
I am writing my first Powershell script and coming from C# am confused, my code is below:
function Run(
[string] $command,
[string] $args,
[Ref] [string] $stdout,
[Ref] [string] $stderr
)
{
$p1 = New-Object System.Diagnostics.Process
$p1.StartInfo = New-Object System.Diagnostics.ProcessStartInfo;
$p1.StartInfo.FileName = $command
$p1.StartInfo.Arguments = $arguments
$p1.StartInfo.CreateNoWindow = $true
$p1.StartInfo.RedirectStandardError = $true
$p1.StartInfo.RedirectStandardOutput = $true
$p1.StartInfo.UseShellExecute = $false
$p1.Start()
$p1.WaitForExit()
}
$p = New-Object System.Diagnostics.Process
$p.StartInfo = New-Object System.Diagnostics.ProcessStartInfo;
$p.StartInfo.FileName = "ping"
$p.StartInfo.Arguments = "142.553.22242.2"
$p.StartInfo.CreateNoWindow = $true
$p.StartInfo.RedirectStandardError = $true
$p.StartInfo.RedirectStandardOutput = $true
$p.StartInfo.UseShellExecute = $false
$p.Start()
$p.WaitForExit()
$code = $p.ExitCode
$stderr = $p.StandardError.ReadToEnd()
$stdout = $p.StandardOutput.ReadToEnd()
Run("ping","208.67.222.222","","")
The $p.Start() works, but for some reason the parameters passed in to the Run function are ignored and $p1 fails. What am I doing wrong please?
Exception calling "Start" with "0" argument(s): "The system cannot find the file specified"
At C:\Users\Administrator\Desktop\logtofile.ps1:27 char:5
+ $p1.Start()
+ ~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : Win32Exception
Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\Users\Administrator\Desktop\logtofile.ps1:28 char:5
+ $p1.WaitForExit()
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
You have to call run as follows:
Run "ping","208.67.222.222","",""
putting in between the parentheses passes it to the function as a single array argument.
I wasn't trying to start a process from inside a function, but I was getting the same error. It took me a few minutes to realize that it was one of my favorite time-wasters: a UAC trap. I hadn't started PowerShell using "Run as administrator". You have to have admin privileges and run the code as such to start/stop/modify processes that you don't own and this error message is totally unhelpful in this regard.
function Demo {
param (
$fileName,$Arguments
)
$p = New-Object System.Diagnostics.Process
$p.StartInfo = New-Object System.Diagnostics.ProcessStartInfo
$p.StartInfo.FileName = $fileName
$p.StartInfo.RedirectStandardError = $true
$p.StartInfo.RedirectStandardOutput = $true
$p.StartInfo.UseShellExecute = $false
$p.StartInfo.Arguments = $Arguments
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode
}
Demo "getmac" " /v"
I got this error with the start() function on a service because a colleague set the service to "disabled" in the Windows Services window. Setting it back to "Manual" fixed it.
I posted this script the other day in an effort to discover a good way to change file extensions when "saving as." I had the problem licked, but as of this morning, the script will not run without errors. Here's the error message I'm getting:
Processing : C:\users\xxx\Desktop\ht\Automatic_Post-Call_Survey.htm
Exception calling "SaveAs" with "16" argument(s): "This is not a valid file name.
Try one or more of the following:
* Check the path to make sure it was typed correctly.
* Select a file from the list of files and folders."
At C:\users\xxx\Desktop\hd.ps1:11 char:20
+ $opendoc.saveas <<<< ([ref]"$docpath\$doc.FullName.doc", [ref]$saveFormat);
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
if "16" is the error code, that represents an inability to delete the directory...but it doesn't appear as if I'm asking for that at all--unless there's some default parameter in place somewhere. I'm pretty much baffled.anyone have any other ideas I can try out?
$docpath = "c:\users\xxx\desktop\do"
$htmPath = "c:\users\xxx\desktop\ht"
$srcfiles = Get-ChildItem $htmPath -filter "*.htm*"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument");
$word = new-object -comobject word.application
$word.Visible = $False
$filename = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
function saveas-document {
$opendoc = $word.documents.open($doc.FullName);
$opendoc.saveas([ref]"$docpath\$filename", [ref]$saveFormat);
$opendoc.close();
}
ForEach ($doc in $srcfiles) {
Write-Host "Processing :" $doc.FullName
saveas-document
$doc = $null
}
$word.quit();
this should do what do you need, but is not the best design :)
$docpath = "c:\users\xxx\desktop\do"
$htmPath = "c:\users\xxx\desktop\ht"
$srcfiles = Get-ChildItem $htmPath -filter "*.htm*"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument");
$global:word = new-object -comobject word.application
$word.Visible = $False
#$filename = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
function saveas-document ($docs) {
$opendoc = $word.documents.open($docs);
$savepath = $docs -replace [regex]::escape($htmPath),"$docpath"
$savepath = $savepath -replace '\.html*', '.doc'
$opendoc.saveas([ref]"$savepath", [ref]$saveFormat);
$opendoc.close();
}
ForEach ($doc in $srcfiles) {
Write-Host "Processing :" $doc.FullName
saveas-document -doc $doc.FullName
$doc = $null
}
$word.quit();