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

Append Email subject with recipient name

$
0
0

We have a bizarre scenario I am having trouble wrapping my head around, I hope someone can help. I am new here (To my current employer and to script center) and trying to replace this terrible way of contacting our stores.

We have 900+ stores, each with 1 printer and not one user in the store can access a PC (Yes, not one user has access to anything) There are a few reasons why we do this, and we cannot work around this.

In order to communicate with one of the stores, a print job is sent to the printer. (They are all Brother MFCxxxx)

We use an archaic manor of sending these print jobs, by FAX!! (MetroFax)

Installed on each PC that needs to communicate with the stores (Again... yes this is the way we work) they send a Fax and it prints at the store.

SO...I have found an excellent utility; AutoEmailManager by Namtuk, and with a little customization we can now:

Send an email to the store (EX: 0001@ourstorename.com)
All 900+ stores are forwarded to one mailbox (all.stores@ourstorename.com)
The software looks in that mailbox every x minutes
Processes the user in the TO: field (0001) of each email and prints to the corresponding store printer

WOOP WOOP!! Problem solved!!!

NOPE!
When exchange receives an email (EX: I send an email to more than one store: 0001, 0002, 0003) it forwards the same email to multiple mailboxes. These mailboxes in turn send it to All.Stores, but it is not received as 3 emails, it is received as one with 3 recipients.

So now my question:
Can I make a transport rule somehow (It appears that with PowerShell scripting the rule, I can use variables) to perhaps add a prefix to the subject with the recipient (Or anything unique) so that each email is different and would appear as 3 emails in the all.stores mailbox?

A mouthful I am sorry, but I felt that a "Why do you want to do that?" question would appear so I tried to detail as much as possible. I look forward to questions and hopefully a solution!!

Derick


how can i get the while loop to enter a different loop beside the first one

$
0
0

I can't seem to figure out how to change the value to enter into one of the other while statements in the script. I am new to this and can't seem to find anything how to enter in the information to be able to go to different while statements and then run what is located in that statement.

The script is supposed to let me choose between TC, MonsterLock, and Cyc and then jump to the while statement that is associated with one of them and then run what ever is located in that block. All i am getting is a infinite loop and it never sees the other while loops. I have 3 set up the go along with the first statement but no matter what i type in for them it always looks at the first while statement and stays there.

Can someone please help me with having it do what i stated earlier.  

write-host "This script sets up DATABASE Staging"
$ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to run?(TC/MonsterLock/Cyc)"
While($ProductionDistro -notmatch "(TC|MonsterLock|Cyc)"){
    write-host "You have entered an error" -ForegroundColor Red
    write-host "You must type TC or MonsterLock or Cyc"
    write-host "you typed $ProductionDistro"
    write-host "This script sets up DATABASE Staging"
    $ProductionDistro = Read-Host -Prompt "Which production do you `enter code here`want to run?(TC/MonsterLock/Cyc)"
}

while($ProductionDistro -match $TC) {

write-host "Sets up location you want to run staging"
        $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
        While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
            write-host "you have enterd an error" -ForegroundColor Red
            write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
            write-host "you typed $ElementDistro"
            write-host "set location you want to run staging"
          $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
 }

