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

map drive in workgroup error

$
0
0

enviroment:  pc1(xp,pc1,192.168.10.1)  pc2(xp,pc2,192.168.10.130)

                     pc1,share 1  "c:\ps\ps2test" no need username/password,

                     pc1,share 2  "c:\ps\ps3"  need username/password,

in pc2 can use psh create map drive:

    $drivek=New-Object -ComObject wscript.network
    $drivek.MapNetworkDrive("L:", "\\192.168.10.1\ps3",$true,"username","password") 
    $drivek.MapNetworkDrive("K:", "\\192.168.10.1\ps2test",$true) 

it work ok!

but

  in pc1,I can't use invoke-command -session $rs -file .\mapdrive.ps1

  $rs can work ,mapdrive.ps1 like pc2's map code

error:  MapNetworkDrive refuse

 

 

 

 

 


adding new values to a psobject?

$
0
0

Hi,

maybe I'm too stupid but I looked through the web for two days now and I can't find a solution.

I created a PSobject and added some properties and values. it looks like this:

  $script:resultall = new-Object PSobject
  Add-Member -InputObject $resultall -memberType NoteProperty -Name DisplayName -Value "Test1"
  Add-Member -InputObject $resultall -memberType NoteProperty -Name Status -Value "Status1"

Now I want to add a second line with similar values to my object but it doesn't work in any way.

Every hint is welcome...

 

Sven

Import-PSSession, bug or bug-like feature?

$
0
0

Good Morning,

I've come across a strange error with the import-pssession cmdlet, and wanted to run it by the experts. I'm using it in a larger account creation script the import the exchange cmdlets from an exchange server to create a mailbox. In testing it all in the shell the below commands work fine:

$session=New-PSSession-ConfigurationNameMicrosoft.Exchange-ConnectionUrihttp://$exchangeserver/powershell

Import-PSSession-session$session-AllowClobber-DisableNameChecking

However, when I run them in my larger script, I get the below error:

Import-PSSession : Cannot convert null to type "System.DateTime".

At C:\scripts\importbug.ps1:8 char:5

+ Import-PSSession -session $session -AllowClobber -DisableNameChecking

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : MetadataError: (:) [Import-PSSession], ArgumentTransformationMetadataException

+ FullyQualifiedErrorId : RuntimeException,Microsoft.PowerShell.Commands.ImportPSSessionCommand

Now I couldn't for the life of me figure out what Import-PSSession would be doing with any dateTime values, or even what null variable I was passing to it. After deconstructing my script I narrowed it down the following minimum code to illustrate the error:

 

FunctionGet-Exchangecmdlets {

    param(

        [string]$ExchangeServer,

 

        [datetime]$date

    )

    $session=New-PSSession-ConfigurationNameMicrosoft.Exchange-ConnectionUrihttp://$exchangeserver/powershell-AllowRedirection-AuthenticationKerberos

    Import-PSSession-session$session-AllowClobber-DisableNameChecking

}

 

Get-Exchangecmdlets-ExchangeServer'exchangeserver1'  #This throws the error

 

Get-Exchangecmdlets-ExchangeServer'exchangeserver1'-Date"10/10/2013"  #This does not

 

So it seems that when import-pssession runs, it validates all the variables in its parent function.  Since $Date wasn't specified, it was null, which can't be converted to DateTime, hence the error.  This error also appeared with parameters using the [validatescript] setting, such as:

 

FunctionGet-Exchangecmdlets {

    [cmdletbinding()]

    param(

        [string]$ExchangeServer,

 

        [ValidateScript({test-path (Split-Path-Path$_-Parent)})]

        [string]$ErrorLog

    )

    $session=New-PSSession-ConfigurationNameMicrosoft.Exchange-ConnectionUrihttp://$exchangeserver/powershell-AllowRedirection-AuthenticationKerberos

    Import-PSSession-session$session-AllowClobber-DisableNameChecking

}

 

Get-Exchangecmdlets-ExchangeServer'exchangeserver1'  #This throws the error

Import-PSSession : Cannot bind argument to parameter 'Path' because it is an empty string.

At C:\scripts\importbug.ps1:10 char:5

+ Import-PSSession -session $session -AllowClobber -DisableNameChecking

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidData: (:) [Import-PSSession], ParameterBindingValidationException

+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ImportPSSessionCommand

 

