Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Include credentials in cmdlet

$
0
0

I have a simple script that creates Organizational Unit in Active Directory

Here is how I execute the script:

.\CreateOU.ps1 -OUName testOU -OU 'OU=test,DC=abc' -Login 'Domain01\User01'

The command in my script:

New-ADOrganizationalUnit -Name $OUName –path $OU -Credential $Login

This will prompt for password. How do I include my password as a parameter so I don't need to put in the password manually?


Endless loop stops executing

$
0
0

I have trouble with a PS script running on Windows Server 2012.

Essentially, it is an endless loop looking like this

do {

  Some-Stuff

  Start-Sleep -Seconds 60

} while ($true)

This loop runs in a Powershell window (not the ISE) perfectly well for some period of time (sometimes a few hours, sometime a few days) but then, having reached the end of Some-Stuff it simply stops executing. It never stops in the middle of Some-Stuff. Powershell isn't locked up - I can press Ctrl-C to terminate the script, which gets back to a command prompt. I can then restart the script and it will run normally, until it just stops again.

I would really appreciate any help with suggestions to help debug this problem.

Many thanks,

Colin

Capture console output to a file

$
0
0

Any idea why the following code doesnt write to a file when I run the script from the powershell command window? Strangely it only works when I run from the powershell command in Powershell ISE

I try not to use Start-transcript as it only captures errors, not everything on the screen.

$path     = Split-Path -parent $MyInvocation.MyCommand.Definition
$newpath  = $path + "\log.txt"


Add-Type -AssemblyName System.Windows.Forms
cls

write-host "hello"
raseoijresilrjh

[Windows.Forms.Sendkeys]::Sendwait('$psise.CurrentPowerShellTab.ConsolePane.text')

$text = $psise.CurrentPowerShellTab.ConsolePane.text
set-content -path $newpath $text
$text

Screen message logging

$
0
0

Hi

I need help with this! I'd like to log everything includes error messages and write-host messages display on the screen to a text file. What's the best way to achieve this?

Start-transcript doesnt log write-host messages.

$psise.CurrentPowerShellTab.ConsolePane.text or some reasons doesn't work for my script.

My script:

param (
   [Parameter(Mandatory=$true)]
   [string]$ID,
   [string]$OU
)

Try {
  Import-Module ActiveDirectory -ErrorAction Stop
}
Catch {
  Write-Host "[ERROR]`t ActiveDirectory Module couldn't be loaded. Script will stop!" -ForegroundColor Red
  Exit 1

}


Function Create-dev-group {
      $devacc = $ID +"-ACCESS"
      $devaccpath = "OU=$ID,"+"$($OU)"
      Try {
        New-ADGroup -Name $devacc –path $devaccpath -GroupCategory Security -GroupScope DomainLocal
        Write-Host "[INFO]`t Created new group : $devacc" -ForegroundColor Green
        }
      Catch {
        Write-Host "[ERROR]`t Unable to create group : $devacc" -ForegroundColor Red

        Exit 1
      }
}

 If (($ID -eq "") -Or ($OU -eq "")) {
        Write-Host "[ERROR]`t Missing parameters."  -ForegroundColor Red
        Exit 1
    } Else {     
      Create-dev-group

        }
    }

   

Passing Password in Powershell script

$
0
0

I have to pass password in the powershell script.

currently i am using CreditSSP and password storing in secure sting in the disk .

Is there any way to read password from schedule task configuration or SSO or windows authentication

Printer Driver Isolation Mode

$
0
0

hallo

I am looking for a script that makes the printer drivers on the server to Driver Isolation Mode 

please help

thenks 


אם תגובתי פתרה את בעייתך - לחץ/י, על "סמן כתשובה" ליד סימן ה V הירוק.

Need help in tokenizing Web.config files with DSC in RM 2013.4

$
0
0

Hi All,

<Couldnt find and DSC Forum so , Posting in PowerShell. Experts out their, need your help >

Our deployment goes like this, From TFS drops location we Invoke RM client with the activity -> Using PS/DSC, where I invoke a PS script to upload binaries to BLOB and copies binaries from Blob to destination folder of Azure VM . 

The major challenge was with respect to Web.config transformations, since these are VNext deployments we are using DSC script to transform Web.config files. 

http://www.donovanbrown.com/post/2014/09/05/Tokenization-for-DSC

https://gallery.technet.microsoft.com/xReleaseManagement-db1baef1

Below is the DSC : 

Question 1 ) I have 5 Web.config files from 5 folders of TFS build drop loc,how do I transformation the changes with DSC before copying to the destination folder of Azure VM. 

