Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

IF Else Statement

$
0
0

Hello,

I am running several scripts similar to the one below. While the script is running, it gives me a list of computers not responding along with a few other errors that I would like to capture on a report to keep track of which computers failed to run the script. Below the script are some of the errors I am getting. Is this report possible?

$password = "P@ssw0rd12345!"
$computers = Get-Content -path "C:\enumerated\Backup Admin Accounts.txt"
foreach ($computer in $computers)
{
   If (Test-Connection -ComputerName $computer -Count 1 -Quiet)
    {
        $userName = [ADSI]"WinNT://$computer,computer"
        $LocalAdmin = $userName.create("User", "Backup Admin")
        $LocalAdmin.SetPassword($Password)
        $LocalAdmin.SetInfo()
    }
    else
    {
        Write-Host "$computer is not responding"
    }
    }
   

 

Test-Connection : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument that is not n
ull or empty and then try the command again.
At line:5 char:37
+    If (Test-Connection -ComputerName <<<<  $computer -Count 1 -Quiet)
    + CategoryInfo          : InvalidData: (:) [Test-Connection], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand

 

The following exception occurred while retrieving member "create": "Access is denied.
"
At line:8 char:22
+         $LocalAdmin = <<<<  $userName.create("User", "Backup Admin")
    + CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemException
    + FullyQualifiedErrorId : CatchFromBaseGetMember

 

$computer is not responding
$computer is not responding


Reset a Computer Account's Active Directory Password from the Command Line

$
0
0

Q: How can I reset a Windows computer account's Active Directory password from the command line?

Read More

PowerShell File Frontier, Part 3: Right Tool for the Job

$
0
0

Over the last few lessons we've been exploring different ways of filtering for files. On one hand using separate cmdlets in a pipelined expression is the "right" way, I also recognize the need for an easier to use tool. So I created a wrapper function to Get-ChildItem called Get-MyFile. Here is the code:

Read More 

Invoke-command with "Run As Administrator" on remote machines.

$
0
0

Hi,

I'm trying to run a command on a remote machine with the invoke-command cmdlet. The command fails with access denied in the eventlog. I need to run the remote session with "Run As Administrator" on the remote machine. Any direction on how to this is greatly appreciated.

Example:

$computers= get-content "./servers.txt"

Invoke-command -ScriptBlock {c:\temp\example.cmd} -ComputerName $computers

Rename Files in a Directory

$
0
0

I have to rename files in a directory that are pictures but use a number as the extension for a card system. The picture numbers are UID's that relate to individuals. I have been trying to do this in a Batch file but getting many errors. The file name look like this

00000.1
00001.2
00123.3
88001.4
12345.7

What i need to do is first strip the "." and change the extension to .JPG

so the first file would be:

000001.jpg

Then strip leading zeros only  so i would end with

1.jpg
12.Jpg
or
880014.jpg

this will be added to a bat file or a ps1 file that Deletes all files from a directory to update with new files renames them then Uploads them to a new location. The first 2 steps and last step i have completed using robocopy. Would rename Item work? or does that only work on current directory. In which case the delete would delete the bat file calling it... Head hurts

Running a command line command with powershell

$
0
0

I have been trying to run a couple of dos commands with in powershell. I need to run a couple of TSMVE commands on a bunch of servers.

TSMVE commands

Change directory to 1 utf-8

0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4C:\Program Files\Tivoli\TSM\baclient

run this command

dsmc set password -type=vm servername  AD\username password -optfile=t:\TSMVE_Jobs\servername.opt

Then on some server we can run this command. My other issue is that I have quotes within quotes. So I'm not sure quotes within quotes with my varaible $cmdLineBSCHED.

1 utf-8

0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4dsmcutil inst scheduler /name:"TSM-serveraname-Backup-Scheduler" /node:servername/password:password /clientdir:"c:\program files\tivoli\tsm\baclient" /optfile:"D:\TSM_Jobs\servername_Backup_dsm.opt" /autostart:Yes

 

$tool="cmd.exe C:\Program Files\Tivoli\TSM\baclient"


$cmdLineSVC = "dsmc set password -type=vm" + " " + $VMCHOST + " " + "ms\tsmve password -optfile=t:\TSMVE_Jobs\" + $servername + "_TSMVE_Proxy_dsm.opt"


$cmdLineBSCHED = "dsmcutil inst scheduler /name:" + ""TSM-"" + $SERVERNAME + "-Backup-Scheduler"" +  "/node:" + $SERVERNAME + "/password:" + $DC + $servername + "/clientdir:""c:\program files\tivoli\tsm\baclient"" /optfile:""D:\TSM_Jobs\" + $SERVERNAME + "_Backup_dsm.opt"" /autostart:Yes"
           
 ###################### Creates TSVE Service #################
            invoke-expression "$tool $cmdLineSVC"
           
################## Install Local Backup Scheduler  #################
            invoke-expression "$tool $cmdLineBSCHED"

using Powershell to query Removable Storage Manager in win 2003

$
0
0