I didn’t test the other validation methods, but I suspect they’ll all throw the error.

 

Once identified this is easy enough to work around, I simply made a separate function for the import-pssession with no optional parameters and no validation.  However, since optional parameters should only be validated if a value is provided, this seems rather bug-like to me.  Nothing in the documentation for Import-PSSession jumped out at me as suggesting that variables are re-processed or anything like that.

 

Thoughts?

4 Essential PowerShell Provider Commands for SQL Server

$
0
0

Windows PowerShell commands can be a valuable addition to your SQL Server management tools. Although I don’t think PowerShell is going to replace SQL Server Management Studio (SSMS) anytime soon, it can be used for a wide range of scripted management tasks. PowerShell can run T-SQL commands and also work with objects outside of the SQL Server database. You can use the SQL Server PowerShell Provider to navigate and manage SQL Server database objects, and PowerShell scripts can be run by SQL Agent. In addition, you can import and execute SMO or ADO.NET assemblies by using PowerShell. In this column, I’ll cover four of the essential PowerShell Provider commands that can help you get started using PowerShell with SQL Server.

Read More

How PowerShell Differs From the Windows Command Prompt

$
0
0

You may have noticed a new command-line environment in Windows since Windows 7 — PowerShell. PowerShell is a much more powerful command-line shell and scripting language than the Command Prompt is, giving Windows system administrators a useful command-line environment.

Read More

SqlDev PowerShell 101: Getting Started with PowerShell

$
0
0

This is the first in a new series focused on PowerShell for SQL developers. That means using PowerShell to create and/or modify table schema, stored procedures, and indexes. In other words, automating code development and database tuning processes. This is mostly what I’ve been using PowerShell for so far, and I have to say, I am LOVING it! It’s allowing me to save *days* of coding and validating.

Read More 

Run the Access Control App to Configure Windows Remote Management with PowerShell

$
0
0

If you need to adjust the Access Control List for utilizing PowerShell commands on remote computers, you'll first need to know how to open the UI for managing and modifying the ACLs.

Read More

Learn More about PowerShell and Modular Inputs

$
0
0

Recently, we caught up with Joel Bennett, a Windows PowerShell MVP awardee, who also happens to be my teammate on Splunk’s BD Labs team. Joel is the lead developer for the Splunk Add-on for Microsoft PowerShell, a modular input for Splunk 5 which enables you to easily and efficiently add data to Splunk. Please visit powerscripting.net to listen to the full episode or subscribe to the podcast feed.

Read More


#PSTip List SQL database mirroring partner using SMO

$
0
0

In an earlier tip, we looked at how to verify if a SQL database is mirrored. Continuing this series on SQL SMO tips series, let us look at how we can list the SQL database mirroring partner information. I find this information quite helpful when managing the SQL Server mirroring. 

Read More

Write-Host with formated number called from cmd

$
0
0

Hi all,

I'm new in PowerShell and I try to display formated number from cmd.

Into PowerShell the following command works fine:

PS E:\> Write-Host ("{0:N0}" -f 123456789 )
123 456 789

but when I try the following from cmd, it doesn't work:

E:\>PowerShell -Command "&{Write-Host (("{0:N0}" -f 123456789 ))}"
0:N0

 

Thank you for your help.

Olivier.

 

 

Download files from Codeplex with start-bitstransfer

$
0
0

Hello, I'm quite new to Powershell. I want to download some files from the internet.

In some cases there is no problem:

Getting Windows6.1-KB974405-x64.msu from Microsoft:

Start-BitsTransfer 'http://download.microsoft.com/download/D/7/2/D72FD747-69B6-40B7-875B-C2B40A6B2BDD/Windows6.1-KB974405-x64.msu' "g:\"

which is

<a href="http://download.microsoft.com/download/D/7/2/D72FD747-69B6-40B7-875B-C2B40A6B2BDD/Windows6.1-KB974405-x64.msu">Hier klicken</a> on the download site.

but if I want to download something from Codeplex it won't work.

<a tabindex="9" id="fileDownload1" href="http://autospsourcebuilder.codeplex.com/downloads/get/486671" class="FileNameLink">AutoSPSourceBuilder.zip</a>

I tried

Start-BitsTransfer 'http://autospsourcebuilder.codeplex.com/downloads/get/486671/AutoSPSourceBuilder.zip' "g:\"

Result