My Web.config files would reside like Folder1\Web.config 

      Folder2\Web.config .. etc 

How can I transform the same ? 

My DSC looks like below : 

$ConfigData = @{
   AllNodes = @(
      @{
         NodeName = "localhost";
         SourcePath = "$($PSScriptRoot)\tokenfile_drop\";
         DestinationPath = "$($PSScriptRoot)\tokenfile_target\";
         Tokens = @{Database="db02"};
         SearchPattern = "*.config"
      }
   )
}

Configuration TokenizeFiles
{
   # You have to import the xReleaseManagement resource before
   # you can use it in your configuration
   Import-DscResource -ModuleName xReleaseManagement
    
   # Node is read from ConfigData defined above
   Node $AllNodes.NodeName
   {
      # Use the built in File resource to copy files
      File CopyBits
      {
         Ensure = "Present"
         Force = $true
         Recurse = $true
         Type = "Directory"
         SourcePath = $Node.SourcePath
         DestinationPath = $Node.DestinationPath
      }

      # Use the xTokenize resource to transform your web.config files
      xTokenize WebConfigs
      {
         dependsOn = "[File]CopyBits"
         recurse = $true
         useTokenFiles = $true
         tokens = $Node.Tokens           
         path = $Node.DestinationPath
         searchPattern = $Node.SearchPattern
      }
   }
}

TokenizeFiles -ConfigurationData $ConfigData

Start-DscConfiguration -Wait -Verbose -Path .\TokenizeFiles -Force

------------------------------------------------------------------------------------------------------------------------------------------------------

Could you please help me here ?

Thanks,


Abraham Dhanyaraj

How to run a script in PowerShell ISE from a bat file

$
0
0

Hi,

Currently I have a bat file with content: "Powershell.exe -executionpolicy unrestricted -File data\aduserfind.ps1 -sta"

When I double-click the bat file, the PowerShell script is ran and GUI opens.

However I have noticed that some things do not work correctly when the bat is used. When I run the same script from PowerShell ISE, the functions work.

One example is a confirmation dialog where an AD user is disabled:

$disableToolStripMenuItem_Click={
$title = "Disable user"
$message = "You are about to disable the user '$($textBox1.Text)'. Are you sure you want to continue?"
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `"Disables the user '$($textBox1.Text)' and then moves the user to 'xxxxxxxxxxxxx.com\xxxxxxxxx\xx\Disabled Users\'"
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `"Cancels the action."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice($title, $message, $options, 1)
switch ($result)
    {
        0 {
        Get-ADUser $textBox1.Text | Move-ADObject -TargetPath "OU=Disabled Users,OU=xx,OU=xxxxxxxxx,DC=xxxxxxxxxxxxx,DC=com" -PassThru | Disable-ADAccount
        $richTextBox1.Text = "The user '$($textBox1.Text)' has been successfully disabled and moved to 'xxxxxxxxxxxxx.com\xxxxxxxxx\xx\Disabled Users\'."; break}
        1 {"Action canceled."; break}
    }
}

This works without issues in PowerShell ISE (though, the confirmation window will not be on top, but it will pop up to the background), however when I run the script from bat file, the confirmation is instead displayed in the cmd window (and the GUI freezes, not responding during this).

A possible workaround I might need to get is: bat file opens PowerShell ISE and then runs the script.

I tried "Powershell_ISE.exe -File data\aduserfind.ps1 -sta", however it does not run the script. It only opens the script, but does not run it. What do I need to add to make the script also run?

Or is there another solution to this, where I can continue using my current bat file that opens Powershell (instead of ISE)?

Another example is the below (icon on the top left of the window - works in ISE, does not work in regular Powershell):

$form1.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon('data\icon.ico')

Thank you in advance.




Include password in cmdlet

$
0
0

New-ADGroup -Name $de –path $depath -GroupCategory Security -GroupScope DomainLocal

How do I include my login name and password in my script to execute the creation of AD group (above cmdlet)? I do not want my script to prompt me to put in my password.

Script to detect GPO linked but not enabled

$
0
0

Hi folks,

I need help to find which one is linked but not enabled.

Actually im trying like this :

[xml]$GPOReport = (get-gporeport -name MY_GPO -ReportType xml)

Then if I type : 

$GPOReport.GPO


I get : 