While($PrductionDistro -match $MonsterLock){

write-host "Sets up location you want to run staging"
        $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
        While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
            write-host "you have enterd an error" -ForegroundColor Red
            write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
            write-host "you typed $ElementDistro"
            write-host "set location you want to run staging"
          $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
 }
 }
   while( $ElementDistro -match $DATABASE1 ){
function Execute-MySqlcommand {param( [string]$Server,    #the host of the SQL server
                                            [string]$Database1,   #the name of the database
                                            [System.Data.MySqlclient.MySqlcommand]$Command)  #the command to execute (name of stored command)

         $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
         $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE1.DATABASE1S2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE1.DATABASE1S3.BTXSUPB"
         $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE1.DATABASE1S2.BTXADDR;TRUNCATE TABLE DATABASE1.DATABASE1S3.BTXSUPB; INSERT INTO DATABASE1.DATABASE1S3.BTXSUPB SELECT * FROM DATABASE1.DATABASE1S2.BTXSUPB; select count(*) from DATABASE1.DATABASE.BTXADDR; select count(*) from DATABASE1S.DATABASE.BTXADDR; select count(*) from DATABASE1.DATABASE.BTXSURB; select count(*) from DATABASE1S.DATABASE.BTXSUPB;"

         $Command.CommandType = 1 # 1 is the 'Text' command type
         $Command.Connection = $mysqlConnection

         $mysqlConnection.Open()
         $Result = $Command.ExecuteNonQuery()
         $mysqlConnection.Close()

         if ($Result -gt 0) {return $True} else {return $False}

 }
    function Execute-MySQLCommand {param(   [string]$Server,                #the host name of the SQL server
                    [string]$DATABASE1,             #the name of the database
                    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)

            $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
            $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE1;Description=DATABASE1;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE1;DATASET=DEFAULT"

            $Command.CommandType = 1 # 1 is the 'Text' command type
            $Command.Connection = $sqlConnection

            $sqlConnection.Open()
            $Result = $Command.ExecuteNonQuery()
            $sqlConnection.Close()

            if ($Result -gt 0) {return $TRUE} else {return $FALSE}
        }       

                function Copy-File {
                #.Synopsis
                # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
                param}($DATABASE0980453.pkg,"d/DATABASE1/code_stg")

                # create destination if it's not there ...
                #mkdir $destination -force -erroraction SilentlyContinue

                foreach($original in ls $source -recurse) { 
                  $result = $original.FullName.Replace($source,$destination)
                  while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }

                  if($original.PSIsContainer) { 
                   # mkdir $result -ErrorAction SilentlyContinue
                 # } else {
                    copy $original.FullName -destination $result
                  }
                        cd /d/DATABASE1/code_stg
                        install  ../DATABASE0980453.pkg

    }

    while($ElementDistro -match $DATABASE2 ) {
   
    function execute-MySqlcommand {param( [string]$Server,    #the host of the SQL server
                                            [string]$DataBase2,   #the name of the database
                                            [System.Data.MySqlclient.MySqlcommand]$Command)  #the command to execute (name of stored command)

         $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
         $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE2.DATABASE2MS2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE2.DATABASE2S3.BTXSUPB"
         $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE2.DATABASE2S2.BTXADDR;TRUNCATE TABLE DATABASE2.DATABASE2S3.BTXSUPB; INSERT INTO DATABASE2.DATABASE2S3.BTXSUPB SELECT * FROM DATABASE2.DATABASE2S2.BTXSUPB; select count(*) from DATABASE2.DATABASE.BTXADDR; select count(*) from DATABASE2S.DATABASE.BTXADDR; select count(*) from DATABASE2.DATABASE.BTXSURB; select count(*) from DATABASE2S.DATABASE.BTXSUPB;"

         $Command.CommandType = 1 # 1 is the 'Text' command type
         $Command.Connection = $mysqlConnection

         $mysqlConnection.Open()
         $Result = $Command.ExecuteNonQuery()
         $mysqlConnection.Close()

         if ($Result -gt 0) {return $True} else {return $False}

 }
        
        function Execute-MySQLCommand {param(   [string]$Server,                #the host name of the SQL server
                    [string]$DATABASE2,             #the name of the database
                    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)

            $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
            $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE2; Description=DATABASE2; Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE2;"

            $Command.CommandType = 1 # 1 is the 'Text' command type
            $Command.Connection = $sqlConnection

            $sqlConnection.Open()
            $Result = $Command.ExecuteNonQuery()
            $sqlConnection.Close()

            if ($Result -gt 0) {return $TRUE} else {return $FALSE}
            }
    
                function Copy-File {
                #.Synopsis
                # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
                param}($DATABASE0980453.pkg,"d/DATABASE2/code_stg")

                # create destination if it's not there ...
                #mkdir $destination -force -erroraction SilentlyContinue

                foreach($original in ls $source -recurse) { 
                  $result = $original.FullName.Replace($source,$destination)
                  while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }

                  if($original.PSIsContainer) { 
                   # mkdir $result -ErrorAction SilentlyContinue
                 # } else {
                    copy $original.FullName -destination $result
                  }
                    
                        cd /d/DATABASE2/code_stg
                        install ../DATABASE0980453.pkg
                    }

    While( $ElementDistro -match $DATABASE3 ) {
    
    function Execute-MySqlcommand {param( [string]$Server,    #the host of the SQL server
                                            [string]$DATABASE3,   #the name of the database
                                            [System.Data.MySqlclient.MySqlcommand]$Command)  #the command to execute (name of stored command)

         $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
         $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE3.DATABASE3S2.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE3.DATABASE3S3.BTXSUPB"
         $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE3.DATABASE3S2.BTXADDR;TRUNCATE TABLE DATABASE3.DATABASE3S3.BTXSUPB; INSERT INTO DATABASE3.DATABASE3S3.BTXSUPB SELECT * FROM DATABASE3.DATABASE3S2.BTXSUPB; select count(*) from DATABASE3.DATABASE.BTXADDR; select count(*) from DATABASE3S.DATABASE.BTXADDR; select count(*) from DATABASE3.DATABASE.BTXSURB; select count(*) from DATABASE3S.DATABASE.BTXSUPB;"

         $Command.CommandType = 1 # 1 is the 'Text' command type
         $Command.Connection = $mysqlConnection

         $mysqlConnection.Open()
         $Result = $Command.ExecuteNonQuery()
         $mysqlConnection.Close()

         if ($Result -gt 0) {return $True} else {return $False}
}
             function Execute-MySQLCommand {param(   [string]$Server,                #the host name of the SQL server
                        [string]$DATABASE3,             #the name of the database
                        [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)

                    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
                    $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE3;Description=DATABASE3;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE3;"

                    $Command.CommandType = 1 # 1 is the 'Text' command type
                    $Command.Connection = $sqlConnection

                    $sqlConnection.Open()
                    $Result = $Command.ExecuteNonQuery()
                    $sqlConnection.Close()

                    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
    }
        cd /d/DATABASE3/code_stg
            install ../DATABASE0980453.pkg
        }

                function Copy-File {
                #.Synopsis
                # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
                param}($DATABASE0980453.pkg,"d/DATABASE3/code_stg")

                # create destination if it's not there ...
                #mkdir $destination -force -erroraction SilentlyContinue

                foreach($original in ls $source -recurse) { 
                  $result = $original.FullName.Replace($source,$destination)
                  while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }

                  if($original.PSIsContainer) { 
                   # mkdir $result -ErrorAction SilentlyContinue
                 # } else {
                    copy $original.FullName -destination $result
                  }
    While($ElementDistro -match $DATABASE4 ) {
        
       function Execute-MySqlcommand {param( [string]$Server,    #the host of the SQL server
                                            [string]$DATABASE4,   #the name of the database
                                            [System.Data.MySqlclient.MySqlcommand]$Command)  #the command to execute (name of stored command)

         $mysqlConnection = new-object System.Data.MySqlclient.MySqlConnection
         $MySqlConnection.ConnectionString = "DROP_VIEW DATABASE.BTXADDR;DROP_VIEW DATABASE.BTXSUPB;CREATE_VIEW DATABASE.BTXADDR FOR DATABASE4.DATABASE42.BTXADDR;CREATE_VIEW DATABASE.BTXSUPB FOR DATABASE4.DATABASE4S3.BTXSUPB"
         $MySqlConnection.ConnectionString = "TRUNCATE TABLE DATABASE4.DATABASE4S2.BTXADDR;TRUNCATE TABLE DATABASE4.DATABASE4S3.BTXSUPB; INSERT INTO DATABASE4.DATABASE4S3.BTXSUPB SELECT * FROM DATABASE4.DATABASE4S2.BTXSUPB; select count(*) from DATABASE4.DATABASE.BTXADDR; select count(*) from DATABASE4S.DATABASE.BTXADDR; select count(*) from DATABASE4.DATABASE.BTXSURB; select count(*) from DATABASE4S.DATABASE.BTXSUPB;"

         $Command.CommandType = 1 # 1 is the 'Text' command type
         $Command.Connection = $mysqlConnection

         $mysqlConnection.Open()
         $Result = $Command.ExecuteNonQuery()
         $mysqlConnection.Close()

         if ($Result -gt 0) {return $True} else {return $False}
}       
        function Execute-MySQLCommand {param(   [string]$Server,                #the host name of the SQL server
                    [string]$DATABASE4,             #the name of the database
                    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)

    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = "DATABASE_CONNECT_STRING=DSN=DATABASE4;Description=DATABASE4;Trusted_Connection=Yes;WSID=Server;DATABASE=TF90PVS;"

    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $sqlConnection

    $sqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $sqlConnection.Close()

    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
   
function Copy-File {
#.Synopsis
# Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists
param}($DATABASE0980453.pkg,,"d/DATABASE4/code_stg")

# create destination if it's not there ...
#mkdir $destination -force -erroraction SilentlyContinue

foreach($original in ls $source -recurse) { 
  $result = $original.FullName.Replace($source,$destination)
  while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") }

  if($original.PSIsContainer) { 
   # mkdir $result -ErrorAction SilentlyContinue
 # } else {
    copy $original.FullName -destination $result
  } 

    cd /d/DATABASE4/code_st
    install ../DATABASE0980453.pkg
}
     While($ElementDistro -match $ALL ){

     function Execute-MySQLCommand {param(  [string]$Server,              #the host name of the SQL server
                    [string]$DATABASE1,$DATABASE2,$DATABASE3,$DATABASE4,                #the name of the database
                    [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)

    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = "(DATABASE_CONNECT_STRING=DSN=DATABASE1;Description=DATABASE1;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE1;DATASET=DEFAULT;),(DATABASE_CONNECT_STRING=DSN=DATABASE2; Description=DATABASE2; Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE2;),(DATABASE_CONNECT_STRING=DSN=DATABASE3;Description=DATABASE3;Trusted_Connection=Yes;WSID=Server;DATABASE=DATABASE3;),(DATABASE_CONNECT_STRING=DSN=DATABASE4;Description=DATABASE4;Trusted_Connection=Yes;WSID=Server;DATABASE=TF90PVS;)"

    $Command.CommandType = 1 # 1 is the 'Text' command type
    $Command.Connection = $sqlConnection

    $sqlConnection.Open()
    $Result = $Command.ExecuteNonQuery()
    $sqlConnection.Close()

    if ($Result -gt 0) {return $TRUE} else {return $FALSE}
 }  
  
    install ../DATABASE0980453.pkg
     }
     
 While($ProductionDistro -match $Cyc) {
 write-host "Sets up location you want to run staging"
        $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
        While($ElementDistro -notmatch "(DATABASE1|DATABASE2|DATABASE3|DATABASE4|ALL)") {
            write-host "you have enterd an error" -ForgroundColor Red
            write-host "You must type DATABASE1 or DATABASE2 or DATABASE3 or DATABASE4 or ALL"
            write-host "you typed $ElementDistro"
            write-host "set location you want to run staging"
          $ElementDistro = Read-Host -Prompt "Which Element do you want to run? (DATABASE1/DATABASE2/DATABASE3/DATABASE4/ALL)"
 }
}
}}}}}

