Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

Error and mistake notifications in Powershelll

$
0
0

Hello everybody

I wrote a small script in Powershell and i builded mistakes in it.

Now i have a question

How can i Interpret error and mistake notifications right/correctly?

Have a nice afternoon.

Have a nice day


Newb looking for help with scheduled task

$
0
0

Hi. I'm trying to run a very basic script that uploads a daily file to an FTP server. I used the following script: http://www.howtogeek.com/howto/windows/how-to-automate-ftp-uploads-from-the-windows-command-line/

The script (named upload.bat) is located in C:\temp, which is where the file to be uploaded (named inventory.csv) is also located. It runs successfully when initiated from a command prompt window as follows:

C:\temp>upload inventory.csv

So I then created a scheduled task (named Wholesale Inventory Upload2) to run the script unattended every morning. I created a task with a location of \ (I couldn't seem to place it elsewhere), added a trigger to run daily at 6:30am, and an action to "start a program." I set the Program/Script as C:\temp\upload.bat, and I set the argument as inventory.csv.

The script appears to run without error, but it is not uploading the file. So I'm thinking that the argument is not being passed properly, or something else is happening that I'm not aware of. When I look at the task it simply shows that it ran, with the status "The operation completed successfully. (0x0)." Here's the task history from this morning:

Task Scheduler started "{529dd6e1-3a7c-4a2d-8992-621690d43dd7}" instance of the "\Wholesale Inventory Upload2" task for user "xxx\xxx".

Task Scheduler launched action "C:\Windows\SYSTEM32\cmd.exe" in instance "{529dd6e1-3a7c-4a2d-8992-621690d43dd7}" of task "\Wholesale Inventory Upload2".

Task Scheduler successfully completed task "\Wholesale Inventory Upload2" , instance "{529dd6e1-3a7c-4a2d-8992-621690d43dd7}" , action "C:\Windows\SYSTEM32\cmd.exe" with return code 0.

Any help pointing out what I'm missing and/or doing wrong would be greatly appreciated!

John

Handle exception in calling routine instead of imported module/function

$
0
0

I have two scripts located in the same directory.

Check-Disk.ps1 and Get-DiskUsage.ps1.

Check-disk.ps1 contains the following;

Import-Module $PSScriptRoot\get-diskusage.ps1

try{
     $obj = Get-DiskUsage -computer $c -PerCentageFree $MaxPercent
     $obj
     $report += $obj
    }
catch{
         write-verbose $_.Exception.Message 

       }

The Get-DiskUsage script contains;

Get-WmiObject win32_logicaldisk `
                         -ComputerName $c -Filter "Drivetype=3" -ErrorAction SilentlyContinue |
                         Where-Object {
                                               $divSize = 1
                                               if($_.size -gt 0){$divSize = $_.size} 
                                               ($_.freespace/$divSize) -le $PercFree} |
                                                     Select-Object @{Label = "Server Name";Expression = {$_.SystemName}},
                                                       @{Label = "Drive Letter";Expression = {$_.DeviceID}},
                                                       @{Label = "Total Capacity (GB)";Expression = {"{0:N1}" -f( $_.Size / 1gb)}},
                                                       @{Label = "Free Space (GB)";Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) }},
                                                       @{Label = 'Free Space (%)'; Expression = {"{0:N}" -f (($_.freespace/$_.size) * 100)}}

The problem is that when an exception occurs in the Get-DiskUsage function, such as an RPCerror because the computer is not powered on, it is never caught in the due to the ErrorAction setting.

If I remove the ErrorAction setting, then the exception takes place in the Get-DiskUsage function and I want to catch the exception in the calling routine, in this case the Check-Disk function.

Hopefully this makes sense and thanks in advance for your assistance.

powershell - working with local printers

$
0
0

Here is my PowerShell script. 

$printer = (Get-WMIObject -class Win32_Printer -computer 'MyPCName' -Filter Default=True).name
$printer
Start-Sleep -s 10
$printer.SetDefaultPrinter()

It runs without errors.   I run this and it shows me my default printer.   During the 10 second pause I go into Control Panel and I change my default printer to something else.   The script then finishes yet my default printer does not change back.  How come? 

Also, the $Printer.SetDefaultPrinter()  variable I don't get.  I've seen a few examples of this on Google searches where people use this exact command to set a printer yet when I type in $printer. 'dot' the menu that pops up does not have a SetDefaultPrinter()     How come?


mqh7

Invoke-Command Error Handling

$
0
0

Hello Everyone,

I am trying to run a script to query the folders inside "C:\Users" against Active Directory, this in order to delete any folder of a user who is not found in AD. Since I will be running this on ALL servers, I need to run Invoke-Command against a DC in order to query those users, but I am unable to CATCH error messages from within the Scriptblock, into a local file in the computer, this is the code I have so far (I DO get an output when running, I just dont know how to pass that output which is comming from the remote computer, to a text file in the local server where I am running the script):

$RunLocation = "C:\Users"
$ContLocation = Get-ChildItem -Path $RunLocation
$ScriptLocation = "C:\Scripts\C_Drive"
$BaseFile = New-Item (Join-Path $ScriptLocation "Base.txt") -ItemType file -Force
$SetContent = Set-Content -Path (Join-Path $ScriptLocation "Base.txt") -Value $ContLocation
$LogFile = New-Item (Join-Path $ScriptLocation "NotFound.txt") -ItemType file -Force
$Users = gc $BaseFile


$ScriptBlockCont = {
                Param($RemoteUsers=$Users)

                try
                {
                    Import-Module activedirectory
                    $NoOut = Get-ADUser $RemoteUsers | Select-Object Name,Samaccountname,Enabled,distinguishedname
                }
                catch
                {
                    $ErrorOut = Write-Host "$RemoteUsers"

                }

}

$l = 0
Get-Content $BaseFile | ForEach {
            Invoke-Command -ComputerName LAB-DC-01.LAB.COM -ScriptBlock $ScriptBlockCont -ArgumentList @($Users[$l])
            $l = $l + 1
}

PLEASE HELP ME :(


Could not find file: Certificate.format.ps1xml

$
0
0

Was working on uninstalling and reinstalling my powershell/powershell ise. I was trying out WMF 5.0 and ran into some compatibility issues with it and was rolling back to 4.0. After trying to reinstall powershell I keep getting this error when trying to work with ActiveDirectory Cmdlets.

Anyone have any advice on this one?

writeErrorStream      : True
Exception             : System.Management.Automation.CommandNotFoundException: Could not find file 'C:\Windows\System32\WindowsPowerShell\v1.0\Certificate.format.ps1xml'. ---> System.IO.FileNotFoundException: Could not find
                        file 'C:\Windows\System32\WindowsPowerShell\v1.0\Certificate.format.ps1xml'.
                           at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
                           at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs,
                        String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
                           at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
                           at System.Management.Automation.ExternalScriptInfo.ReadScriptContents()
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.ExternalScriptInfo.ReadScriptContents()
                           at Microsoft.PowerShell.Commands.Internal.Format.XmlLoaderBase.LoadXmlDocumentFromFileLoadingInfo(AuthorizationManager authorizationManager, PSHost host, Boolean& isFullyTrusted)
                           at Microsoft.PowerShell.Commands.Internal.Format.TypeInfoDataBaseLoader.LoadXmlFile(XmlFileLoadInfo info, TypeInfoDataBase db, MshExpressionFactory expressionFactory, AuthorizationManager
                        authorizationManager, PSHost host, Boolean preValidated)
                           at Microsoft.PowerShell.Commands.Internal.Format.TypeInfoDataBaseManager.LoadFromFileHelper(Collection`1 files, MshExpressionFactory expressionFactory, AuthorizationManager authorizationManager,
                        PSHost host, Boolean preValidated, List`1& logEntries, Boolean& success)
                           at Microsoft.PowerShell.Commands.Internal.Format.TypeInfoDataBaseManager.LoadFromFile(Collection`1 files, MshExpressionFactory expressionFactory, Boolean acceptLoadingErrors, AuthorizationManager
                        authorizationManager, PSHost host, Boolean preValidated, List`1& logEntries)
                           at Microsoft.PowerShell.Commands.Internal.Format.TypeInfoDataBaseManager.UpdateDataBase(Collection`1 mshsnapins, AuthorizationManager authorizationManager, PSHost host, Boolean preValidated)
                           at System.Management.Automation.Runspaces.InitialSessionState.UpdateFormats(ExecutionContext context, Boolean update)
                           at System.Management.Automation.Runspaces.InitialSessionState.RemoveTypesAndFormats(ExecutionContext context, IEnumerable`1 formatFilesToRemove, IEnumerable`1 typeFilesToRemove)
                           at Microsoft.PowerShell.Commands.ModuleCmdletBase.RemoveTypesAndFormatting(IEnumerable`1 formatFilesToRemove, IEnumerable`1 typeFilesToRemove)
                           at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModuleManifest(String moduleManifestPath, ExternalScriptInfo scriptInfo, Hashtable data, Hashtable localizedData, ManifestProcessingFlags
                        manifestProcessingFlags, Version version, Version requiredVersion, ImportModuleOptions& options, Boolean& containedErrors)
                           at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModuleManifest(ExternalScriptInfo scriptInfo, ManifestProcessingFlags manifestProcessingFlags, Version version, Version requiredVersion,
                        ImportModuleOptions& options)
                           at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModule(PSModuleInfo parentModule, String fileName, String moduleBase, String prefix, SessionState ss, Object privateData, ImportModuleOptions&
                        options, ManifestProcessingFlags manifestProcessingFlags, Boolean& found, Boolean& moduleFileFound)
                           at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadUsingExtensions(PSModuleInfo parentModule, String moduleName, String fileBaseName, String extension, String moduleBase, String prefix,
                        SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, Boolean& found, Boolean& moduleFileFound)
                           at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadUsingModulePath(PSModuleInfo parentModule, Boolean found, IEnumerable`1 modulePath, String name, SessionState ss, ImportModuleOptions options,
                        ManifestProcessingFlags manifestProcessingFlags, PSModuleInfo& module)
                           at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadUsingModulePath(Boolean found, IEnumerable`1 modulePath, String name, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags
                        manifestProcessingFlags, PSModuleInfo& module)
                           at Microsoft.PowerShell.Commands.ImportModuleCommand.ImportModule_LocallyViaName(ImportModuleOptions importModuleOptions, String name)
                           at Microsoft.PowerShell.Commands.ImportModuleCommand.ProcessRecord()
                           at System.Management.Automation.Cmdlet.DoProcessRecord()
                           at System.Management.Automation.CommandProcessor.ProcessRecord()
