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

Create certificate chain with PowerShell

$
0
0

Hi All,

I want to create a certificate chain with PowerShell, where is "root" certificate self-signed certificate, and "webCert" is signed with "root". I know that for self-signed certs I can use cmdlet New-SelfSignedCertificate.

Is there any way in PowerShell to create "webCert" that is issued by my "root" certificate?

Regards,


ADUser PasswordNeverExpires -eq 'false'

$
0
0

I am trying to get a list of user accounts that have PasswordNeverExpires -eq 'false' or true.

I can run a this:

get-aduser -filter * -properties passwordneverexpires | Select-Object PasswordNeverExpires

and i get a list of all true and false.

why when i am running this line:

get-aduser -filter * | where {$_.PasswordNeverExpires -eq 'false'}

i get nothing?

Thank you.

Create Remote Share

$
0
0

I've read many of the forum post regarding this topic and none of the seem to work for me. I've tried:

I have tried to verify that the share is created by properties of the folder and by looking at the registry.

Any ideas would be appreciated?  

Powershell getElementById() not working with IE11‏

$
0
0

Dear Microsoft,

I was reading the MSDN article article Web UI Automation with Windows PowerShell. When I am testing the script of DOM manipulation I found that the getElementbyID() method could not work under IE11.

With some search, there is another StackOverflow article getElementById does not seem to work in IE10 seems to suggest the same.

Is this due to some news security restrictions imposed by the new IE? Based on the original contents of the article, can any modification be made to make the Powershell snippets work with IE11?

Bob

  

Scheduled task powershell script cant write file

$
0
0

Hello experts

I have scheduled task with powershell but cant write CSV file. Below my PS script:

$ExemptGroup = Get-ADGroup app_users
Get-ADUser -Filter { -not (memberOf -RecursiveMatch $ExemptGroup.DistinguishedName) } -Properties * |
 Select-Object -Property DisplayName,SamAccountName,WhenCreated,@{Name='Last Logon';Expression={[System.DateTime]::FromFileTime($_.LastLogon).ToString('g')}},LogonCount,@{N='Status';E={ If ( $_.useraccountControl -match '^(?:514|546|66050|66082)$' ) { 'Disabled' } Else { 'Enabled' } }} |
 Sort-Object -Property DisplayName | Export-Csv C:\Users\22041912\Documents\User_statis_list.csv

In Powershell my script working normally and writing CSV file but in scheduled task cant write CSV file. Task history told me succesfully finished.

Anyone suggest? What wrong?


windows 2012 powershell 4 and shadow copy disable

$
0
0

Hello:

        With diskPart you can disable shadow copy of any disk, for example:

diskpart att vol clear shadowcopy

       So I need disable shadow copy over Disk 1 on a server windows 2012. The server have 2 disk:

Number Friendly Name                            OperationalStatus
------ -------------                            -----------------
1      VMware Virtual disk SCSI Disk Device     Online
0      VMware Virtual disk SCSI Disk Device     Online

But I need shadow copy on Disk 0, then only need disabled shadow copy on Disk 1.

Any way to do this with powershell and without Diskpart??. Thanks and sorry for my bad english.

Loading the SCCM 2012 R2 Cmdlets from within a module

$
0
0

Hi together,

In the following article was described how to load the Powershell Module for SCCM 2012:

http://blogs.technet.com/b/configmgrteam/archive/2013/03/27/powershell-connecting-to-configuration-manager.aspx

I've taken the code to build a function to load the Powershell Module which works fine when i directly integrate it in my scripts.