Home directory scripting

$
0
0

I am trying to script H drive creatation for new user builds via MS Orchstrator. I have a script that I put together that does add the appropriate permissions to the folder but only if I run the script as a domain admin. When I try to run the script as the orchestrator service account I get the below error message.

set-acl : The process does not possess the 'SeSecurityPrivilege' privilege which is required for this operation.

At line:11 char:1

The service account does have access to the home drive share as I can do all of these steps manually. The main difference between the service account and my domain admin account is the Domain admin account has full control while the service account has "special" permissions and then given full control there. Can someone point me in the right direction as to my mistake? set-acl : The process does not possess the 'SeSecurityPrivilege' privilege which is required for this operation. At line:11 char:1

$acl= get-acl "\\share\users\userid"

$DirectoryOwner = New-Object System.Security.Principal.NTAccount("userid")

$Nuser = "userid","FullControl","ContainerInherit,ObjectInherit","none","allow"

$ar = New-Object System.Security.Accesscontrol.FileSystemAccessRule $nuser

$acl.SetAccessRule($ar)

$acl.SetOwner($DirectoryOwner)

$acl.SetAccessRuleProtection($true,$true)

set-acl "\\Share\users\userid" $acl

internetexplorer.application activex component can't create object

$
0
0

I am getting the infamous 429 error with a new image of Windows 2003 Server.