xsi                 : http://www.w3.org/2001/XMLSchema-instance
xsd                 : http://www.w3.org/2001/XMLSchema
xmlns               : http://www.microsoft.com/GroupPolicy/Settings
Identifier          : Identifier
Name                : GPO_LS_TEST_SCRIPT
IncludeComments     : true
CreatedTime         : 2012-10-24T09:09:18
ModifiedTime        : 2012-10-24T09:09:18
ReadTime            : 2012-10-24T15:09:00.4308084Z
SecurityDescriptor  : SecurityDescriptor
FilterDataAvailable : true
Computer            : Computer
User                : User
LinksTo             : {LinksTo, LinksTo}

Good, now if I type : 

$GPOReport.GPO.LinksTo

I get : 

SOMName
-------
Lausanne
Lausanne Tests


Now if i tape : 

$test.GPO.LinksTo | fl


I get : 

SOMName    : Lausanne
SOMPath    : mydom.com/Lausanne
Enabled    : true
NoOverride : false

SOMName    : Lausanne Tests
SOMPath    : mydom.com/Lausanne Tests
Enabled    : false
NoOverride : false

My question : How can i handle the value "Enabled" without fl ?

Example : 

$GPOReport.GPO.LinksTo.Lausanne.Enabled

And it's return true or false.

Thanks

Regards,

Jon



MCITP Enterprise Administrator / Server Administrator




How to run a PS script on a remote machine

$
0
0

Hi,

I have a script located on a remote machine at c:\Temp\Script1.ps1  I want to run this script remotely from a driver system.  Via Powershell remoting on the driver machine, I run the following:

$cred = Get-Credential Domain1\User1

$Sessid = New-Pssession DC1

Invoke-Command -session $sessid -cred $cred -ScriptBlock {c:\temp\Script1.ps1}

I get an error 'Invoke-Command : Parameter set cannot be resolved using the specified named parameters.

I see the Session ID created and opened fine and the script runs fine on its own on the remote machine.

Any suggestions as to how to resolve the error


Thanks for your help! SdeDot

Flat nested AD groups

$
0
0


Hi,

I try to create a PS script that makes nested AD groups flat. It should add all users from every nested groups in the group at first level (we want to flat).

For example:

Actual situation
Group1
	User A
	User B
	Group2
		User C
		Group3
			User D

What we need
Group1
	User A
	User B
	Group2
		User C
		Group3
			User D
	User C
	User D

Output in Logfile
Member			from group			in group
User C			Group2				Group1
User D			Group3				Group1

First I tried it with the Get-ADGroupMember cmdlet and the -recursive switch.

$Groups2Flat = Get-ADGroup -Filter {Name -like "zz8MAN*" -and Name -notlike "*_li"}
foreach ($Group2Flat in $Groups2Flat)
    {
        $Members = Get-ADGroupMember -Identity $Group2Flat -Recursive
        Add-ADGroupMember -Identity $Group2Flat -Members $Members
        Clear-Variable -Name Members
    }

This version works fine. So I wanted to add an output in a logfile. I need the following informations: which member, from which group, is added in which group. But there’s the problem. If I use the Get-ADGroupMember with the –recursive switch I can’t get these informations. I can’t see from which nested group the member comes.

So I decide to create an own recursive function. That’s what I’ve got so far:

function Flat-ADGroups {
    param (
        $Group
    )
    $Members = Get-ADGroupMember -Identity $Group
    foreach ($Member in $Members) {
        if ($Member.objectClass -eq "group") {
            Flat-ADGroups -Group $Member.Name
        }
        else {
            Add-ADGroupMember -Identity $Group -Members $Member
        }
        Clear-Variable Member
    }
}

Flat-ADGroups -Group Test_1

This code works well, too. But there is still a little problem where I don’t know what to do. The nested users weren’t add in the group at first level (of course, the function calls itself with a new groupname). They are added to the nested group. I tried a few things (second variable and so on) but nothing worked.

What is to do that the script adds all nested members to the first group? I hope I could explain the problem sufficiently.

Btw: As you can see there is no logging part at the moment and it would be useful if I include a part which deletes the nested groups after they are flatted. This things I will add later to the script. Now I only want to know what is to do to resolve my actual problem. I’m not looking for someone who writes the whole script for me ;-)

Thanks for the answers and ideas J

mkdir -? - - - > how is the [ -path ] option used ?

$
0
0

Would anyone be able to give an example of how the  [  -path  ]   option is used   ?    I found it when looking up more information under the ' making a directory '   command    mkdir -?

Hope this is not too vague of a  question.

Thank you in advance  !

alvino6

Advanced Function Parameters

$
0
0

I've created an advanced function using cmdlet binding and parameters, but I seem to be missing the setting which prevents the user from entering a parameter more than once. It's quite a lengthy function but here is my param block:

    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]$Server,

        [Parameter(Mandatory=$true)]
        [string]$Username,

        [Parameter(Mandatory=$true)]
        [string]$Password,

        [Parameter(Mandatory=$true)]
        [string]$File
        )