I am trying to use PS to get information about tapes in RSM (Removable Storage Manager).

I have been unable to find any posts that refer to "Removable Storage Manager" on the Powershell site.

So far I have been ale to use RSM commands to query the libraries and tapes, and parse the output, but I am unable to get information on mount counts.

Can someone point me in the right direction?

 

thanks,

Ole Jensen.

Parsing an array to a function

$
0
0

Hello,

 

I am wondering if someone can give me a quick hand on a function I am writting which it is not behaving in the way I am expecting.
I want to call this function by doing a (Get-Content .\Users.txt) | Get-ProfilePath
The script works fine but it only gets 1 users ProfilePath. It is not parsing correctly as it would be an array of users.

 

functionGet-ProfilePath {

param (
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true
)]
[String[]]$Users
)

foreach ($userin$Users)
{
$userDN= (Get-ADUser$User).distinguishedName
$userDN
$userInfo= [ADSI]"LDAP://$userDN"
$userINfo
if ($userInfo.TerminalServicesProfilePath ) {$userInfo.TerminalServicesProfilePath | get-oldnavision }
}

}

Creating Your Own PowerShell Command

$
0
0

Last week, I posted a PowerShell function that you could use as an accelerator to create your own PowerShell tools. My tool takes command metadata from an existing PowerShell cmdlet and gives you the structure to create your own tool wrapped around what is in essence a proxy function.

Read More

call script event

$
0
0

I have a puzzling problem:

I have a script that when I click in a button, it runs another .ps1 script. In Powershell ISE it works perfectly, but when I start from a Batch Script it not work, not start the second script.
The event:

Register-ObjectEvent $call_x1 Click click_event -Action {
    Invoke-Expression "E:\Tests\x1.ps1"

Installing Windows Updates using Powershell

$
0
0

Hello Everyone,

I have no Powershell experience but need to learn it. We are transitioning to IBM BigFix for patches and can't seem to get it up and running. This is being fixed as we speak but we have an internal audit coming up in a few days and have tons of machines on a text file missing different patches. I have the computer name on a text file. Can someone guide me in the right direction on how to create a script for this? I really need it fast since this will be our workaround until we can get BigFix up and running smoothly.

 

Displaying a nested group hierarchy

$
0
0

I have an organization that loves nested groups in Active Directory.  I have found that nested groups can easily get out of control without good business practices and excellent documentation. 

I have been using Get-ADGroupMember to list the members of an AD group.  The -recursive switch listing all members.  It does however list child groups as it passes through the hierarchy.  To display these group I have a function: 

function Get-GroupHierarchy ($searchGroup)
{
import-module activedirectory
$groupMember = get-adgroupmember $searchGroup | sort-object objectClass -descending
   foreach ($member in $groupMember)
    {Write-Host $member.objectclass,":", $member.name;
    if ($member.ObjectClass -eq "group")
        {Get-GroupHierarchy $member.name}}
}

Sharing problems with $ExecutionContext.InvokeCommand.NewScriptBlock

$
0
0

Hello.

I realy hope someone can help me here. I´m trying to create a folder on a remote server and then share this folder. The folder is created but it doesn´t get shared. I always get this error message:

The syntax of this command is:
    + CategoryInfo          : NotSpecified: (The syntax of this command is::String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName      :
Myserver.domain.com
NotSpecified: (:) [], RemoteException
NET SHARE
sharename
          sharename=drive:path [/GRANT:user,[READ | CHANGE | FULL]]
                               [/USERS:number | /UNLIMITED]
                               [/REMARK:"text"]
                               [/CACHE:Manual | Documents| Programs | BranchCache | None]
          sharename [/USERS:number | /UNLIMITED]
                    [/REMARK:"text"]
                    [/CACHE:Manual | Documents | Programs | BranchCache | None]
          {sharename | devicename | drive:path} /DELETE
          sharename \\computername /DELETE

 

This is my script: (when i run the NET SHARE-command localy on the server the share works):

# Credentials
    $username = "domain\user"
    $pass = convertto-securestring -String "MyPassword" -AsPlainText -Force
    $cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist $username, $pass

# Create DIR and Share-commands
    $CreateDir = $ExecutionContext.InvokeCommand.NewScriptBlock("mkdir F:\test\user")
    $CreateShare = $ExecutionContext.InvokeCommand.NewScriptBlock("NET SHARE user=F:\test\user /GRANT:everyone,FULL")


# Run them
    Invoke-Command -ComputerName "Myserver.domain.com" -ScriptBlock $CreateDir -Credential $cred
    Invoke-Command -ComputerName "Myserver.domain.com" -ScriptBlock $CreateChare -Credential $cred

 

I hope someone can help!

Exporting from Active Directory (SBS) list of active and disabled domain users to a txt file

$
0
0

Hi everyone,

As you'll see I'm pretty much "fresh" in PowerShell.
I've found this Ed Wilson's script named "FindDisabledUserAccounts.ps1" and it works perfectly on my Small Busyness Server with PowerShell 2.0.
It even lists all active domain users in green and disabled users in red colour, which makes it very easy to navigate through results.
My problem is that I can't find a way to export those results to txt file for a report purposes.
I added that last line "Out-File D:\SBS_users.txt" to Ed's script and it saves txt file right on the spot with no problem whatsoever.
Problem is that txt file in question is always EMPTY, there is NO single line in it?
I can't export results directly to csv format 'cause there is no MS Office Excel instalation on SBS.
Please help.
Thanks in advance.

Script - FindDisabledUserAccounts.ps1:

$filter = "(&(objectClass=user)(objectCategory=person))"
$users = ([adsiSearcher]$Filter).findall()

 foreach($suser in $users)
  {
   "Testing $($suser.properties.item(""distinguishedname""))"
   $user = [adsi]"LDAP://$($suser.properties.item(""distinguishedname""))"
 
   $uac=$user.psbase.invokeget("useraccountcontrol")
     if($uac -band 0x2)
       { write-host -foregroundcolor red "`t account is disabled" }
     ELSE
       { write-host -foregroundcolor green "`t account is not disabled" }
  } #foreach
Out-File D:\SBS_users.txt

How to Convert OLM to PST Tool?

$
0
0

To convert OLM file to PST file format, I recommended an excellent or hassles free software, you can use Kernel for OLM to PST Converter Tool. This application efficient to convert MS Outlook 2011 for Mac (OLM file) to Microsoft Outlook for Windows (PST file). It can also migrate MS Outlook 2011 for Mac to Microsoft Outlook 2003, 2007, 2007 & 2013. This software also convert all email, attachments, contacts, calendar, tasks and other folders to Outlook PST file format. 

 

To get more details click here : http://www.olmfileconverter.net


Script not work on console

$
0
0

Somebody know why this script works fine in Powershell_ISE but when running in the console doesn’t seem to catch the click events?




[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)#Remove any registered events related to notifications
Remove-Event BalloonClicked_event -ea SilentlyContinue
Unregister-Event -SourceIdentifier BalloonClicked_event -ea silentlycontinue
Remove-Event BalloonClosed_event -ea SilentlyContinue
Unregister-Event -SourceIdentifier BalloonClosed_event -ea silentlycontinue#Create the notification object
$notification = New-Object System.Windows.Forms.NotifyIcon

#Define the icon for the system tray
$notification.Icon = [System.Drawing.SystemIcons]::Information

#Display title of balloon window
$notification.BalloonTipTitle = “This is a Balloon Title”

#Type of balloon icon
$notification.BalloonTipIcon = “Info”

#Notification message
$title = “This is the message in the balloon tip.”
$notification.BalloonTipText = $title

#Make balloon tip visible when called
$notification.Visible = $True

## Register a click event with action to take based on event
#Balloon message clicked
register-objectevent $notification BalloonTipClicked BalloonClicked_event `
-Action {.\Test.ps1} | Out-Null

#Balloon message closed
register-objectevent $notification BalloonTipClosed BalloonClosed_event `
-Action {[System.Windows.Forms.MessageBox]::Show(“Balloon message closed”,”Information”);$notification.Visible = $False} | Out-Null

#Call the balloon notification
$notification.ShowBalloonTip(600)



Citrix Scripting: Automating VM operations on XenServer using PowerShell

$
0
0

With the release of the XenServer 6.2 SDK, there is a better alignment between the PowerShell snap-in and the PowerShell standards of Cmdlet design and usage. Here are some great reference documents:

Read More

Complex script for creating inbox rules

$
0
0

I am looking to create an inbox rule for all users in my environment. 

 

I am looking at users created in the last x days, and also verifying if the rule already exists. 

 

This is what I have so far, but there is no logic that checks if the rule exists. 


Appreciate the help!

 

Get-User -resultsize unlimited | where {$_.WhenCreated -gt (get-date).adddays(-7)} | foreach {new-inboxrule -Name Marketing -Mailbox $mbx.alias -SubjectContainsWords "[MARKETING]" -movetofolder ":\Junk E-Mail" -ExceptIfSubjectContainsWords ("RE: [MARKETING]","FWD: [MARKETING]") -StopProcessingRules $true -confirm:$false -Force}

HOTFIX: PowerShell exits unexpectedly when you run the New-CMSiteSystemServer cmdlet in ConfigMgr 2012 R2

$
0
0

When you run the New-CMSiteSystemServer cmdlet that's included with Microsoft System Center 2012 R2 Configuration Manager, PowerShell may exit unexpectedly. If you experience this issue we have a new hotfix available to address it.

Read More 

New features introduced in Windows Management Framework 5.0 Preview September 2014

$
0
0

Windows Management Framework 5.0 Preview September 2014 was released on September 4.

An overview of new features added since the May 2014 Preview is listed in the announcement on the Windows PowerShell Team blog, while additional details are available in the release notes.

There are also some new features not mentioned in the release notes, which we will look at in this article.

Viewing all 6937 articles
Browse latest View live