I am sure this is an issue with the Windows 2003 Server image, so I have to figure out a work around to get this  to work.  No updates to the image are possible.  I have been searching for a solution for a couple of days and nothing I have tried has worked so any assistance you can provide is most welcome.

This script works just fine on my Windows 7 machine and used to work just fine on the previous image of Windows 2003 Server I had which is no longer available:

Err.Number: 429

Err.Description: "ActiveX component can't create object"

Here is the code:

On Error Resume Next
'
Set fsoObj = CreateObject("Scripting.FileSystemObject")
'
Dim objIE
'
Err.Clear
'
Set objIE = CreateObject( "InternetExplorer.Application" )
'
If ( Err.Number <> 0 ) Then
   '
   WScript.Echo "Number (" & Err.Number & ")" & vbCrLf _
              & "Description [" & Err.Description & "]"
   WScript.Quit
   '
End If
'
objIE.Navigate "about:blank"
objIE.Width          = 200
objIE.Height         = 300
'
Do Until objIE.ReadyState = 4
   WScript.Sleep 200
Loop
'
Do While objIE.Busy
   WScript.Sleep 200
Loop
'
bodyStr = javaScriptStr & "<table align='center'><tr><td align='center' colspan='2'>Click Run or Cancel</td></tr>" _
        & "<tr align='center'>" & vbCrLf _
        & "<td colspan='2'>" & vbCrLf _
        & "<input type='submit' value=' Run ' " & "OnClick='VBScript:OK.Value=1'>" & vbCrLf _
        & " &nbsp; &nbsp; " & vbCrLf _
        & "<input type='submit' value=' Cancel ' " & "OnClick='VBScript:CANCEL.Value=1'>" & vbCrLf _
        & "</td></tr>" & vbCrLf _
        & "</table>" & vbCrLf _
        & "<input type='hidden' id='CANCEL' name='CANCEL' value='0'>" & vbCrLf _
        & "<input type='hidden' id='OK' name='OK' value='0'>"

'
objIE.Document.Body.InnerHTML = bodyStr
objIE.Visible = True
'
Do While ( ( objIE.Document.All.CANCEL.Value = 0 ) AND ( objIE.Document.All.OK.Value = 0 ) )
   '
   WScript.Sleep 200
   '
   If Err Then ' user clicked red X (or alt-F4) to close IE window
      '
      objIE.Quit
      Set objIE = Nothing
      logFile.WriteLine Now & " - aborting input!"
      '
   End if
