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

How to color your sqlprompt for Oracle in the glogin.sql powershell?

$
0
0

Hello scripter/PowerShell/Technet geeks.

I'm very well verse in the Lunix work when in come to scripting but getting my way around PowerShell(thx God or whomever...)

I have this glogin.sql script that would customized the prompt when we access the database, as shown below is nice out-put:

time: user @ dbname : version-release -> and hostname. I’ve been trying to implement color to it but it looks like ANSI color codes would not work in PowerShell/Windows. Is there a way we can accomplish this in the MS-windows environment using the ansi color codes? ex: same script in Lunix I would just "chr(27) ||'[31m' ||” to show the user in red and be done with it… any link or light on this is greatly appreciated!

glogin.sql>>>

set timing on;

col dbname new_value pbname noprint;

col dbhost new_value pbhost noprint;

col dbvers new_value pbvers noprint;

col dbuser new_value pbuser noprint;

col dbpt new_value pt noprint;

select (select user from dual) dbuser,

        upper(i.instance_name) dbname,

        substr(i.version,1,8) dbvers,

            i.host_name || ' ' || chr(13) || chr(10) || 'SQL-> ' dbpt

from v$instance i;

set sqlprompt "&&pbuser @ &&pbname:-&&pbvers->&&pt";

set termout on;

set time on;

<<<—EOF—>>>

16:49:00 SYS @ STRE:-11.2.0.2->MS-HOST-2kR8

SQL->

# - Fancy Works on Lunix only

define gname=idle

column global_name new_value gname

set heading off

set termout off

col global_name noprint

select chr(27) ||'[31m' || sys_context ('userenv', 'db_name')||chr(27)||'[m'

               ||'@'||

       chr(27) ||'[32m' || sys_context ('userenv', 'con_name')||chr(27)||'[m'||chr(10)

       global_name

from dual;

set sqlprompt '&gname SQL> '

set heading on

set term out on


Exchange

$
0
0

Team

As a part of Migration Batch creation, we are not sure how to generate a report that would help us get the delegate details of a mailbox If user A has full access over user B, these 2 need to be included in the same batch, and if user C has access over user B, he will also be added here. So, if this chain continues, wouldn’t it be very hard to create the batches this?

Requesting to have a script where I can simple plan for migration batches, Please help on this.


Delete Files listed on a Text file across many directories

$
0
0

I've got a txt file with approx 60 files names and I need to delete the file across approx 300 folders.  The folders are all located under a single data directory (ex C:\data).

I found the below code a ran it, but it took over an hour to run.  Is there a better and faster way to accomplish this?

gc C:\cleanup.txt  | % {gci "C:\data" -Include $_ -Recurse} | % {Remove-Item $_ }

Thanks,

Kevin

Empty Recycle Bin From Batch File

$
0
0

Hello,

I need help with emptying the recycle bin from the command line.  I think it involves using the rundll32 command to call the function SHEmptyRecycleBin; Also, Can someone help with using Cleanmgr from the command line, I want to run cleanmgr from a batch file and when it runs I want it to automatically clear EVERYTHING, with no user input and I DONT want to use the sageset or sagerun switches. Your help is much appreciated!


Brandon Jimenez

Convert .doc to .pdf then process files

$
0
0

Convert .DOC to .PDF then move PDF files to new folder then  delete .doc files every 10 min

I have a folder that receives .doc files every 5-10 min.  I want to convert these doc files to PDF and move to a new folder and delete the doc files that it converted without deleting new .doc files received. Is it possible to create a log file as well? I have worked  hours trying to get this to work.  I almost have it but its not working quite like I would like. Microsoft word isn't closing the doc files and its using 100% of the CPU and is really slow. Any help would be appreciated.  please see my code below.  Some of the code are bits and pieces i have found on the Internet.

Thanks in advance,

Bosmond