Start-BitsTransfer : HTTP-Status 500: Der Server kann die Anforderung aufgrund eines unbekannten Fehlers nicht erfüllen.

Bei Zeile:1 Zeichen:19
+ Start-BitsTransfer <<<<  'http://autospsourcebuilder.codeplex.com/downloads/get/486671/AutoSPSourceBuilder.zip' "g:\"
    + CategoryInfo          : InvalidOperation: (:) [Start-BitsTransfer], Exception
    + FullyQualifiedErrorId : StartBitsTransferCOMException,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand

also

Start-BitsTransfer 'http://autospsourcebuilder.codeplex.com/downloads/get/486671' "g:\"

or

Start-BitsTransfer 'http://autospsourcebuilder.codeplex.com/downloads/get/486671#' "g:\"

with the same result.

 

Any ideas, how to download from codeplex?

Many thanks in advance,

 

Thorsten

 

 

Office 365 Script binding problem

$
0
0

I am working on a script that doing auto licensing for Office 365 Users, 

here is the script

 

 

$password = ConvertTo-SecureString "password" -AsPlainText –Force $credential = New-Object System.Management.Automation.PsCredential("myusername",$password) $cred = Get-Credential -cred $credential Import-Module MSOnline Connect-MsolService -Credential $cred $msoExchangeURL = “https://ps.outlook.com/powershell/” $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $msoExchangeURL -Credential $cred -Authentication Basic -AllowRedirection $Users = Get-MsolUser -Maxresults 200000 -DomainName MyDomain.com –UnlicensedUsersOnly | Select UserPrincipalName $AccountSkuIdFACULTY = "MyDomain:STANDARDWOFFPACK_FACULTY" $AccountSkuIdSTUDENT = "MyDomain:STANDARDWOFFPACK_STUDENT" $UsageLocation = "US" $LicenseOptions = New-MsolLicenseOptions -AccountSkuId $AccountSkuId $LicenseOptionsFACULTY = New-MsolLicenseOptions -AccountSkuId $AccountSkuIdFACULTY -DisabledPlans SHAREPOINTWAC_EDU,MCOSTANDARD,SHAREPOINTSTANDARD_EDU $LicenseOptionsSTUDENT = New-MsolLicenseOptions -AccountSkuId $AccountSkuIdSTUDENT -DisabledPlans SHAREPOINTWAC_EDU,MCOSTANDARD,SHAREPOINTSTANDARD_EDU $Users | Where-Object {$_.CustomAttribute7 -like "S_*"}| ForEach-Object {Set-MsolUser -UserPrincipalName $_.UserPrincipalName -UsageLocation $UsageLocation Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -AddLicenses $AccountSkuIdSTUDENT -LicenseOptions $LicenseOptionsSTUDENT }

 

 

when using this statement only it is working fine with me 

Get-MsolUser -Maxresults 200000 -DomainName education.qa –UnlicensedUsersOnly | Select UserPrincipalName

 

but when binding it with | Where-Object {$_.CustomAttribute7 -like "S_*"} as below it does not getting any result and if i changed the $_.CustomAttribute7 -like "S_*" to $_.CustomAttribute7 -like "*" it works but getting all results

$Users | Where-Object {$_.CustomAttribute7 -like "S_*"}| ForEach-Object {Set-MsolUser -UserPrincipalName $_.UserPrincipalName -UsageLocation $UsageLocation
Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -AddLicenses $AccountSkuIdSTUDENT  -LicenseOptions $LicenseOptionsSTUDENT }

 

 

 

can anyone help me please to get this script working

 

 

 

 

how to get the master OU for every user and populate it in ExtensionAttribute8

$
0
0

Hello All,

I am working on a script to add the master OU name only to the users extensionAttribute8 but i failed to do this.

e.g. I have these users distinguishedName

1- CN=user1,OU=10289,OU=Students,DC=mydomain,DC=com

2- CN=user2,OU=10335,OU=Staff,DC=mydomain,DC=com

3- CN=user3,OU=Teachers,DC=mydomain,DC=com

so how can I have the OU after DC=mydomain,DC=com (from right)  whatever the user exist on any child OU

for example i need for the first user1 to add Student word as a value to extensionattribute8

and for  user2 to add staff word as a value to extensionattribute8

and for  user3 to add Teachers word as a value to extensionattribute8

thanks a lot in advance

Call a 2nd PS, as another user and bring back paramters