Loop
'
objIE.Quit
'


need help finding out which accounts in an OU aren't members of a certain security group

$
0
0

Hi all,

I'm new to scripting but I think what I need might be relatively simple. I have about 40 department OU's that contain users. Each user in that OU needs to be a member of that department's security group for our My Docs redirection to work. For example, users in the Human Resources OU need to be a member of "HR (Everyone)".  I'm hoping to find out which users in an OU are NOT in that group. Of course, I'd love to be able to run this against all user OU's at once but they would need to be members of their respective groups so that may not easily be possible. I don't mind if I have to go one OU at a time.

Our domain function level is 2008 R2 if that is needed.

I hope I've provided enough information and thanks in advance!


Getting Data from SCCM

$
0
0

Getting data from SCCM via Get-WmiObject

If anyone can help me out I would certainly appreciate it. I'm new to powershell and I'm not understanding it very well.

Here is what I'm trying to do, I have a script that pull computername from a txt file and does a foreach to bring back the data for each computer. I guess my syntax is not correct and I've been looking everywhere for information on how to do this.

Here is my script below.


    $list = import-csv -path '.\Computers.txt'

    $objectCollection=@()


    $list | %{
        $wmi_computersystem = Get-WmiObject -Class win32_ComputerSystem -ComputerName $_.computername
        $wmi_SCCM = Get-WmiObject -Class SMS_R_System -ComputerName HFDSCCM -Namespace "root\SMS\Site_HFD" -Filter $("Name = '$_.computername'")

        $object = New-Object psobject
        Add-Member -InputObject $object -MemberType NoteProperty -Name Name -Value $wmi_computersystem.Name
        Add-Member -InputObject $object -MemberType NoteProperty -Name SCCM_HostName -Value $wmi_SCCM.Name
        Add-Member -InputObject $object -MemberType NoteProperty -Name SCCM_OS -Value $wmi_SCCM.ADSiteName
       
       
                $objectCollection +=  $object

        $object
$objectCollection | export-csv -path '.\ComputerInfo.csv' -NoTypeInformation -Append
    }

Trying to use multiple if statements to set a variable in my script

$
0
0

I am importing a csv file to create user accounts.. i have it working.. but now i want to have the script look at a variable, and based on that variable set other variables, like the ou or home directory path etc..

here's what i have so far.. it seems to select the 2nd option ASH unless i # it out then it selects the first option..i am clearly missing something simple here.... i can't just use an else statement as i will need many lines of logic to support the many different ou's, home dir shares etc.. globally...

import-csv $csv | foreach-object {

                   

 $site=$_.site
                   $HomeDArl= "\\teleflex\global\home\medical\na\arl"
                   $HomeDASH= "\\ashfs01.arrowintl.com\user"

                        if ($site='ARL'){
                            $homed = $HomeDArl
                        }
                        if ($site='ASH'){
                            $homed =$HomeDASH 
                        } 

}


Script to disable USB 'Power Management'?

$
0
0

   I'd like to have the capability to have the "Allow the computer to switch off the USB port to conserve power' box unchecked. Instead of manually going to each PC, it would be great if I could run a script. Anybody out there know how to do this? Any help is gratefully appreciated.

Thank you,

Joao


Power shell script to add multiple aliases with a .csv file.

$
0
0

I have an email address lets say project@mailserver.org and I need 1000 aliases added to the email. For example Project1@mailserver.org, Project2@mailserver.org etc etc. and I have a .csv file with 990 columns with just project1, project2.

Is there a way to run a command in powershell exchange to import all the aliases I need in a few commands? Can someone point me in the right direction if I am in the wrong forum also? Thanks

No sure if this is correct or not:

> $mbx = Get-Mailbox Project
> Import-CSV "C:\SomePath\wherever.csv" | foreach { $mbx.EmailAddresses += $._SmtpAddress }
> Set-Mailbox project -EmailAddresses $mbx.EmailAddresses

Find installed software on Domain

$
0
0

HI All,

  I just want to find the installed software. Found following command but with the computerlist.txt file

  But i need to know run against domain combining these two below command?