So I need the user to provide only one instance of each parameter. Currently it's possible to enter a parameter more than once, for example:

Do-This -Username -Password -Password -Server -File

Is this normal or is possible to prevent the user from entering more than one of a parameter. I was looking at the documentation here but I'm only really seeing how to limit the number of values after a parameter (eg. servers entered in the server parameter).

Any help would be appreciated

Thanks in advance
Adam

Create AD group using powershell

$
0
0

foreach ($item in $list) {
 If ($item.GroupName -eq "") {
        Write-Host "[ERROR]`t Please provide valid group details in spreadsheet."  -ForegroundColor Red
      } Else {
      $item.ID = $ou
    New-ADGroup -Name $item.GroupName –path “OU=$ou,DC=account,DC=company,DC=com”  -GroupCategory Security -GroupScope DomainLocal

}

I am getting a syntax error because of OU=$ou. Any idea how to fix this?


DaysOfMonth - Complex Requirement

$
0
0

Hi Guys,


I have a complex requirement, I have to determine that whether today is the 2nd Saturday or 3rd Saturday of the month using PowerShell, and if it is the 2nd or 3rd Saturday of the month, then execute the task.

Is there anyone could help me out on this?


Regards, Saugata D

List size of specific sub-folders for several root folders

$
0
0

I need to be able to get an overview of the foldersize of a specific sub-folder for a numerous of root folders.

The root folders are all listed in a csv file and for each of these listed folders I want to know the foldersize and amount of files for a specific sub-sub folder.

For example, each root folder (these are listed in a CSV file) has a subfolder called ‘SubSubFolderX’, I would like to get an overview of the total size of SubSubFolderX (and sub-folders) and the amount of files in it.

Example:

RootFolder1

           SubFolder1

                       SubSubFolderX

           SubFolder2

           SubFolder3

RootFolder2

           SubFolder1

                       SubSubFolderX

           SubFolder2

           SubFolder3

RootFolder3

           SubFolder1

                       SubSubFolderX

           SubFolder2

           SubFolder3

RootFolder4

           SubFolder1

                       SubSubFolderX

           SubFolder2

           SubFolder3

Remote software installation

$
0
0

Hi All,

I am trying to mass install an agent in my environment:

The installer support command line installation:

AGENT-WinCollect-<version>-setup.exe /s /v"/qn INSTALLDIR="C:\IBM\WinCollect" AUTHTOKEN=eb59386c-e098-49b8-ba40-6fb46bfe7d1 FULLCONSOLEADDRESS=100.10.10.1:8413 HOSTNAME=my_host

I created a power shell script out however the agent never get installed.

Not sure why, need advice here.

########################################################################
# Remote Install
#
# Created By: Chan Guo Qiang
########################################################################

$computers = Get-Content "C:\Users\Tester\Desktop\computer.txt"

foreach ($computer in $computers) {

#Copy file to tmp
Copy-item "\\192.168.0.123\FileServer" -container -recurse \\$computer\c$\windows\temp\

#The Install string can have commands aswell
  $InstallString = 'C:\windows\temp\FileServer\AGENT_x64_WinCollect-7.2.2.1018564-setup.exe /s /v"/qn INSTALLDIR="C:\IBM\WinCollect" AUTHTOKEN=eb59386c-e098-49b8-ba40-6fb46bfe7d1 FULLCONSOLEADDRESS=100.10.10.1:8413 HOSTNAME=my_host'
 
    ([WMICLASS]"\\$computer\ROOT\CIMV2:Win32_Process").Create($InstallString)
#Output the install result to your Local C Drive
    Out-File -FilePath C:\Users\Tester\Desktop\installed.txt -Append -InputObject "$computer"}



Running PowerShell Code in VBS

$
0
0

Im trying to use the following PowerShell code in my VBS script however im not to sure how to and if possible I would like to use a variable from the vbs code at the start of the mail box? Does anyone know how to do this please?

    Set-ExecutionPolicy RemoteSigned
   
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUrihttp://address.domain.co.uk/PowerShell/ -Authentication Kerberos
    Import-PSSession $Session
    sleep 1
    Enable-Mailbox varraiblehere@domain.co.uk -Database "Students"

How to capture CPU and RAM utilization thru script/tool

$
0
0

Hi All,

I need an script which will capture the utilization of servers CPU and RAM along with remote servers.

Do we have any script/tool which can fulfill my requirement.

Thanks

Viewing all 21975 articles
Browse latest View live


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