TargetObject          :
CategoryInfo          : ObjectNotFound: (:String) [Import-Module], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.ImportModuleCommand
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
PSMessageDetails      : 

Help to write a some

$
0
0

Hi,

I need some sort of script that can be attached to a desktop shortcut.

What it needs to do is

  • Copy a file from a server to a folder on the C Drive (It should create the folder too if it does not exists)
  • Then run the file (the file would be a Access Database)

The next time you run the script

  • It would check that the local file to see if it is out of date
  • If it is over write the file from the server and run.
  • If not just run the local copy.

The database file that is copied over links to a second database file on the server so any data added is held on the second database file.

Hope this makes sense!

Many thanks,

Deepak

Multiple parametrized query with same connection and command objects using vbscript

$
0
0

Hi,

  I have two different query sets which needs to be parameterized to prevent from SQLi. I have written the code whereas in the same, the first query executing fine and the second one throws error as "Incorrect syntax near the keyword 'DEFAULT'". Please find the code snippet below and help me to overcome the issue.

 Note: Code is written in vbscript for a classic ASP page and has to execute sequentially.

/* Code 1 which executes fine*/
reqQryStr_id= Request.QueryString("ID")
Set cpRs1= Server.CreateObject("ADODB.Recordset")
Set cmdObj1= Server.CreateObject("ADODB.Command")
qryStr = "Select name,id From table_abc Where id= ?" 
   cmdObj1.ActiveConnection=Conn