Currently i build a Module called SCCM-HelperFunctions.psm1 and the above mentioned function is one which i want to integrate, i named it "Import-Cmdlets". The Import of my Module works fine,  the function "Import-Cmdlets" is available trough IntelliSense and the command ends with no errors in the context of the given Site (ex. "PS CM1:\") but when i try to use SCCM Cmdlets the Command is not found.

I've checked if the Module was loaded successfully but it isn't. Following is the function included in the Module:

Function Import-SCCMCmdlets {<#
.SYNOPSIS
Lädt die SCCM Cmdlets und wechselt in den Kontext der angegebenen Site.

.DESCRIPTION
Die Funktion Import-SCCMCmdlets lädt die Powershell Cmdlets und wechselt in den PSDrive Kontext des angegebenen Sitecodes.
In diesem Kontext können dann die in folgeendem Artikel aufgeführten Cmdlets ausgeführt werden:
http://technet.microsoft.com/en-us/library/jj821831%28v=sc.20%29.aspx

.PARAMETER Sitecode
Eine Zeichenkette mit dem Sitecode der CAS oder Primary Site in dessen Kontext die Cmdlets laufen sollen.

.EXAMPLE
Import-SCCMCmdlets -SiteCode "P01"

.EXAMPLE
$SiteCode = "P01"
Import-SCCMCmdlets -SiteCode $SiteCode
#>
    Param (
		[Parameter(Mandatory=$true)]
		$SiteCode
	)

$null = Import-Module ($env:SMS_ADMIN_UI_PATH.Substring(0,$env:SMS_ADMIN_UI_PATH.Length – 5) + '\ConfigurationManager.psd1') 
Set-Location "$($SiteCode):" | Out-Null
if (-not (Get-PSDrive -Name $SiteCode))
    {
        Throw "Beim Versuch das Powershell Modul zu laden und auf das PSDrive $Sitecode zu wechseln trat ein Fehler auf."
}
}

The exact same function works when i copy it to the ISE and run it.
Does anyone have any ideas and can point me into the right direction? (eventually different workspaces when the function runs from within the module or something like that?)

Best regards

Rolf

Executing local variable to a remote Active Directory server

$
0
0
Hi,

From my remote PC I tried using below command to create users in AD. But in the "-path" section I am getting an error. Please help me to resolve this.

-----------------------------------------------
$theOU = "HR"
#status = success :|

$myOU = Invoke-Command -ComputerName dc01 -ScriptBlock {"(Get-ADOrganizationalUnit -LDAPfilter '(Name=$theOU)' -SearchBase 'OU=Users,OU=LabOU,DC=cyquent,DC=ae').DistinguishedName" }
#status = success :|


Invoke-Command -ComputerName dc01 -ScriptBlock {New-ADUser -DisplayName peter -Path $myOU -GivenName peter -City Houston -Country US -Description Accountant -Surname jason -Name peter -SamAccountName peter -UserPrincipalName peter -AccountPassword (ConvertTo-SecureString password@123 -AsPlainText -Force) -ChangePasswordAtLogon:$true -Enabled:$true}

#status = Error :oops:
Error: Cannot validate argument on parameter 'Path'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
----------------------------------------------------------


Note:- If I type -path as -PATH 'OU=HR,OU=Users,OU=LabOU,DC=cyquent,DC=ae' I am able to create the user successfully.

But I need to use it through a variable as I was trying.

Note: - "HR" is the Organization Unit name where I am trying to create the user.:|

plz help me.

Thanks,
Shamir

restricting powershell version in script

$
0
0

Stupid question probably, but just want to make sure.

Does Set-StrictMode -Version 2.0 actually prevent the script from processing functionality that exists in Powershell 3 or 4 or does it just implement "strictMode" rules that existed in version 2?

Thanks.

2003 terminal server. Clients log in , see their desktop and then it changes to a fake windows desktop.

$
0
0

I figured this was a virus or malware, and have scanned the server but have not found the virus/malware.

Because of the delay of the fake screen popping up, I figured it was in the startup folder, but it is not.

Malware Bytes only detected a possible threat in  a download forlder, but that was eliminated.

Any clues where to look?

Using Send-MailMessage to change fonts with -BodyAsHTML

$
0
0

Anyone know how to change the font type and size in a body of text so the -BodyAsHTML parameter of send-mailmessage will recognize the font change? Here is what I have, but I haven't figured out how to change the font:

### Email Body ###
    $EmailBody = "<style>Body{font-family:Arial}</style>"

    $EmailBody += "<b>This is bold</b>"

### Email Subject ###
    $EmailSubject = "Subject"

Send-MailMessage -From Sender -To Receiver -Subject $EmailSubject -Body $EmailBody -SmtpServer Smtpserver -BodyAsHtml

I would like to see if I can do it all inside the text body, and not have to use the "ConvertTo-HTML" cmdlet.

Expanding %1 and other variables from a command

$
0
0

Hi!

I need a simple command to open a specific file (rasphone.pbk) with whatever is the default program for opening text files.

What I have so far:

(Get-ItemProperty -Path 'Registry::HKEY_CLASSES_ROOT\txtfile\shell\open\command').'(Default)'

Which gives me this output:

"C:\Program Files\Sublime Text 2\sublime_text.exe" "%1"

It will be executed for different machines/users. Some may only have the default notepad.exe, others may have different editors.

So I now need to replace the %1 with

%AppData%\Microsoft\Network\Connections\Pbk\rasphone.pbk

while also expanding %AppData%. The default command is

%SystemRoot%\system32\NOTEPAD.EXE %1

where I would need to expand %SystemRoot% as well.

It should be a 1-liner if possible because the command is stored in a database. If I need a script file I have to find a way to distribute that file to each client as well... and for simply opening a file that would be a bit too much.

If it's easy in CMD that would be even better, but I thought Powershell is a capable tool for doing stuff like that in a simple way. I just can't wrap my head around it...

thanks for any help! :)