$
0
0

Hi

 

I'm new to PS, but not scripting in general and am trying to create a script to automate our Win7 build process.

For various reasons, the machine will be built off the domain, then join itself to an existing machine account at the end.

In order to get the right set of applications installed, the machine account is added to an AD group when created and this info will need to be pulled back to call the applications.

During the build, the machine gets logged on as a local user with admin rights which has no access to the domain.

Now we come to the issue I am having...

I can get the PS1 to call PS2 one and pull back the required parameters, but only while logged on with a domain account.

The PS1 is as follows with some options I've tried commented out:

#Invoke-Command -FilePath R:\PostBuild\OUInfo.ps1#Invoke-Command -Credential $strCred -ScriptBlock {$strOU, $strCompName = & "R:\PostBuild\OUInfo.ps1"}$strOU, $strCompName = & "R:\PostBuild\OUInfo.ps1" -Credential $strCred

There is a working command above this to set $strCred - I know this works as it has been copied from a working PS.

When I try either of the Invoke-Command lines, I just get the following error:

 

Invoke-Command : Parameter set cannot be resolved using the specified named parameters.

At R:\PostBuild\PostBuild.ps1:10 char:15

+ Invoke-Command <<<<  -FilePath R:\PostBuild\OUInfo.ps1

    + CategoryInfo          : InvalidArgument: (:) [Invoke-Command], ParameterBindingException

    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeCommandCommand

 

But the line not using Invoke-Command works while run as a network user but doesn't use the credentials provided and thus falls over when run as a local user.

 

Sorry if I've been a bit ambiguous here, I may not be explaining myself properly

Does anyone know of a way to do what I need to do?

 

Thanks in advance

 

Matt

Want to "nest" a list in another Format-List

$
0
0

I have the command below that will give me a nice display of PrimarySMTP and other SMTP addresses (as well as the X400/500 addresses). The problem is that the proxyAddresses are listed as a long text block and I cannot find a way to display them as a list. Can I output a "Format-List" inside of another "Format-List" to pull this off?

get-qAdUser SamAcctNameHere...|

 

 

Select-Object

 

 

 

-PropertyprimarySMTPaddress,@{Name='ListOfOthers';Expression=

{

 

 

 

$_.proxyAddresses -join","}}

|

 

 

 

Format-List


Odd param behaviour

$
0
0

Hello All

Can anyone explain the following odd behaviour

Example 1

Param (
[string]$Volume="Ernie",
[string]$ShapshotNameExpr="$Volume-Brant"
)
cls
$Volume
$ShapshotNameExpr

$Volume.Length
$ShapshotNameExpr.Length

Output 1 (as you would expect)

Ernie
Ernie-Brant
5
11

now see what happens in example 2, when changing the "-" after the $Volume variable to a "_"

Example 2

Param (
[string]$Volume="Ernie",
[string]$ShapshotNameExpr="$Volume_Brant"
)
cls
$Volume
$ShapshotNameExpr

$Volume.Length
$ShapshotNameExpr.Length

Output 2

Ernie

5
0

We end up with a zero lenght string for the variable $ShapshotNameExpr weird!

so I thoguht it must be something to do the with "_" and tried the following

Example 3

Param (
[string]$Volume="Ernie",
[string]$ShapshotNameExpr="_$Volume-Brant"
)
cls
$Volume
$ShapshotNameExpr

$Volume.Length
$ShapshotNameExpr.Length

Output 3

Ernie
_Ernie-Brant
5
12

The above is back to normal behaviour, so it appears if I put the "_" any where "after" the $Volume variable it turns it (i.e. the $volume variable and any thing after it) to a zero lenght string.

Example 4

Param (
[string]$Volume="Ernie",
[string]$ShapshotNameExpr="_Hello$Volume_Brant"
)
cls
$Volume
$ShapshotNameExpr

$Volume.Length
$ShapshotNameExpr.Length

Output 4

Ernie
_Hello
5
6


Does any one know why it behaves in this way, I can only assume "_" is a reserved (not allowed) character in variable names when following another variable?

Thank all in advance, I am using PowerShell v2

Ernie

 

 

 

 

 

 

 

reboot a list of servers and output results to file.

$
0
0

I am new to powershell and i am trying to write a simple script that will reboot a list of machines (XP, and 7) and input the results of the reboots to a text file.  I created the below script that reboots the machine and creates the output file, but when I open the file I do not see any results in it. 