$wdFormatPDF = 17
$word = New-Object -ComObject word.application
$word.visible = $false
$folderpath = "D:\IHC\CoderConvertUploadCerner\Step3\*"
$fileTypes = "*.docx","*doc"
Get-ChildItem -path $folderpath -include $fileTypes |
foreach-object `
{
 $path =  ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
 "Converting $path to pdf ..."
 $doc = $word.documents.open($_.fullname)
 $doc.saveas([ref] $path, [ref]$wdFormatPDF)
 $doc.close()

}
$word.Quit()
$tskill winword.exe

$FileLimit = 20 


$DropDirectory = "D:\IHC\CoderConvertUploadCerner\Step4\"

$PickupDirectory = Get-ChildItem -Path "D:\IHC\CoderConvertUploadCerner\Step3\*.doc"

$Counter = 0
foreach ($file in $PickupDirectory)
{
    if ($Counter -ne $FileLimit)
    {
        $Destination = $DropDirectory+$file.Name

        Write-Host $file.FullName #Output file fullname to screen
        Write-Host $Destination   #Output Full Destination path to screen
        
        Move-Item $file.FullName -destination $Destination
        $Counter++

robocopy "D:\IHC\CoderConvertUploadCerner\Step3\" "D:\IHC\CoderConvertUploadCerner\Step4"*.pdf

Remove-Item D:\IHC\CoderConvertUploadCerner\Step4\*.doc

    }  
}

 



Documentation and examples for using DynamicKeyword

$
0
0

I've recently encountered a situation where I needed to define a configuration mechanism and format for our ops team for a piece of our infrastructure that needs to be managed across multiple instances.  The configuration elements arewide and deep and I thought this would be a great opportunity to define a DSL for them that would be somewhat self-documenting and self-guiding.

I quickly thought of how DSC is implemented as a language within a language and that theconfiguration keyword extension to PS is exactly the kind of functionality I'm looking for -- within ISE, the IntelliSense helps to guide the configuration options and structure inline without the need to constantly reference docs and online help.

I know (or at least I think I know) that the DSC configuration format is implemented within a PS module itself and I've dug through this code somewhat and have seen that it's tapping into System.Management.Automation.Language.DynamicKeyword to manipulate the inline language support, but the usage is not very clear or straightfoward.

Bingling around I found MSDN docs for this and related classes, but the actual documentation is missing, simply including the comment "TBD. Introduced in Windows PowerShell 4.0." in all the related docs.  And there appears to be no overall usage description, examples or even any mention on any authoritative sources, and only a couple snippets of sample code here and there.

So my question is, is this intentional and is this language extension mechanism meant to be obscure and reserved for internal PS usage only?  And if not, then where does one get the details to make use of this feature?

Script for listing all servers with /24 subnet

$
0
0

Hello, I am trying to write a script that will provide me with a .csv that will list the server name and subnet mask, but ONLY if the subnet mask is equal to 255.255.255.0 (/24). Ideally I would like to have this in a spreadsheet format with servers in one column and SMs in the next. I think I have just been working on this for too long today and am having "scripter's block". Please let me know if I can answer any other questions, here is the code I have so far.  I am NOT looking for someone to automagically fix this for me!!!  I am trying to learn and I am just stuck and do not know why the script is "hanging" at a certain point, it seems to hang when it hits the part where it would be querying the network adapters (Get-WMIObject).  Thank you for any assistance in just pointing me in the right direction.

<#
.NOTES
===========================================================================
Created on:   01/15/2016 8:06 PM
Created by:  
Organization:
Filename:     Get-PSPSubnetMask.ps1
===========================================================================
.DESCRIPTION
#> 

[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[System.String]
$CommandLineFilePath
)

function Get-PSPSubnetMask {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[System.String]
$FilePath
)

        Write-Verbose "Retrieving server names from text file..."

   #Retrieve a list of PSP servers from text file and set to $serverNames
        $serverNames = Get-Content $FilePath                
    
        Write-Verbose "Gathering network information..."

        #Iterate through each of the server names
   foreach ($serverName in $serverNames) {

#Check if the server is online before doing the remote command
If (Test-Connection -ComputerName $serverName -Quiet -count 1) {

                $ethernetAdapters = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "ipenabled = 'true' and description like 'Intel(R) Ethernet%'" -ComputerName $serverName;       

                    foreach ($ethernetAdapter in $ethernetAdapters) {

                        $SubnetMask  = $ethernetAdapter.IPSubnet;

                            If ($SubnetMask -eq "255.255.255.0") {

                                New-Object -TypeName PSCustomObject -Property @{
                                Server = $serverName
                                SubnetMask = $SubnetMask |
                                Export-Csv C:\Temp\PSPSubnetMask.csv -Append
                            
                                } 

                                Write-Verbose "$serverName has /24 configuration, logged"

                            Else {

                                Write-Verbose "$serverName already has a /23 configuration"

                                } #Else

                        } #foreach ($ethernetAdapter in $ethernetAdapters) {

                } #If (Test-Connection -ComputerName $serverName -Quiet) {

        } #foreach ($serverName in $serverNames) {

    } #function Get-PSPSubnetMask {
                       
   }  
   
Write-Verbose "Script completed successfully"  
             
#Run the Get-PSPSubnetMask function using the text file path that was passed to this script
Get-PSPSubnetMask -FilePath $CommandLineFilePath -Verbose
        
 

Copy-Item from Temporary Internet Files. Possible?

$
0
0

I need to write a script to get login user photo from our intranet and save it to a local drive.

I accessed the photo S712.jpg from this website via IE.  And I would like to copy from the Internet Temporary File (the file name is S712[1].jpg) to my local drive.

Following is my script, no error when it is executed but the file is not copied.

Please advise.


$url="https://a.b.c.com/photo/S712.jpg"

$ie = New-Object -com internetexplorer.application; 
$ie.visible = $false; 
$ie.navigate($url);

Get-Process iexplore | Foreach-Object { $_.CloseMainWindow() }

Copy-Item 'C:\Users\TEST\AppData\Local\Microsoft\Windows\Temporary Internet Files\S712[1].jpg' 'D:\TEMP\S712[1].jpg'


Powershell Script

$
0
0

Hi,

Trying to tidy our Skype for Business environment as we have a lot of user accounts for people have left the business.

Our HR team have sent me a csv of all currently employed staff in the following format:

Name,EmailAddress

Now all of our Skype for Business users SIP address match their email address.

How can I take that CSV input, run a get-csuser against each user to see if they exist in Skype for Business, and then output the results (maybe a true/false if the do/dont exist) to a csv?

Im not really a scripter so any help would be greatly appreciated. I did try to use get-aduser with the msRTCIP-UserEnabled but failed miserably.

Cheers

script to check the which VM stopped replicating to resume

$
0
0

dear all

i have a hyperv 2012 R2 cluster the replicate to Azure. if a machine is replicating for over 6 hours, hyperv stops the replication and it will need someone to resume the replication manually

i have made a script that will try to resume all machines and ran it on schedule but i want to add lines before to check whether the machine has stopped replicating or not before attempting to resume

the line i have in my script is as follows:

Resume-VMReplication * -ComputerName host1, host2, host3

appreciate you helps, thanks

Show file name when comparing content of files with Powershell

$
0
0

Hi

I'm comparing the content of 30 files in 2 foldersles on 2 different PC's. I'm doing it this way:

compare (gc \\$comp1\c$\data\*) (gc \\$comp2\c$\data\*)

And it's working just fine, but it would also be nice to see the file name in the result, when there is a difference

Is there some kind of a parameter I can add to it - still a newbie to powershell :-)

/K

Gather space size of desktop directory of all users profiles from computers list file

$
0
0

Hello,

I have a list of computers, from this txt computers list i need gather information about "Users" profiles desktop directories spaces remotely.

Anyone can help for that?

As starting i using to gather information

$a= "c:\users"
dir $a | foreach -begin {} -process{
 $size=(dir $_.FullName -recurse -force -ea silentlycontinue | Measure-Object 'length' -sum -Maximum).sum
 write-host("{0:n2}" -f ($size/1MB) +" MB",$PSItem.fullname)
 }



automation of transport rules creation - check message header fields

$
0
0

hi everybody,

i am trying to create another transport rule on an exchange server 2007 in powershell.

this rule is supposed to check the mail header for certain texts. in that case it should forward

the message as bcc. it is part of a bigger script to automate the creation of project mailboxes.

$short = "test_02"
$shortCollector = "test_02.collector"

  #create transport rule - >replyTo<

  $Condition1 = Get-TransportRulePredicate HeaderContains
  $mywords = @($short + "@mycompany")
  $mywords = $mywords + "cn=$short"

  $Condition1.messageHeader = @($mywords)
  $Action1 = Get-TransportRuleAction BlindCopyTo
  $ADOCollector = get-mailbox $shortCollector | select -expand userprincipalname
  $Action1.Addresses = @(get-mailbox $shortCollector)
  $RULE_name = $short + " out(replyTo)"
  New-TransportRule -name $RULE_name -Condition @($Condition1)  -Action @($Action1)   


it does not work as intended as i get another error like

...Cannot convert the "System.Object[]" value of type "System.Object[]" to type"Microsoft.Exchange.MessagingPolicies.Rules.Tasks.HeaderName".

any ideas how i can convert correctly?

thank you - best regards

marc

Powershell script to run sql

$
0
0

Hi,

I have a code which runs the script as shown below. When I run this code on PowerShell version 2.0, the script runs fine, however when I run it on PowerShell version 4.0, the script just hangs. Is there a way, that powershell terminates the sqlplus cmd if it runs for more than a 30 seconds. 

$cmd = "cmd.exe";
write-host "24"
$args = "/c sqlplus user/password@newmdb @D:\harvest\sql\Delete_Reserved_Records.sql '$Pkg' $LC Draft";
        write-host "25"&$cmd $args;
        write-host "26"

Currently when I run the sql, on PowerShell version 4.0, the sqlplus connection is done, however the script is not run.

PS D:\SCM\SCM\udp>         $cmd = "cmd.exe";
        write-host "24"
        $args = "/c sqlplus user/password@newmdb @D:\harvest\sql\Delete_Reserved_Records.sql '$Pkg' $LC Draft";
        write-host "25"
        &$cmd $args;
        write-host "26"
24
25

SQL*Plus: Release 11.2.0.1.0 Production on Mon Jan 18 09:51:14 2016

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Automatic Storage Management, OLAP, Data Mining
and Real Application Testing options

Thanks,

Arnab

List all mapped drives for all users that have logged into a computer.

$
0
0

 I have seen the script that will list all the mapped drives for the current user that is logged into the PC.  Is there a way, to get a list of  all mapped drives for all users on the PC and send it to a file whether or not a user is logged into that machine?   I have been trying to modified that other script to make it go through the all users, but no luck on it.


The file would need to be able to break it down by the users.  For example:
user1
map drive 1
map drive 2
user2
map drive 1
user 3
map drive 1
map drive 2
map drive 3

And while I am at it.  The same information but for printers.  Have all the printers whether or not they are local or network printers.

I appreciate any help.

James

PowerShell Convert-VHD

$
0
0

Hi I am trying to convert two vhd files to vhdx. My OS is Windows 10 Pro.  Here is a copy of the error I am receiving:

Windows PowerShell
Copyright (C) 2015 Microsoft Corporation. All rights reserved.
PS U:\> Convert-VHD –Path F:\Images\Symantec\Win7\ST-Office2-Disk0-OS-Fixed.vhd –DestinationPath F:\Images\Symantec\Win7\ST-Office2-Disk0-OS-Fixed.vhdx
Convert-VHD : The operation on computer 'ST-MANAGE' failed: Invalid class
At line:1 char:1
+ Convert-VHD –Path F:\Images\Symantec\Win7\ST-Office2-Disk0-OS-Fixed.v ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Convert-VHD], VirtualizationException
    + FullyQualifiedErrorId : Unspecified,Microsoft.Vhd.PowerShell.Cmdlets.ConvertVhd

PS U:\>

What does this error mean?

Thanks.

-JP

Move computer account to a differenct ou using powershell

$
0
0
Looking for a quick script usig powershell to move computers to new ou. Dave

How to Literally send an email with PS 5.0 (that works)

$
0
0

I've been working on maybe thousands of lines of code for the Send-MailMessage cmdlet, and have only gotten 1 to work.  I've researched maybe more that 50 sites, and very rarely does their code work.

First of all, here's the code that works for me:

$EmailFrom = “myself@gmail.com”
$EmailTo = “olivia@myplace.com”
$Subject = “PowerShell test of sending an email using Gmail”
$Body = “PowerShell test of sending an email using Gmail”
##$Att = “D:\DOWNLOAD\xcopy.text”

$SMTPServer = “smtp.gmail.com”
##$SMTPServer = "$PSEmailServer"

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“myself@gmail.com”, “pwd”);
##$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body, $Att)
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

Notice that I have the Attachments line commented out because it doesn't work if it's in.

Question #1:  How do I send an attachment?

Question #2:  I use Thunderbird for my email client so I can see (from account settings) that the smtp server is:  smtp.verizon.net;   and the port is:  465.  I am using Windows 10 x64 (all up-to-date).  So, if I use this code:

$EmailFrom = “myself@verizon.net”
$EmailTo = “olivia@myplace.com”
$Subject = “PowerShell test 3004 of sending an email”
$Body = “PowerShell test 3004 of sending an email”
##$Attachments = "D:\DOWNLOAD\xcopy.txt"

$SMTPServer = “smtp.verizon.net”

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 465)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“myself@verizon.net”, “pwd”)
##$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body, $Attachments)
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

and it doesn't work.  On the $SMTPClientCredentials = New...  line I also tried "myself" instead of "myself@verizon.net" to no avail.  With the "myself@verison.net" in it, the error I get is:

       Exception calling "Send" with "4" argument(s). "The operation has timed out."  At ... line 14 char 1

which is the last line.  Recently, I have also gotten other errors (using the smtp.verizon.net server) that signified "unauthorized ..."  and "access denied" so I added any email addresses I use to the Verizon white-list in MyVerizon.

Also, I can't even seem to use Help.  I ran this:  Update-Help  from the ISE which did a lot of updating, but if I do these: 

        get-help $SMTPClient           -or-            get-help $emailMessage       -or-     get-help $PSEmailServer

it just bombs out.  I just got this to work:   get-help send-MailMessage

Y-a-a-a-y!!!

Question #3:  Is there a way to see exactly what smtp client is being used in my PC or by PowerShell?  I tried to show the properties of this:  $SMTPClient   so I can see what the system has stored, but couldn't do it?

If you are so kind as to answer my questions, please don't leave out any characters or lines of code as I know very little about these variables and PowerShell (i.e., don't assume I know something that is completely obvious to others), and I'm having a real hard time with my trying to send an email message from the command line using PowerShell.  I've been using 2 other slightly out-of-the-mainstream programs for my job but neither of them offers a way to send an attachment. 

I can always use my script that works with gmail, but it has been really bugging me why the Verizon script won't work.  Whole days have gone by while I plugged away with this problem, and then I almost panic.

Thanks Very Greatly in advance.  crank1948

Find Computer OU Cross Domain and export to csv file

$
0
0

Hello,

I have a list with server names (servers.txt)  with this list I am trying to find the related ou the servers are in.
In total the servers are possible located in 15 trusted domains. (i have a list with the trusted domains)

At the end I d like this all in a CVS file.

I have found several scripts but none of them seem to help me :(

of course it has to do with my basic knowledge about scripting and PS1.

I was trying to do it with the following:

 $computerlist = @(Get-Content C:\temp\servers.txt) 
$computerlist | C:\temp\GetComputerOU.ps1 | Export-CSV c:\temp\oulijst.csv

getcomputerou.ps1 refers to this script: (found on Scripting forum 

<#
.SYNOPSIS
This script will find the OU of the current computer or a specified computer or computers.

.DESCRIPTION
This script will use the System.DirectoryServices functionality to retrieve the OU for
the current computer or a list of computers. This will return a list of objects with
a Name and OU property. If the ValueOnly switch is used, then only the OU of the objects
is returned.

.PARAMETER ComputerName
The name(s) of the computer or computers to retrieve the OUs for. This can be specified as a string
or array. Value from the pipeline is accepted.

.PARAMETER ThisComputer
This parameter does not need to be specified. It is used to differentiate between parameter sets.

.PARAMETER ValueOnly
This switch parameter specifies that only the OU of the computer(s) should be returned.

.EXAMPLE
.\GetComputerOU.ps1 -ValueOnly

This will return the OU of the current computer.

.EXAMPLE
$ComputerList = @("Computer1", "Computer2", "Computer3")
$ComputerList | .\GetComputerOU.ps1

This will return an array of object (Name and OU) of the three computer names specified.
#>
[CmdletBinding()]
#requires -version 3
param(
    [parameter(ParameterSetName = "Computername", Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
    $ComputerName ="" 

  #  [parameter(ParameterSetName = "ThisComputer")]
   # [switch]$ThisComputer,
 #  [switch]$ValueOnly
)

begin
{
    $rootDse = New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")
    $Domain = $rootDse.DefaultNamingContext
    $root = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$Domain")
}

process
{
    if ($PSCmdlet.ParameterSetName -ne "ComputerName")
    {
        $ComputerName = $env:COMPUTERNAME
    }

    $searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
    $searcher.Filter = "(&(objectClass=computer)(name=$ComputerName))"
    [System.DirectoryServices.SearchResult]$result = $searcher.FindOne()
    if (!$?)
    {
        return
    }
    $dn = $result.Properties["distinguishedName"]
    $ouResult = $dn.Substring($ComputerName.Length + 4)
    if ($ValueOnly)
    {
        $ouResult
    } else {
        New-Object PSObject -Property @{"Name" = $ComputerName; "OU" = $ouResult}
    }
}

But When I run this, i am getting errors like this one

 

You cannot call a method on a null-valued expression.
At C:\temp\GetComputerOU.ps1:65 char:5
+     $ouResult = $dn.Substring($ComputerName.Length + 4)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

So I am stuck here and hope for some help...

Resume:

The script needs to find the ou for a Servername (in a txt file) in de AD and return its FQDN 
there are 15 trusted domains to search for
These results need to be exported to a Csv File.

thx in advance


copy-item Progress-Bar

$
0
0
It is possible that the Progress-Bar display large files as 30 Gb?

Write-Progress -Activity "Copying Files..." -PercentComplete ([int](($FilesCopied/$NumberofFiles)*100)) -CurrentOperation "$FilesCopied files copied out of total of $NumberofFiles files" -Status "Total Size: $TotalSizeGB GB, please wait while copying..."
Viewing all 15028 articles
Browse latest View live


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