Using start-process to from one script to start another

$
0
0

Hi!

I've been playing around with Start-Process and it seems to have different behaviour depending on if I run it "interactively" from a console or in a script. I use powershell v3.

So if I have a powershell window running and start a script, let's say script_no1.ps1 that contains this,

Start-Process -FilePath "c:\windows\notepad" -wait

Start-Process -FilePath "c:\windows\system32\calc.exe" -wait

...it will first start notepad and then wait until I close notepad and then start calculator. So far so good...

However if I put those 2 above lines into a script, let's call it test.ps1 and want to run that script with start-process and -wait I get a different behaviour...

Start-Process "powershell.exe" -ArgumentList "-File c:\windows\temp\test.ps1" -Wait

The 2 Start-Process in test.ps1 are started without any wait, so powershell doesn't wait until I close notepad to start calculator, it just spawns both.

Main script:

Start-Process "powershell.exe" -ArgumentList "-File c:\windows\temp\test.ps1" -Wait

"Child" script:

Start-Process -FilePath "c:\windows\notepad" -wait

Start-Process -FilePath "c:\windows\system32\calc.exe" -wait

Why is the behaviour different? I've found a workaround using Wait-Process but I'm trying to understand whats going on under the hood here. I've tried adding -PassThru also but no difference...




Powershell Command to check specific user is a part of certain group or not

$
0
0

Hi,

I need a powershell script that will check whether specific user is a part of certain group or not and if the user is part of any of those groups, script should remove it.

E.x. 

$User = "Test"

$Groups = "Group1","Group=2","Group3","Group4","Group5"

If test user is part of any of the groups from the $Groups,  it should be removed when I run the script.

Please let me know the best way to do this.

Thanks in advance


Can't get DynamicParam to work when set values include commas

$
0
0

Hi all!  Having a weird problem and have spent a lot of time troubleshooting with no luck, so I'm hoping someone can assist.  Here's the deal:

Trying to include a dynamic parameter in my function to allow my users to select from a validated list of OU distinguished names given a previously-input $Domain parameter. 

The problem is that distinguished names have commas in them, and that's causing errors after I tab-complete the OU DN and hit . (The actual dynamic variable list works fine… lists the OUs correctly etc.)

If I tab-complete the OU DN, then go back and manually add single or double quotes around that value, it works as intended.

If I add

| foreach {"'$_'"}


to the end of the line defining the $arrSet variable, the validated list shows up with single quotes around each DN, but when I hit Enter it fails, telling me that the value (with single quotes) does not belong to the set (shows me a set with the exact value with quotes).   So that seems weird, because it's saying 'A' isn't part of set "'A','B','C'"

So I'm out of ideas.  Anybody have anything else?

Code below is a functional snippet of the much larger script, and throws the same errors I'm seeing.  To make it work in your domain, you'll need to modify

[ValidateSet('mydomain.local')]


and

-SearchBase 'DC=mydomain,DC=local'

Thanks!

function Thing {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false,Position=1,ValuefromPipeline=$true,ValueFromPipelineByPropertyName=$true,HelpMessage='Please enter a valid domain name.')]
        [ValidateSet('mydomain.local')]
        [string]
        $Domain
    )

    DynamicParam {
            # Set the dynamic parameters' name
            $ParameterName = 'OrganizationalUnit'

            # Create the dictionary
            $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary

            # Create the collection of attributes
            $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]

            # Create and set the parameters' attributes
            $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
            $ParameterAttribute.Mandatory = $true
            $ParameterAttribute.Position = 2

            # Add the attributes to the attributes collection
            $AttributeCollection.Add($ParameterAttribute)

            # Generate and set the ValidateSet



            $arrSet = (Get-ADOrganizationalUnit -Filter * -SearchBase 'DC=mydomain,DC=local' -SearchScope OneLevel -Server $Domain).DistinguishedName
            $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)

            # Add the ValidateSet to the attributes collection
            $AttributeCollection.Add($ValidateSetAttribute)

            # Create and return the dynamic parameter
            $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
            $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
            return $RuntimeParameterDictionary
    }

    begin {
        # Bind the parameter to a friendly variable
        $OrganizationalUnit = $PsBoundParameters[$ParameterName]
    }

    process {
        # Your code goes here
        Write-Output "Domain: $Domain"
        Write-Output ""
        Write-Output "Selected OU: $OrganizationalUnit"
        Write-Output ""
        Write-Output "OU List: $arrset"
    }

}