================================================cmd 1========= 

 Get-ADComputer -Filter * -SearchBase "OU=Computers,OU=myour,DC=domain,DC=com,DC=au" | ForEach-Object {$strComputerName = $_.Name;.....

=========================cmd 2=============================

Get-Content'c:\computerlist.txt'| ForEach-Object{Get-WMIObject-ComputerName$_-Query"SELECT * FROM win32_product WHERE name LIKE '%firefox%'"|Select-Object-Property$_,Name,InstallLocation,InstallDate|Export-CSV'c:\computerqueryresults.csv'

==============================================================

AS

  

email signature

$
0
0

any one got any sample html code for exchange 2013 email signatures?

I'd like to grey out the disclaimer and bold and enlarge the company name, maybe even add an image?


Some stuff works great in webmail but not MS Outlook so it has to be conservative enough to work in both.

for example this works great in webmail but not so good in MS Outlook from exchange 2013

<div style="font-size:12pt; font-family: 'Calibri' ,sans-serif; ">
<STRONG>%%DisplayName%%, %%Company%%</strong><br>
<div style="font-size:11pt; font-family: 'Calibri' ,sans-serif; ">
%%Title%%<br>
%%StreetAddress%%, %%City%%, %%StateorProvince%% %%PostalCode%%<br>
Tel: %%Phone%% | Fax: %%FaxNumber%% | Email: %%email%% <br>
<br>
<hr>
<font face="Arial" color="Gray" size="2">CONFIDENTIALITY NOTICE: The information contained in or attached to this e-mail may be confidential information subject to protection by law or terms of applicable confidentiality agreements, and is intended only for the use of the individual or entity named above. If the reader of this message is not the intended recipient, or the employee or agent responsible to deliver it to the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication is strictly prohibited. If you are not the addressee indicated in this message (or responsible for delivery of the message to such person), you should destroy this message and notify the sender by reply email.

Getting Help on WMI Classes

$
0
0

Hi,

Does PowerShell provide help for WMI classes? I know Get-Help <cmdlet> gives information about the cmdlet. But is there something like, Get-Help <WMI class> which gives the information about the WMI class?

Ex: Get-Help Win32_Bios


Thanks!


NM

Can't find my mistake

$
0
0

I am writing a user creation script and just working through my variables at this point.  So i have the script importing a csv file with user info.  Based on that user info it creates a series of variables three of which i am using the switch command to choose the string that is associated with another string.  that all seems to work fine however when the message to type the $dept variable.  the read-host is showing the $upn of the first user to go through not the user that it is actually setting the variable for.  like i said the variables seem to be setting properly just the output in the shell shows the wrong upn for what i am updating.. code and output below:                                                       

function TFX-CreateNewUsers{
       [CmdletBinding()]
        param(
            [string]$logfile = 'c:\PowerShell_Logs\UserCreationErrors.txt',

            [Switch]$LogErrors,

            [Parameter(Mandatory = $true,
                       valuefrompipeline = $true,
                       HelpMessage = "Please provide valid path and file name to the CSV file with the user information.")]
            [Alias('csv')]
            [string]$FilePath
         )

        $date = Get-Date -Format g
        $addn = (Get-ADDomain).DistinguishedName
        $dnsroot = (Get-ADDomain).DNSRoot
        $userlist = Import-Csv $FilePath

        $userlist | ForEach-Object{
              If (($_.GivenName -eq '') -Or ($_.LastName -eq ''))
                   {Write-Host 'ERROR: Please provide valid GivenName, LastName and Initials. Processing stopped' -ForegroundColor Red
                   "$date ERROR: Please provide valid GivenName, LastName and Initials. Processing stopped" | Out-File $logfile -Append
                   Break
                   }
              Else {
                   $upn="$first.$last@company.com"
                   $site=$_.site
                      switch ($site) {
                          Arl {$homed = "\\share\global\home\medical\na\arl"}
                          Ash {$homed ="\\share2\user"}
                      }
                      switch ($site) {
                          Arl {$HDrive = "H:"}
                          Ash {$HDrive ="U:"}
                      }
                      switch ($Site) {
                        Arl {$ou="OU=Users,OU=ARL,OU=NA,OU=company,DC=company,dc=global,dc=pvt"}
                        Ash {$dept = Read-Host "Enter Asheboro Department for $upn. Accounting, Engineering, Human Resources, Information Technology, Manufacturing, or Quality Assurance"
                             $ou="OU=$dept,OU=Users,OU=ARL,OU=NA,OU=company,DC=company,dc=global,dc=pvt"}
                        }
                   $First=$_.GivenName
                   $last=$_.LastName
                   $sam=$first.substring(0,1) + $last
                   $Office=$_.OfficeName
                   $description=$_.Description
                   $street=$_.StreetAddress
                   $city=$_.City
                   $zip=$_.postalcode
                   $state=$_.state
                   $Company=$_.Company
                   $Dept=$_.Department
                   $Title=$_.title
                   $mail=$upn
                   $phone=$_.phone
                   $manager=$_.manager
                   $Location=$_.Country
                   $pass=$_.Password
                   $expires=$_.passwordneverexpires
                   $Enabled=$_.Enabled
                   $setpass = ConvertTo-SecureString -AsPlainText $pass -force
                   $display="$last, $first"
                   Write-Verbose "$sam,$HomeD,$HDrive,$OU,$phone,$site"
                   }
        }


}

Output when showing my variables and asking for the dept

VERBOSE: SRogers3,\\share\global\home\medical\na\arl,H:,OU=Users,OU=ARL,OU=NA,OU=company,DC=company,dc=global,dc=pvt,ARL
Enter Asheboro Department for Steve.Rogers3@company.com (This should be the user below). Accounting, Engineering, Human Resources, Information Technology, Manufacturing, or Quality Assurance: asdf
VERBOSE: EScott,\\share2\user,U:,OU=asdf,OU=Users,OU=ARL,OU=NA,OU=company,DC=company,dc=global,dc=pvt,,ASH





is it possible to add value to the attributes of in ADSIedit?

$
0
0

I had been using PowerShell version 3 and use LDAP query to query out both attributes and value from Active Directory. 

Is it possible to use powershell script to set value to the description attributes which had been written as <not set> in ADSIedit?

Or I need to change the the ADSIedit <not set> value before I am able to add value to <not set> description attributes?

Windows Scripting to copy files

$
0
0

Hi there,

New to Windows scripting. 

I have tried to create a simple script to copy file but failed. Most probably the syntax is wrong. Pls help. thanks.

I give you my code below:

@ECHO OFF
SETLOCAL

REM SET INDIR="\\sge-fs01\enablers_development\ptc\OUTGOING"
SET SLIFTCMD="C:\Program Files\PrivyLink\SLIFT-Ez Classic\1.4\SLIFTC.exe"
SET PFX="C:\PrivyLink\KeyPeer\111111.pfx"
SET PFXPWD="pass12345"
SET CER="C:\PrivyLink\KeyPeer\sgesftpuser.cer"
SET PATTERN="*.IN"
SET DSTDIR="C:\SFTP\OUTBOUND"
SET BKDIR="C:\SFTP\BACKUP"
SET SENDDIR="C:\SFTP\SENDTO"
SET INDIR="C:\SFTP\PTC\OUTGOING"

REM ####### MAIN CALL #########
CALL:MainScript
GOTO :EOF

REM ####### Check Files in PTC OUTGOING #########
:MainScript
SETLOCAL

@ECHO OFF
PUSHD %INDIR%
IF EXIST "C:\SFTP\PTC\OUTGOING\*.IN"
(   
COPY "C:\SFTP\PTC\OUTGOING\*.IN" %DSTDIR%


ELSE 
(
      echo "There are no files today - %date:~-4,4%%date:~-7,2%%date:~-10,2%" >> C:\SFTP\PTC.log
pushd %~dp0
start "" cmd /c cscript SMTP.vbs

)       


POPD
ENDLOCAL
GOTO :EOF

REM ####  END ########


How to loop out selected property?

$
0
0

Hi,

how to loop out the selected input value and able to loop out the rest of the property from imported csv file?

For example, I want to look properties from just based on the sAMAccountName.

This is my scripting:

$userInfo = Import-CSV D:\info.CSV 

$name = @()
$sAMAccountName = @()

ForEach-Object {
$sAMAccountName = $userInfo.sAMAccountName

$name = $userInfo.properties
}

$inputName = Read-Host -Prompt "Input sAMAccountName"

if ($sAMAccountName -contains $inputName)
    {
    Write-Host "Users Exists"
    $Where = [array]::IndexOf($sAMAccountName, $inputName)
    Write-Host "property Name: " $Name[$Where]
    }

else 
    {
    write-host 'error: '  $Error
    }


This is what I get:


Running VBScript on remote computer....aaarrrrggghhh

$
0
0

Hello all,

I have a vbscript that I cannot run on a remote computer, it uses psexec to run and if I run the line from a local CMD prompt it works,


psexec.exe \\computername cscript.exe c:\wuafix\wuafix.vbs

If I try and run it from a script as per below, it doesn't run, what am I doing wrong??the strComputer is using a input box to parse the correct computer name OK as the previous parts of the script work...all I see when I run the whole script is what looks like the psexec screen for a fraction of a second... and then the script exits

'set command line executable to run a silent install remotely
strInstaller1 = "cscript.exe c:\wuafix\wuafix.vbs"
'strInstaller2 = "c:\wuafix\wuafix.vbs"
strExec = "c:\pstools\PsExec.exe " 

objshell.Run strExec & " \\" & strComputer & strInstaller1

the whole script Is below which I have modified, I have only been using VB for a week so not really sure what to look for and also I know it could be tidied up, but for now I would like to get the PSEXEC line working, or is there another way to get the vbscript running on a remote machine, the file itself is copied over earlier in the script. I appreciate anyone's help on this

'setting objects
Dim net, objFSO, shell
Dim objFile, strLine, intResult
Set objnet = CreateObject("wscript.network")
Set objFSO = CreateObject("scripting.filesystemobject")
Set objshell = CreateObject("wscript.shell")
strfile = "c:\wuafix\wuafix.vbs"
strUser = "domain\user"
strPassword = "password"
'getting server name or IP address
strComputer=InputBox("Enter the IP or computer name of the remote machine on which to repair the WUA agent:", "Starting WUA Fix")
'check to see if the server can be reached
Dim strPingResults
Set pingExec = objshell.Exec("ping -n 3 -w 2000 " & strComputer) 'send 3 echo requests, waiting 2secs each
strPingResults = LCase(pingExec.StdOut.ReadAll)
If Not InStr(strPingResults, "reply from")>0 Then
  WScript.Echo strComputer & " did not respond to ping."
  WScript.Quit
End If
'Check if source file exists
If Not objFSO.FileExists(strFile) Then
   WScript.Echo "The source file does not exist"
   WScript.Quit
End If
MsgBox "The WUA Fix  is in process.  Please wait.", 64, "Script Message"
'mapping drive to remote machine
If objFSO.DriveExists("Z:") Then
objnet.RemoveNetworkDrive "Z:","True","True"
End If
objnet.MapNetworkDrive "Z:", "\\" & strComputer & "\c$", True
'creating folder for install exe on remote machine
If (objFSO.FolderExists("Z:\wuafix\") = False) Then
   objFSO.CreateFolder "Z:\wuafix"
End If
'copying vbs to remote machine
objFSO.CopyFile strFile, "Z:\wuafix\wuafix.vbs"
'set command line executable to run a silent install remotely
strInstaller1 = "cscript.exe c:\wuafix\wuafix.vbs"
'strInstaller2 = "c:\wuafix\wuafix.vbs"
strExec = "c:\pstools\PsExec.exe " 

objshell.Run strExec & " \\" & strComputer & strInstaller1

Sub Pause()
    WScript.Echo ("Press Enter to continue")
    z = WScript.StdIn.ReadLine()
End Sub

'checking if log file is present and parse through the log for Successful message
'strLogFile = "z:\Program Files\APPQcime\CimExtensions\APPQcime_CIM_Extensions_InstallLog.log"
'CONST ForReading = 1 
'If objFSO.FileExists(strLogFile) Then
'   Set objFile = objFSO.OpenTextFile(strLogFile, ForReading)
'   strLine = objFile.Readline
'   Do Until objFile.AtEndofStream 
'    strLine = objFile.ReadLine
'    intResult = InStr(strLine, "Installation: Successful")
'    If intResult <>0 Then
'   		WScript.Echo("CIM Extension Agent was installed for " & strComputer & " on " & Time & " " & Date)
'    End If
'   Loop  
' Else
'   WScript.echo "Unable to install the agent. Please try again"
' End If
'removing mapped drives
'objFile.Close
'objnet.RemoveNetworkDrive "Z:"
'quit
'wscript.quit


many thanks

WMI Class corresponding diskpart vdisk available?

$
0
0

Hello,

does anyone know if there is a WMI Class which gives the info I get with diskpart - list vdisk (specifically the file property)? I know there are some classes for Hyper-V, however looking for non hyper-v systems (local attached vhd's).

Thanks

Florian

VBScript to check if a user is a group member runs on Windows 7 & 8 but not on XP

$
0
0

Hi all,

I have a VBS function (IsMember) to check whether a user is a member of a group or not - The domain, username and group name are passed in when the function is called... My dilemma is that it works fine in Windows 7/8/Server 2008 R2/2012 R2 etc. but fails when run on XP/Server 2003 with the fairly generic error of 0x80005008 at source (null). I'm wondering if it could be something syntax related with my query? Or if there is perhaps a component I am trying to reference that doesn't exist in XP?

The key thing is that I need to be able to pass in the username and group name on the fly and that I won't know the full LDAP path of either the user or the group.

Here's the function;

IsMember "domain", "username", "group"

Function IsMember(Domain, User, Group)
	Dim oConnect, oRecordSet, oGroup

	Set oConnect = CreateObject("ADODB.Connection")
	oConnect.Open = "Provider=ADsDSOObject"

	Set oRecordSet = oConnect.Execute("SELECT AdsPath FROM 'LDAP://" & Domain & "' WHERE cn='" & Group & "'")

	Set oGroup = GetObject(oRecordSet("AdsPath"))
	If (oGroup.IsMember("LDAP://" & User)) Then
		IsMember = True
	Else
		IsMember = False
	End If

	oConnect.Close

	Set oConnect = Nothing
	Set oGroup = Nothing
	Set oRecordSet = Nothing
End Function

If anyone has any suggestions or ideas as to where I might be going wrong I'd be very grateful.

James



Server2012/Win8.1/PowerShell4.0 set printer permissions for multiple printers

$
0
0

Hey Scripting Guys!

looking at the new Set-Printer command for 2012/Powershell4.0. 

we have a bunch of printers already added. I have changed the global perms on the printer server, but would like to mod the perms on existing printers. Anyway to do it via powershell?

cheers

Stu w

Viewing all 15028 articles
Browse latest View live


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