cmdObj1.CommandText= qryStr
cmdObj1.CommandType= adCmdText
cmdObj1.Parameters.Refresh
cmdObj1.Parameters.Append cmdObj1.CreateParameter("@id",,,,reqQryStr_id)
Set cpRs1 = cmdObj1.Execute
reqid= cprs1("id")
/*Code 2 where throws error */
qrystr= "Select name,id from table_abc where name like ?"
Set cmdObj1= Server.CreateObject("ADODB.Command")
cmdObj1.ActiveConnection=Conn
cmdObj1.CommandText= qryStr
cmdObj1.CommandType= adCmdText
cmdObj1.Parameters.Refresh
cmdObj1.Parameters.Append cmdObj1.CreateParameter("@reqid",adVarChar,adParamInput,200,reqid)
Set cpRs1 = cmdObj.Execute

I also tried the Parameters.Append similar to that code1, but throwed an error like "necessary parameters are missing".

Please help to resolve this.


Go Green.Save Earth.



How to understand if a running Windows process is 32bit or 64bit

$
0
0

Hello all!

I need to develop a rule VbSciprt based. One of the requirements I have is that I need to understand if a running Windows process (a.k.a. task) is 32bit or 63bit.

Constraints are:
1. VbScript (no PowerShell of any version; no external applications). I know I could use a C# external application with Is64BitProcess property, but I cannot;
2. Must fit all running Windows process (a.k.a. task) not only system processes (so also for custom developed processes).

Thank you!

Lizzy

How to use User32.dll functions like FindWindow with Vbscript

$
0
0

Hi all

In VBA I know how to use it.

But in Vbscript I don't know how