restart-computer (get-content c:\reboot\rebootlist.txt) | out-file -filepath c:\results.txt

I also found the below script but for some reason it will not work, but it's not rebooting the machines.  I can get it to show me the list of machines in the text file but it does not reboot them.  My plan was to get it working and output the results to a file, but it's not working out for me.

Get-Content C:\reboot\rebootlist.txt |
   Where {test-connection $_ -quiet -count 2} |
   foreach {
    write-host "Restarting $_ "-force "Green"
    Restart-Computer $_ -force -whatif}

Please let me know if you have any suggestions.

 

Creating a Powershell script to add a key to multiple web.config files.

$
0
0

I am attempting to create a script that will update multiple web config files (120) with a new add key value. So far the script is what I have so far, however when I run it. It adds it as a hole new node instead of just an add key value. Please help! 

 

********************Web.config**********************

  <appSettings>

 

    <add key="Database" value="something" />

    <add key="UUDecodePassword" value="true" />

    <!--<add key="ClientName" value="DEVELOPMENT" />-->

    <add key="ClientFolder" value="Test" />

    <add key="OfflineApplicationHref" value="https://snowboaridng.com/publish.htm" />

    <!--<add key="ReportingServiceHref" value="https://snowboaridng.com/report/publish.htm" />-->

    <!--<add key="ReportingServiceUserName" value="" />-->

    <!--<add key="ReportingServicePassword" value="" />-->

    <!--<add key="ReportingServiceDomain" value="" />-->

    <add key="ReportViewerServerConnection" value="ReportViewerServerConnection, APP_CODE" />

    <!--<add key="WebDialerURL" value="https://snowbaording.com/rider/services/rider/SoapService"/>-->

    <add key="CacheHost" value="testdb" />

    <add key="aspnet:MaxHttpCollectionKeys" value="5000" />

      <add key="https://snowboaridng.com/admin/AuthForm.aspx?guid=5265df71-1fb2-4436-ac94-bf4cde170005" />

  </appSettings>

 

*************************************************************

 

*********************Begin Script ******************************

 

# Array of files to make changes to, add as many as you like

$filesarray = @("C:\Users\Documents\powershellscript\webconfig\websn.config","C:\Users\Documents\powershellscript\webconfig\websb.config") 

# Go thru all files

foreach ($filename in $filesarray)

{

    # Get file + cast as xml

    $xml = [xml](get-content $filename)

 

    # Backup file before making changes

    $backup = $filename + "-" + (get-date).tostring("yyyy-MM-dd-hh_mm_s")

    $xml.Save($backup)

 

    $root = $xml.get_DocumentElement();

 

 # Add a new node

    $node = $xml.createElement("FeedbackFormURL")

    $root."appSettings".appendChild($node)

    $subnode = $xml.createElement("add")

    $node.AppendChild($subnode)

    $attribute = $xml.CreateAttribute("key")

    $attribute.set_Value("https://snowboaridng.com/admin/AuthForm.aspx?guid=5265df71-1fb2-4436-ac94-bf4cde170005")

    $subnode.SetAttributeNode($attribute )

 

    # Save

    $xml.Save($filename)     

}

 

 

 

 

 

 

 

 

Change a .lnk target

$
0
0

Hi 'm fairly new to PowerShell and I' m looking for a way to use a PowerShell script to change a short cuts target from an HTTP:\\ link to C:\Windows\System32\rundll32.exe dsquery.dll,OpenQueryWindow on all my work stations on my network. This is what i have come up with so far:

$objShell = New-Object -ComObject WScript.Shell
   $lnk = $objShell.CreateShortcut("C:\Users\username\Desktop\Test.lnk")
   $lnk.TargetPath = "C:\Windows\System32\rundll32.exe dsquery.dll,OpenQueryWindow"
   $lnk.Save()

Every time that i run this i get the following error when looking at the properties of the link "The name 'C:\Windows\System32\rundll32.exe dsquery.dll,OpenQueryWindow' specified in the Target box is not valid"

Now if I just type just in the new target in the target filed it works just fine.

Any ideas?

Thank you for the help!

List Ad Groups With Same Attributes

$
0
0

Hello I'm wondering how I can user powershell to show me a list of AD groups with the same attributes to locations within the same domain

Viewing all 8411 articles
Browse latest View live