check file exists in folder

$
0
0

I would to check file in folder and send name file to my email.  How to use power-shell script

we have files in folder but this file change name everyday. i need to check file and sent to my email every day

Please advise and idea .

invoke-sqlcmd with domain user name and password

$
0
0

I am trying to execute below small SQL script from powershell by passing my domain user name and password..but it is throwing an error login failed for the user.

Howerver I am able to execute the same query by passing normal user 'non domain' and password. The issue is only when i am trying to connect with domain username.

Can you please suggest if there is any way to execute below query with domain user..

Invoke-Sqlcmd-query"select name from master.sys.databases"-ServerInstance"CM-NCKM-DBTST04\SQL2012" -username "sos\9venk" -password "xxxx"

Thanks

Venkat


venkat

check disk space

$
0
0

Hi,

     I have to check disk space on remote servers..and alert us (send email) if free space goes below threshold value..Any ideas Please how to implement this using power shell...any help would be appreciated.

Thanks

C Drive is not showing when running powershell command remotely

$
0
0

I have prepared a script which will be invoked on remote server and check for the used space threshold. If I run the same script locally, It is giving me the proper output which has C: but from remote It is not showing C:\ and showing the other drives. Here is my script.

$th = 50
foreach($v in Get-wmiobject win32_logicaldisk -filter 'drivetype = 3')
 {
    Try
    {
    $res=""
            if((( $v.Size - $v.FreeSpace ) / $v.Size )*100 -gt $th)
            {
                $res = $res+$v.DeviceID+" "+ "{0:N2}" -f ((( $v.Size - $v.FreeSpace ) / $v.Size )*100)
                $res
            }
    }
    catch [Exception]
    {
        write-host ''
    }
 }

Arockia

Unattended.xml : remove a child item containing a value

$
0
0

Hi all,

I have in a section :

        <component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <DiskConfiguration>
                <Disk wcm:action="add">
                    <CreatePartitions>
                       <CreatePartition wcm:action="add">
                               <Order>1</Order>
                               <Type>Primary</Type>
                               <Size>350</Size>
                               <Extend>false</Extend>
                          </CreatePartition>
                          <CreatePartition wcm:action="add">
                               <Order>2</Order>
                               <Type>EFI</Type>
                               <Size>100</Size>
                               <Extend>false</Extend>
                          </CreatePartition>
                          <CreatePartition wcm:action="add">
                               <Order>3</Order>
                               <Type>MSR</Type>
                               <Size>128</Size>
                          </CreatePartition>
                          <CreatePartition wcm:action="add">
                               <Order>4</Order>
                               <Type>Primary</Type>
                               <Size>64000</Size>
                               <Extend>true</Extend>
                           </CreatePartition>
                     </CreatePartitions>

I load the contents of the Xml in the $Xml Variable

To remove a <CreatePartition></CreatePartition> block, I do the following :

# Delete Partition 3 & 4 of the Template
$tmp = $Xml.unattend.settings[1].component[1].DiskConfiguration.disk[0].CreatePartitions.CreatePartition[3] # MSR UEFI
[void] $Xml.unattend.settings[1].component[1].DiskConfiguration.disk[0].CreatePartitions.RemoveChild($tmp)
$tmp = $Xml.unattend.settings[1].component[1].DiskConfiguration.disk[0].CreatePartitions.CreatePartition[2] # Windows UEFI
[void] $Xml.unattend.settings[1].component[1].DiskConfiguration.disk[0].CreatePartitions.RemoveChild($tmp)

And if works great

Now, I would like to remove in the second CreationPartition section the line

                               <Size>100</Size> 

I tried :

$tmp = $Xml.unattend.settings[1].component[1].DiskConfiguration.disk[0].CreatePartitions.CreatePartition[1].Size

But it returns the string 100 instead of an object on <Size>100</Size>

I also tried

$tmp = $Xml.unattend.settings[1].component[1].DiskConfiguration.disk[0].CreatePartitions.CreatePartition[1]

$tmp.RemoveAttribute("Size")

But it does not remove "Size"

$tmp

action : add
Order  : 2
Type   : EFI
Size   : 100
Extend : false

Could you help me to find the correct syntax.

Thanks


ML


Viewing all 21975 articles
Browse latest View live


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