I have read that I must have a ActiveX DLL and then CreateObject.

My question is there a Activex DLL with the some function of the user32.dll

Thanks


Joao Simplicio Rodrigues

Powershell find strings not in Array

$
0
0

I'm trying to have a script that is pulling information from separate SQL database and storing this information in two single arrays. What I'm trying to accomplish is comparing Array One with Array Two and finding the strings that are in Array One that do not exist in Array Two.

I've tried a couple of ways and am not getting the right results and looking for some guidance on the best approach:

1. Using the Compare-Object is not getting the right results

$Compare = Compare-Object -ReferenceObject ($ArrayOne | Sort-Object) -DifferenceObject ($ArrayTwo | Sort-Object) -PassThru | where {$_.sideindicator -eq "=>"}

2. Tried using a function but it does not seem to work either

Function DiffSYS ($Source, $Search)
{
    $Array = @() 
    $Counter = $Source

For ($i =0; $i -ne $Counter; $i++)
   {
   
            if (($Search[$i] -notcontains $Source) -eq $False)
                {   
                    $Array+=$Search[$i]
           }
        }

        Return $Array
}

$New = DiffSYS ($ArrayTwo, $ArrayOne)

Parsing System Eventlog message to display the filepath.exe only

$
0
0

I have been working at this for a little while and I am stuck.

The output I am looking for is to parse the message after I run this:

Get-EventLog system -after '9/1/2015' -source 'user32' | Select-Object timewritten, username, message

OUTPUT:   1/6/2016 11:42:14 AM  domain\username The process C:\Windows\System32\RuntimeBroker.exe (computername) has initiated the restart of computercomputername on behalf of user domain/username for the following reason: Other (Unplanned)

I need to parse the message down to only display:

1/6/2016 11:42:14 AM  domain\username  C:\Windows\System32\RuntimeBroker.exe

I can get rid of "The Process" by running:  

Get-EventLog system -after '9/1/2015' -source 'user32' | Select-Object timewritten, username, @{Name="message"; Expression={$_.Message.substring(12)}}

Need some help please. I just want to see the timewritten, username and the *.exe

Thank you in advance.

Searching INI files - to select-string or not to select-string?

$
0
0

I'm looking for a means of reviewing remote INI files to verify settings within certain sections.

I've found I can use select-string to locate the sections in the remote files, but I want to, once I find the sections, return the information between that section and the next.

so if I used this data 

[SECTION NAME]

blahblah = 103

blah blah blah blah 

blah2blah=true

[NEXT SECTION NAME]

I'd want it to return the three lines below it (before the next section name).

Additionally, if you can tell me how to include a bracket in the search (-pattern "[SECTION NAME]" doesn't work!!) I'd appreciate it.

Thanks!

Ben

Script to disconnect network drive upon RDP disconnect

$
0
0

Is there any one have a clue on how to write a script that would run every time a RDP disconnect?

I need to create a script to disconnect all network drive upon an RDP disconnect.

Environment:

+ Windows Professional (XP, 7, 8, 8.1, and 10).

+ Windows Server STD (2008, 2012)

 

Please help.

Thank you.


-- A human.

Exception Calling "AdvancedSearch with outlook.application and MAPI

$
0
0

Hello Scripting Guys!, This is my first question but I read you frequently.

I wrote a script to "datamining" information from my outlook mail client folders and mails and it was running ok but I want  improve the performance.To try do this I was testing the AdvancedSearch method from Microsoft.Office.Interop.Outlook.ApplicationClass to try use DSL with it. But I have found the next error when I invoke the method:

Exception calling "AdvancedSearch" with "4" argument(s): "Could not complete the operation. One or more parameter values are not valid."
At <path to my test script>:<line with AdvancedSearch method> char:1
+ $s=$o.AdvancedSearch($Scope,$Filter,$true,'Test')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException

I tried use [ref] with my parameters and later use directly the values in the call without success. I tried a simple call to test and I obtain the same error:

$o=New-Object -comobject outlook.application

$n = $o.GetNamespace('MAPI')

$Scope= "\test@mail.com\Inbox\TEST\"

$Filter="urn:schemas:httpmail:subject='/var/tomcat/scripfiles/test'"

$s=$o.AdvancedSearch($Scope,$Filter,$true,'TestTag')

$s.Results

Any idea that how I could use this method on Powershell?. 

Thank you in advance for your help and time with this.



automation of creating transport rules - variable mismatch

$
0
0

hi,

i am trying to automate the creation of transport rules in our company (exchange 2007/powershell 3.0)

as a part of a script to create new AD-groups.

what i want to achieve is to set a new transport rule to send a blindcopy to a mailbox (mailbox1) if a specific group (mailbox0) is addressed. the code i came up wiht is:

$shrtTeam = "team" $shrtCollector = "collector"

$project = "project001" # create transport rule - >in< $Condition1 = Get-TransportRulePredicate sentto $ADOteam = get-adgroup -filter * -Properties * | where { $_.name -eq $shrtTeam} | select -Property mail $Condition1.Addresses = @($ADOteam) $Action1 = Get-TransportRuleAction BlindCopyTo $ADOCollector = get-mailbox $shrtCollector | select userprincipalname $Action1.Addresses = @($ADOCollector) $IN_name = $project + " in" New-TransportRule -name $IN_name -Condition @($Condition1) -Action @($Action1)

the error i get is a variable mismatch between Selected.Microsoft.ActiveDirectory.Management.ADGroup and Microsoft.Exchange.Data.Directory.Management.MailEnabledRecipient.

can i somehow convert / extract the mailbox name to make this work?

thank you for any ideas.

WQL query for list of accounts that have certain privilege/right

$
0
0

I'm required to use WMIC only (no VBScript, Powershell, etc) to construct a query that can return the list of accounts that are granted privileges/rights like SeBatchLogonRight and SeBackupPrivilege. I'm attempting to use a Linux computer to remotely access a Windows server here.

As far as I know the only way to do this is "SELECT * FROM RSOP_UserPrivilegeRight" from namespace root\RSOP\computer. However this returns an incorrect result: it only returns one entry for SeBatchLogonRight which is said to be assigned to some SIDs that don't exist on the accounts list. No other rights or privileges. I think I have read through every relevant information I could find from the web, but couldn't figure out why this query is failing to retrieve the right results and how to correct this.

What is the actually expected result of the above query and the conditions required for it to return correct results? For example does it need certain conditions to be met from the server side? (I remember something like RSOP must have been run on the server computer or something)

Or are there any other ways to achieve this using WMIC without going to the root\RSOP namespace (e.g. from Win32 OS classes)?

Again, I can't use Powershell or VBScript. However if there are other good tools I can use to access information on remote Windows machine from a Linux computer I'd be happy to hear some examples. I'll move this to another category if this is wrong.

Powershell GUI to find and replace the text in wordfile

$
0
0

Hi

I am new user of Powershell script. I have managed to put together a script (from internet sources) that would find and replace the text in a word file using parameters. I have two parameters find (the text that has to be found) and filename (filename of the doc in which text has to be changed).

i am trying to create a GUI such that one can input the parameters like first filename of the word file and followed by find text and finally replace text.

here is the script i have so far.

Since the replace text is a path of the current folder i have my word document i used current directory to get the replace text (so i am not using it has a param)

for example find string is  "$tfs\try\find\release"

and replace string is "c:\documnet\files\myfile.doc"

param(
$Find,
$Myfilename
)
 
$CurrentDir = $(get-location).Path + "\" + $MyFileName

$objWord = New-Object -ComObject word.application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open($CurrentDir)
$objSelection = $objWord.Selection

$FindText = $Find
$ReplaceText = Split-Path -parent $MyInvocation.MyCommand.Definition
$ReplaceAll = 2
$FindContinue = 1
$MatchCase = $False
$MatchWholeWord = $True
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False

$objSelection.Find.Execute($FindText,$MatchCase,
  $MatchWholeWord,$MatchWildcards,$MatchSoundsLike,
  $MatchAllWordForms,$Forward,$Wrap,$Format,
  $ReplaceText,$ReplaceAll)
     
If ($objSelection.Find.Found)
{
    Write-Host("The search text was found.") } Else {
    Write-Host("The search text was not found.") }

any help would be much appreciated.

Thanks,

SRIDAN

PowerShell, LDAP and retrieving operational attributes

$
0
0

Hello. I am using powershell and DirectoryServices.DirectorySearcher ldap code to query a non-AD LDAP server. I can retrieve all attributes except operational attributes such as createtimestamp and modifytimestamp.

Interestingly, if I switch to using the LDAPConnection class in the Protocols namespace, and specify "+" in the attribute list, I can retrieve operational attributes, but not any other attributes.

Does anyone have suggestions on how I can retrieve these attributes?

Thanks

How can I find and remove duplicate files - ?Script or option?

$
0
0

Is there a way to search across my entire OneDrive and find duplicate files, possibly across folders? I would like a way to find these files and then remove them in one swoop. 

I asked the OneDrive forum, and the moderator confirmed there is no option/feature within OneDrive. They suggested I post over here.

Thanks in advance for any help.

TL,

- JJJ

Viewing all 15028 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>