Compare commits

..

12 Commits

Author SHA1 Message Date
fdc6651588 Publish version 1.0.x (#45)
## About

## Content (Micro Commits)

* fixes #38 
* fixes #44 
* Implement precise lookup hierarchy (fixes #43)
* align pester test with #43 logic
* split cert functions
* use new cert functions for save an lookup
* fix pester tests
* [wip]
* fix var name ref
* fix exports
* fix cert store location for windows shared mode
* fix mandatory params
* fix accidentially removed code block
* add basic cert pester pests
* remove old docs
* update cbh blocks
* update cbh blocks
* update docs
* move .net wrapper forpfx files
* do not export .net wrapper functions
* update docs
* rename tests
* fix private functions location
* - fixes #44: FTP connection
* add link to reference
* add format files
* add preview version shield
* update markdown help files (platyps)
* add emoji images in captions
* fix typos
* fix typos
* fix typo
* prepare version numbers
2019-04-29 16:05:43 +02:00
d92d963979 Publish preview version (#42)
* adds certificate store location

* add additional certificate store tests

* add cert store tests for New-CredentialStoreItem

* fix test

* add error handling for credential store path

* add Import-CSCertificate helper function

* Import new certificate if param is given

* fix extension filter

* add linux error message

* fix pester test for linux

* update cert helper functions

* export helper functions

* fix cs cert import

* simplify cs cret lookup

* remove obsolete functions

* fix pester test for linux

* fix error type for linux

* fix var name

* fix pester test

* disable travis artifact upload

* update cert lookup for item functions

* debug build error

* use cert instance constructor for linux

* disable debug output

* remove obsolete exports
2019-04-04 17:02:17 +02:00
5a68527061 fix Connect-To bug (#41)
* replace internal coverage tools with PSCoverage (#39)

* use PSCoverage instead of internal module

* remove internal pscoverage ref

* remove deprecated and internal coverage module

* fix dependency test for conection types without deps

* - tests should return true for missing deps (fixes #40)

* remove pre release counter

* change prerelease tag
2019-03-15 12:49:43 +01:00
dbf53b7cb0 publish 0.5.xxx-alpha1 release 2019-01-16 13:18:27 +01:00
09548fca0a add debug output (#36) 2019-01-16 13:02:51 +01:00
afab3c870c PowerShell 6 Core Support (#35)
## About
This pull request reflects all changes done in the `linuxsupport` branch.

## Content
- Enable PowerShell 6 Core support
- Use PFX Certificate for encryption ( fixes #32 )
- Updates CI / CD pipeline ( fixes #31 )
- uses portable libressl ( fixes #34 )
- adds `-PassThru` switch for returning current `VIServer` session in `Connect-To` ( fixes #34 )
- adds git lfs for embedded libressl files
- restructured internal functions into `Private` dir
- added certificate related functions
- adds travis build pipeline for tests
2019-01-16 12:55:29 +01:00
ab13962f6e Fix FTP Connection Error (#29)
* fixes #27
* fix var name typo
* bump version
2018-03-26 13:01:34 +02:00
680f37c00e fixed another var name typo 2018-03-21 15:30:14 +01:00
1773f1fc06 fixes #26 2018-03-21 15:18:18 +01:00
c0b13052b3 Enables pipeline input for -Credential parameter (#25) 2018-03-21 14:32:32 +01:00
8d55f2d6fd disable AppVeyor builds for specific branches (fixes #23) 2018-03-21 12:52:59 +01:00
ce823d4564 Increase code coverage (#22) 2018-03-21 12:16:09 +01:00
102 changed files with 3842 additions and 1422 deletions

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
src/Vendor/libressl255/* filter=lfs diff=lfs merge=lfs -text
*.pfx filter=lfs diff=lfs merge=lfs -text

42
.travis.yml Normal file
View File

@ -0,0 +1,42 @@
language: csharp
dotnet: 2.2.101
mono: none
git:
depth: 1000
os:
- linux
# Disable OSX bulds for now
# - osx
sudo: required
dist: xenial
osx_image: xcode8.1
matrix:
fast_finish: true
#addons:
# artifacts:
# paths: ./dist/PowerShellGet.zip
install:
# Default 2.0.0 Ruby is buggy
# Default bundler version is buggy
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then
rvm install ruby-2.3.3;
rvm --default use 2.3.3;
fi
- bash <(wget -O - https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/install-powershell.sh)
- pushd tools
- chmod +x travis.sh
- popd
script:
- echo "TRAVIS_EVENT_TYPE value $TRAVIS_EVENT_TYPE"
- ./tools/travis.sh

96
.vscode/launch.json vendored
View File

@ -1,48 +1,48 @@
{ {
// Use IntelliSense to learn about possible attributes. // Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes. // Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"type": "PowerShell", "type": "PowerShell",
"request": "launch", "request": "launch",
"name": "PowerShell Launch Current File", "name": "PowerShell Launch Current File",
"script": "${file}", "script": "${file}",
"args": [], "args": [],
"cwd": "${file}" "cwd": "${file}"
}, },
{ {
"type": "PowerShell", "type": "PowerShell",
"request": "launch", "request": "launch",
"name": "PowerShell Launch Current File in Temporary Console", "name": "PowerShell Launch Current File in Temporary Console",
"script": "${file}", "script": "${file}",
"args": [], "args": [],
"cwd": "${file}", "cwd": "${file}",
"createTemporaryIntegratedConsole": true "createTemporaryIntegratedConsole": true
}, },
{ {
"type": "PowerShell", "type": "PowerShell",
"request": "launch", "request": "launch",
"name": "PowerShell Launch Current File w/Args Prompt", "name": "PowerShell Launch Current File w/Args Prompt",
"script": "${file}", "script": "${file}",
"args": [ "args": [
"${command:SpecifyScriptArgs}" "${command:SpecifyScriptArgs}"
], ],
"cwd": "${file}" "cwd": "${file}"
}, },
{ {
"type": "PowerShell", "type": "PowerShell",
"request": "attach", "request": "attach",
"name": "PowerShell Attach to Host Process", "name": "PowerShell Attach to Host Process",
"processId": "${command:PickPSHostProcess}", "processId": "${command:PickPSHostProcess}",
"runspaceId": 1 "runspaceId": 1
}, },
{ {
"type": "PowerShell", "type": "PowerShell",
"request": "launch", "request": "launch",
"name": "PowerShell Interactive Session", "name": "PowerShell Interactive Session",
"cwd": "${workspaceRoot}" "cwd": ""
} }
] ]
} }

View File

@ -26,7 +26,8 @@
"powershell.codeFormatting.whitespaceAroundOperator": true, "powershell.codeFormatting.whitespaceAroundOperator": true,
"powershell.codeFormatting.whitespaceAfterSeparator": true, "powershell.codeFormatting.whitespaceAfterSeparator": true,
"powershell.codeFormatting.ignoreOneLineBlock": true, "powershell.codeFormatting.ignoreOneLineBlock": true,
"powershell.codeFormatting.alignPropertyValuePairs": false, "powershell.codeFormatting.alignPropertyValuePairs": true,
"powershell.codeFormatting.preset": "Custom",
// cspell spellchecker options // cspell spellchecker options
"cSpell.enabledLanguageIds": [ "cSpell.enabledLanguageIds": [
"c", "c",

View File

@ -1,39 +1,50 @@
[![AppVeyor branch](https://img.shields.io/appveyor/ci/OCram85/PSCredentialStore/master.svg?style=plastic "Master Banch Build Status")](https://ci.appveyor.com/project/OCram85/pscredentialstore/branch/master) [![AppVeyor branch](https://img.shields.io/appveyor/ci/OCram85/PSCredentialStore/master.svg?style=plastic "Master Branch Build Status")](https://ci.appveyor.com/project/OCram85/pscredentialstore/branch/master)
[![AppVeyor tests branch](https://img.shields.io/appveyor/tests/OCram85/PSCredentialStore/master.svg?style=plastic "Pester Tests Results")](https://ci.appveyor.com/project/OCram85/pscredentialstore/branch/master/tests) [![AppVeyor tests branch](https://img.shields.io/appveyor/tests/OCram85/PSCredentialStore/master.svg?style=plastic "Pester Tests Results")](https://ci.appveyor.com/project/OCram85/pscredentialstore/branch/master/tests)
[![Coveralls github](https://img.shields.io/coveralls/github/OCram85/PSCredentialStore.svg?style=plastic "Coveralls.io Coverage Report")](https://coveralls.io/github/OCram85/PSCredentialStore?branch=master) [![Coveralls github](https://img.shields.io/coveralls/github/OCram85/PSCredentialStore.svg?style=plastic "Coveralls.io Coverage Report")](https://coveralls.io/github/OCram85/PSCredentialStore?branch=master)
[![PowerShell Gallery](https://img.shields.io/powershellgallery/v/PSCredentialStore.svg?style=plastic "PowershellGallery Published Version")](https://www.powershellgallery.com/packages/PSCredentialStore) [![PowerShell Gallery](https://img.shields.io/powershellgallery/v/PSCredentialStore.svg?style=plastic "PowershellGallery Published Version")](https://www.powershellgallery.com/packages/PSCredentialStore)
[![PowerShell Gallery](https://img.shields.io/powershellgallery/vpre/PSCredentialStore.svg?label=latest%20preview&style=plastic "PowershellGallery Latest Preview Version")](https://www.powershellgallery.com/packages/PSCredentialStore)
[![PowerShell Gallery](https://img.shields.io/powershellgallery/dt/PSCredentialStore.svg?style=plastic "PowershellGallery Downloads")](https://www.powershellgallery.com/packages/PSCredentialStore) [![PowerShell Gallery](https://img.shields.io/powershellgallery/dt/PSCredentialStore.svg?style=plastic "PowershellGallery Downloads")](https://www.powershellgallery.com/packages/PSCredentialStore)
![forthebadge](http://forthebadge.com/images/badges/built-with-love.svg) ![forthebadge](http://forthebadge.com/images/badges/built-with-love.svg)
![forthebadge](http://forthebadge.com/images/badges/for-you.svg) ![forthebadge](http://forthebadge.com/images/badges/for-you.svg)
General :key: General
======= =======
The PSCredentialStore is a simple credential manager for PSCredentials. It stores PSCredentials in a simple json The PSCredentialStore is a simple credential manager for `PSCredential` objects. It stores PSCredentials in a simple json
file. You can choose between a private and shared credential store. The private one exists in your profile and can file. You can choose between a private and shared credential store. The private one exists in your profile and can
ony accessed by your account on the same machine. The shared store enables you to use different credentials for your ony accessed by your account on the same machine. The shared store enables you to use different credentials for your
scripts without exposing them as plain text. scripts without exposing them as plain text.
**The shared store isn't 100% secure and I don't recommend using it in production!**
PSCredentialStore was developed to simplify the delegation of complex powershell scripts. In this case you often PSCredentialStore was developed to simplify the delegation of complex powershell scripts. In this case you often
need to store credentials for non interactive usage like in scheduled tasks. need to store credentials for non interactive usage like in scheduled tasks.
Starting with version `1.0.0` PSCredential uses Pfx certificates fo encryption. You can use Pfx certificate files
or certificates stored in the certificate store.
For more details read the [about_PSCredentialStore](/docs/about_PSCredentialStore.md) page on github or via CLI with For more details read the [about_PSCredentialStore](/docs/about_PSCredentialStore.md) page on github or via CLI with
`Get-Help about_PSCredentialStore`. `Get-Help about_PSCredentialStore`.
Installation You can find the [reference](/docs/PSCredentialStore.md) in the /docs/ path as well.
:vulcan_salute: Requirements
============ ============
PowerShellGallery.com (Recommended Way) - PowerShell >= `5.1`
- .NET Framework >= `4.6` or .NET Core >= `1.0`
:hammer_and_wrench: Installation
============
:artificial_satellite: PowerShellGallery.com (Recommended Way)
--------------------------------------- ---------------------------------------
* Make sure you use PowerShell 4.0 or higher with `$PSVersionTable`. * Make sure you use PowerShell 5.1 or higher with `$PSVersionTable`.
* Use the builtin PackageManagement and install with: `Install-Module PSCredentialStore` * Use the builtin PackageManagement and install with: `Import-Module PowerShellGet; Install-Module 'PSCredentialStore' -Repository 'PSGallery'`
* Additionally use the `-AllowPrerelease` switch until we publish the final release!
* Done. Start exploring the Module with `Import-Module PSCredentialStore ; Get-Command -Module PSCredentialStore` * Done. Start exploring the Module with `Import-Module PSCredentialStore ; Get-Command -Module PSCredentialStore`
Manual Way :building_construction: Manual Way
---------- ----------
* Take a look at the [Latest Release](https://github.com/OCram85/PSCredentialStore/releases/latest) page. * Take a look at the [Latest Release](https://github.com/OCram85/PSCredentialStore/releases/latest) page.
@ -42,19 +53,27 @@ Manual Way
* Don't forget to change the NTFS permission flag in the context menu. * Don't forget to change the NTFS permission flag in the context menu.
* Start with `Import-Module PSCredentialStore` * Start with `Import-Module PSCredentialStore`
Quick Start :sparkles: Quick Start
----------- -----------
**1.** First we need a blank credential store. You can decide between a *private* or *shared* store. The private **1.** First we need a blank credential store. You can decide between a *private* or *shared* store. The private
Credential Store can only be accessed with your profile on the machine you created it. Credential Store can only be accessed with your profile on the machine you created it.
Starting with version `1.0.0` you can decide the storage type of your fresh created certificate. As default
PSCredentialStore creates a new pfx certificate file beside the credential store itself. Optionally you can provide
the parameter `-UseCertStore`. This imports the new certificate in the user or machine certificate store as well.
```powershell ```powershell
# Private credential store # Private credential store
New-CredentialStore New-CredentialStore
# Shared credential rtore # Private credential store with certificate store usage
New-CredentialStore -UseCertStore
# Shared credential store
New-CredentialStore -Shared New-CredentialStore -Shared
#Shared credential store in custom Location #Shared credential store in custom location
New-CredentialStore -Shared -Path 'C:\CredentialStore.json' New-CredentialStore -Shared -Path 'C:\CredentialStore.json'
``` ```
@ -96,4 +115,17 @@ Connect-To -RemoteHost "ftp.myside.local" -Type FTP
Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS
Connect-To -RemoteHost "esx01.myside.local" -Type VMware Connect-To -RemoteHost "esx01.myside.local" -Type VMware
Connect-To -RemoteHost "vcr.myside.local" -Type CisServer Connect-To -RemoteHost "vcr.myside.local" -Type CisServer
Connect-To -RemoteHost "exchange1.myside.local" -Type ExchangeHTTP
Connect-To -RemoteHost "exchange1.myside.local" -Type ExchangeHTTPS
Connect-To -RemoteHost "ubuntu.myside.local" -Type SCP
``` ```
:pushpin: Credits
-------
A huge thanks to all the people who helped with their projects and indirect contributions which made this possible!
- This module is inspired by the awesome work of Dave Wyatt ([@dlwyatt](https://github.com/dlwyatt)) with articles like these:
- https://powershell.org/2013/11/24/saving-passwords-and-preventing-other-processes-from-decrypting-them/
- https://powershell.org/2014/02/01/revisited-powershell-and-encryption/
- The awesome people from [LibreSSL](http://www.libressl.org/) which publishes the [portable openssl/libressl binaries](https://github.com/libressl-portable/portable)!

View File

@ -1,10 +1,11 @@
version: 0.2.1.{build} # pre release version:
version: 1.0.{build}
branches: #branches:
only: # only:
- master # - master
- dev # - dev
- debug # - debug
skip_tags: true skip_tags: true
@ -20,7 +21,7 @@ image: Visual Studio 2017
install: install:
- ps: Import-Module .\tools\AppVeyor.psm1 - ps: Import-Module .\tools\AppVeyor.psm1
- ps: Invoke-InstallDependencies -Verbose - ps: Invoke-InstallDependencies
environment: environment:
NuGetToken: NuGetToken:
@ -37,10 +38,10 @@ build_script:
- ps: Invoke-AppVeyorBuild - ps: Invoke-AppVeyorBuild
test_script: test_script:
- ps: Invoke-AppVeyorTests
- ps: | - ps: |
$CodeCoverage = Invoke-AppVeyorTests
if ($null -ne $Env:CoverallsToken) { if ($null -ne $Env:CoverallsToken) {
Invoke-CoverageReport Invoke-CoverageReport -PesterCoverageReport $CodeCoverage
} }
else { else {
Write-Warning "No CoverallsToken found. This build seems to be triggered by a PR. Skipping this step..." Write-Warning "No CoverallsToken found. This build seems to be triggered by a PR. Skipping this step..."
@ -60,7 +61,7 @@ deploy:
secure: M+bBX5/nKdJB0eViP7xtrLVTwf3vGDUA9N2MMprZp2i+9ZR3CBVcJnSzJWUmalhB secure: M+bBX5/nKdJB0eViP7xtrLVTwf3vGDUA9N2MMprZp2i+9ZR3CBVcJnSzJWUmalhB
artifact: PSCredentialStore.zip # upload all NuGet packages to release assets artifact: PSCredentialStore.zip # upload all NuGet packages to release assets
draft: false draft: false
prerelease: false prerelease: true
on: on:
branch: master # build release on master branch changes branch: master # build release on master branch changes

BIN
assets/logo256.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Connect-To # Connect-To
## SYNOPSIS ## SYNOPSIS
@ -14,14 +7,14 @@ Connects to the given host using the stored CredentialStoreItem.
### Private (Default) ### Private (Default)
``` ```
Connect-To -RemoteHost <String> [-Identifier <String>] -Type <String> [-Credentials <PSCredential>] Connect-To -RemoteHost <String> [-Identifier <String>] -Type <String> [-Credentials <PSCredential>] [-PassThru]
[<CommonParameters>] [<CommonParameters>]
``` ```
### Shared ### Shared
``` ```
Connect-To -RemoteHost <String> [-Identifier <String>] -Type <String> [-Credentials <PSCredential>] Connect-To -RemoteHost <String> [-Identifier <String>] -Type <String> [-Credentials <PSCredential>] [-Shared]
[-Path <String>] [-Shared] [<CommonParameters>] [-Path <String>] [-PassThru] [<CommonParameters>]
``` ```
## DESCRIPTION ## DESCRIPTION
@ -29,37 +22,37 @@ Establish a connection to the selected host using a stored CredentialStoreItem.
## EXAMPLES ## EXAMPLES
### EXAMPLE 1 ### BEISPIEL 1
``` ```
Connect-To -RemoteHost "ucs.myside.local" -Type CiscoUcs Connect-To -RemoteHost "ucs.myside.local" -Type CiscoUcs
``` ```
### EXAMPLE 2 ### BEISPIEL 2
``` ```
Connect-To -RemoteHost "ftp.myside.local" -Type FTP Connect-To -RemoteHost "ftp.myside.local" -Type FTP
``` ```
### EXAMPLE 3 ### BEISPIEL 3
``` ```
Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS Connect-To -RemoteHost "fas.myside.local" -Type NetAppFAS
``` ```
### EXAMPLE 4 ### BEISPIEL 4
``` ```
Connect-To -RemoteHost "esx01.myside.local" -Type VMware Connect-To -RemoteHost "esx01.myside.local" -Type VMware
``` ```
### EXAMPLE 5 ### BEISPIEL 5
``` ```
Connect-To -RemoteHost "vCenter.myside.local" -Type CisServer Connect-To -RemoteHost "vCenter.myside.local" -Type CisServer
``` ```
### EXAMPLE 6 ### BEISPIEL 6
``` ```
Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP
``` ```
### EXAMPLE 7 ### BEISPIEL 7
``` ```
Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
``` ```
@ -102,6 +95,21 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -PassThru
Returns the value from the underlying connection type function.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path ### -Path
Define a custom path to a shared CredentialStore. Define a custom path to a shared CredentialStore.
@ -112,7 +120,7 @@ Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -142,7 +150,7 @@ Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -167,21 +175,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
File Name : Connect-To.ps1 - File Name : Connect-To.ps1
Author : Marco Blessing - marco.blessing@googlemail.com - Author : Marco Blessing - marco.blessing@googlemail.com
Requires : - Requires :
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Disconnect-From # Disconnect-From
## SYNOPSIS ## SYNOPSIS
@ -21,42 +14,42 @@ Terminates a session established with Connect-To using a CredentialStoreItem.
## EXAMPLES ## EXAMPLES
### EXAMPLE 1 ### BEISPIEL 1
``` ```
Disconnect-From -RemoteHost "ucs.myside.local" -Type CiscoUcs Disconnect-From -RemoteHost "ucs.myside.local" -Type CiscoUcs
``` ```
### EXAMPLE 2 ### BEISPIEL 2
``` ```
Disconnect-From -RemoteHost "ftp.myside.local" -Type FTP Disconnect-From -RemoteHost "ftp.myside.local" -Type FTP
``` ```
### EXAMPLE 3 ### BEISPIEL 3
``` ```
Disconnect-From -RemoteHost "fas.myside.local" -Type NetAppFAS Disconnect-From -RemoteHost "fas.myside.local" -Type NetAppFAS
``` ```
### EXAMPLE 4 ### BEISPIEL 4
``` ```
Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware
``` ```
### EXAMPLE 5 ### BEISPIEL 5
``` ```
Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware -Force:$True Disconnect-From -RemoteHost "esx01.myside.local" -Type VMware -Force:$True
``` ```
### EXAMPLE 6 ### BEISPIEL 6
``` ```
Disconnect-From -RemoteHost "vcenter.myside.local" -Type CisServer Disconnect-From -RemoteHost "vcenter.myside.local" -Type CisServer
``` ```
### EXAMPLE 7 ### BEISPIEL 7
``` ```
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTP
``` ```
### EXAMPLE 8 ### BEISPIEL 8
``` ```
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
``` ```
@ -111,21 +104,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
File Name : Disconnect-From.ps1 - File Name : Disconnect-From.ps1
Author : Marco Blessing - marco.blessing@googlemail.com - Author : Marco Blessing - marco.blessing@googlemail.com
Requires : - Requires :
## RELATED LINKS ## RELATED LINKS

71
docs/Get-CSCertificate.md Normal file
View File

@ -0,0 +1,71 @@
# Get-CSCertificate
## SYNOPSIS
Returns the current used valid PfX certificate.
## SYNTAX
```
Get-CSCertificate [-Type] <String> [-Thumbprint] <String> [<CommonParameters>]
```
## DESCRIPTION
Use this function to get the available pfx certificate respecting the config hierarchy.
## EXAMPLES
### BEISPIEL 1
```
Get-CSCertificate -Type 'Shared' -Thumbprint '12334456'
```
## PARAMETERS
### -Thumbprint
Provide the credentials thumbprint for the search.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Type
Select the current credential store type.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [System.Security.Cryptography.X509Certificates.X509Certificate2]
## NOTES
- File Name : Get-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Get-CredentialStore # Get-CredentialStore
## SYNOPSIS ## SYNOPSIS
@ -31,7 +24,7 @@ Get-CredentialStoreItem.
## EXAMPLES ## EXAMPLES
### EXAMPLE 1 ### BEISPIEL 1
``` ```
$CSContent = Get-CredentialStore -Path "C:\TMP\mystore.json" $CSContent = Get-CredentialStore -Path "C:\TMP\mystore.json"
``` ```
@ -48,7 +41,7 @@ Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -63,7 +56,7 @@ Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -71,23 +64,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [PSObject] Returns the credential store content as PSObject. ### [PSObject] Returns the credential store content as PSObject.
## NOTES ## NOTES
\`\`\` - File Name : Get-CredentialStore.ps1
File Name : Get-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Get-CredentialStoreItem # Get-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
@ -19,7 +12,7 @@ Get-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [<CommonPara
### Shared ### Shared
``` ```
Get-CredentialStoreItem [-Path <String>] -RemoteHost <String> [-Identifier <String>] [-Shared] Get-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Shared] [-Path <String>]
[<CommonParameters>] [<CommonParameters>]
``` ```
@ -28,7 +21,7 @@ Return the credential as PSCredential object.
## EXAMPLES ## EXAMPLES
### EXAMPLE 1 ### BEISPIEL 1
``` ```
$myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" $myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
``` ```
@ -63,7 +56,7 @@ Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -93,7 +86,7 @@ Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -101,23 +94,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [System.Management.Automation.PSCredential] ### [System.Management.Automation.PSCredential]
## NOTES ## NOTES
\`\`\` - File Name : Get-CredentialStoreItem.ps1
File Name : Get-CredentialStoreItem.ps1 - Author : Messing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -0,0 +1,72 @@
# Import-CSCertificate
## SYNOPSIS
Imports a linked certificate to the valid store location.
## SYNTAX
```
Import-CSCertificate [-Type] <String> [-Path] <FileInfo> [<CommonParameters>]
```
## DESCRIPTION
Import-CSCertificate takes a pfx certificate file and imports it to the supposed certificate store for
private and shared credential stores.
## EXAMPLES
### BEISPIEL 1
```
Import-CSCertificate -Type 'Private' -Path (Join-Path -Path $Env:APPDATA -ChildItem 'PfxCertificate.pfx')
```
## PARAMETERS
### -Path
Provide a valid path to pfx certificate file.
```yaml
Type: FileInfo
Parameter Sets: (All)
Aliases:
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Type
Select between the a private and shared credential store.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [None]
## NOTES
- File Name : Import-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

147
docs/New-CSCertAttribute.md Normal file
View File

@ -0,0 +1,147 @@
# New-CSCertAttribute
## SYNOPSIS
Creates required data for a certificate signing request.
## SYNTAX
```
New-CSCertAttribute [-Country] <String> [-State] <String> [-City] <String> [-Organization] <String>
[-OrganizationalUnitName] <String> [-CommonName] <String> [[-Days] <Int32>] [<CommonParameters>]
```
## DESCRIPTION
Defines the certificate related properties for an upcoming New-PfxCertificate execution.
## EXAMPLES
### BEISPIEL 1
```
New-CSCertAttribute -Country 'DE' -State 'BW' -City 'Karlsruhe' -Organization 'AwesomeIT' -OrganizationalUnitName '' -CommonName 'MyPrivateCert'
```
## PARAMETERS
### -City
Certificate city value.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 3
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -CommonName
The certificate common name.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 6
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Country
County code like EN, DE, IT, FR...
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Days
The validation time itself.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: 7
Default value: 365
Accept pipeline input: False
Accept wildcard characters: False
```
### -Organization
Certificate organization value.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 4
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -OrganizationalUnitName
Certificate OrganizationalUnitName value.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 5
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -State
Certificate state value.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [PSCredentialStore.Certificate.CSRDetails]
## NOTES
- File Name : New-CSCertAttribute.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

120
docs/New-CSCertificate.md Normal file
View File

@ -0,0 +1,120 @@
# New-CSCertificate
## SYNOPSIS
Creates a new PFX certificate for the CredentialStore encryption.
## SYNTAX
```
New-CSCertificate [-CRTAttribute] <Object> [[-KeyName] <String>] [[-CertName] <String>] [-WhatIf] [-Confirm]
[<CommonParameters>]
```
## DESCRIPTION
Use this function to create a custom self signed certificate used by the PSCredentialStore module.
## EXAMPLES
### BEISPIEL 1
```
New-CSCertificate -CRTAttribute $CRTAttribute -KeyName './myprivate.key' -CertName './mycert.pfx'
```
## PARAMETERS
### -CertName
Provide a custom full path and name for the PFX certificate file.
The file extension has to be \`*.pfx\`
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 3
Default value: ./certificate.pfx
Accept pipeline input: False
Accept wildcard characters: False
```
### -CRTAttribute
Provide certificate related attributes provided by function New-CRTAttribute.
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```
### -KeyName
Provide a custom full path and name for the private key.
The file extension has to be \`*.key\`.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 2
Default value: ./private.key
Accept pipeline input: False
Accept wildcard characters: False
```
### -Confirm
Prompts you for confirmation before running the cmdlet.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [PSCredentialStore.Certificate.Attribute]
## OUTPUTS
### [None]
## NOTES
- File Name : New-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# New-CredentialStore # New-CredentialStore
## SYNOPSIS ## SYNOPSIS
@ -14,12 +7,14 @@ Creates a new credential store File
### Private (Default) ### Private (Default)
``` ```
New-CredentialStore [-Force] [<CommonParameters>] New-CredentialStore [-Force] [-PassThru] [-SkipPFXCertCreation] [-UseCertStore] [-WhatIf] [-Confirm]
[<CommonParameters>]
``` ```
### Shared ### Shared
``` ```
New-CredentialStore [-Shared] [-Path <String>] [-Force] [<CommonParameters>] New-CredentialStore [-Shared] [-Path <FileInfo>] [-Force] [-PassThru] [-SkipPFXCertCreation] [-UseCertStore]
[-WhatIf] [-Confirm] [<CommonParameters>]
``` ```
## DESCRIPTION ## DESCRIPTION
@ -28,28 +23,28 @@ save new credentials with New-CredentialStoreItem.
## EXAMPLES ## EXAMPLES
### EXAMPLE 1 ### BEISPIEL 1
``` ```
New-CredentialStore New-CredentialStore
``` ```
# Creates a new private CredentialStore # Creates a new private CredentialStore
### EXAMPLE 2 ### BEISPIEL 2
``` ```
New-CredentialStore -Force New-CredentialStore -Force
``` ```
# Resets an existing private CredentialStore # Resets an existing private CredentialStore
### EXAMPLE 3 ### BEISPIEL 3
``` ```
New-CredentialStore -Shared New-CredentialStore -Shared
``` ```
# Creates a new shared CredentialStore # Creates a new shared CredentialStore
### EXAMPLE 4 ### BEISPIEL 4
``` ```
New-CredentialStore -Shared -Path "C:\TMP\CredentialStore.json" New-CredentialStore -Shared -Path "C:\TMP\CredentialStore.json"
``` ```
@ -74,19 +69,34 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -PassThru
{{ Fill PassThru Description }}
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path ### -Path
Define a location for the new shared CredentialStore. Define a location for the new shared CredentialStore.
The default store will be created in The default store will be created in
$Env:ProgramData\PSCredentialStore dir. $Env:ProgramData\PSCredentialStore dir.
```yaml ```yaml
Type: String Type: FileInfo
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -102,6 +112,23 @@ Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -SkipPFXCertCreation
You can skip the pfx certificate creation process.
This makes sense if you have a previously created cert or want to
import a cert in cross-platform environments.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: False Default value: False
@ -109,24 +136,69 @@ Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
### -UseCertStore
Instead of using a plain pfx file beside your CredentialStore file you can import it into the user or machine
certificate store.
In this case the system itself secures the cert and you don't hat to set custom NTFS
permissions so secure your shared certificate.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Confirm
Prompts you for confirmation before running the cmdlet.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### ['PSCredentialStore.Store'] Returns the recently created CredentialStore object if the -PassThru parameter
### was given.
## NOTES ## NOTES
\`\`\` - File Name : New-CredentialStore.ps1
File Name : New-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# New-CredentialStoreItem # New-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
@ -20,8 +13,8 @@ New-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential
### Shared ### Shared
``` ```
New-CredentialStoreItem [-Path <String>] -RemoteHost <String> [-Identifier <String>] New-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential <PSCredential>] [-Shared]
[-Credential <PSCredential>] [-Shared] [<CommonParameters>] [-Path <String>] [<CommonParameters>]
``` ```
## DESCRIPTION ## DESCRIPTION
@ -33,7 +26,7 @@ a VIConnection, NetApp FAS or UCS Fabric Interconnect.
## EXAMPLES ## EXAMPLES
### EXAMPLE 1 ### BEISPIEL 1
``` ```
New-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" New-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
``` ```
@ -51,7 +44,7 @@ Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: None Default value: None
Accept pipeline input: False Accept pipeline input: True (ByValue)
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -83,7 +76,7 @@ Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -104,14 +97,16 @@ Accept wildcard characters: False
``` ```
### -Shared ### -Shared
{{Fill Shared Description}} Define the CredentialStore where you want to add the new item.
Default is always personal but can be
changed to shared, or even shared with custom path.
```yaml ```yaml
Type: SwitchParameter Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -119,23 +114,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
\`\`\` - File Name : New-CredentialStoreItem.ps1
File Name : New-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,46 +1,56 @@
---
Module Name: PSCredentialStore
Module Guid: 6800e192-9df8-4e30-b253-eb2c799bbe84
Download Help Link: {{Please enter FwLink manually}}
Help Version: {{Please enter version of help manually (X.X.X.X) format}}
Locale: en-US
---
# PSCredentialStore Module # PSCredentialStore Module
## Description ## Description
{{Manually Enter Description Here}} [about_PSCredentialStore](about_PSCredentialStore.md)
## PSCredentialStore Cmdlets ## PSCredentialStore Cmdlets
### [Connect-To](Connect-To.md) ### [Connect-To](Connect-To.md)
{{Manually Enter Connect-To Description Here}} Connects to the given host using the stored CredentialStoreItem.
### [Disconnect-From](Disconnect-From.md) ### [Disconnect-From](Disconnect-From.md)
{{Manually Enter Disconnect-From Description Here}} Terminates a session established with Connect-To using a CredentialStoreItem.
### [Get-CredentialStore](Get-CredentialStore.md) ### [Get-CredentialStore](Get-CredentialStore.md)
{{Manually Enter Get-CredentialStore Description Here}} Reads the complete content of the credential store and returns it as a new object.
### [Get-CredentialStoreItem](Get-CredentialStoreItem.md) ### [Get-CredentialStoreItem](Get-CredentialStoreItem.md)
{{Manually Enter Get-CredentialStoreItem Description Here}} Returns the Credential from a given remote host item.
### [New-CredentialStore](New-CredentialStore.md) ### [Get-CSCertificate](Get-CSCertificate.md)
{{Manually Enter New-CredentialStore Description Here}} Returns the current used valid PfX certificate.
### [Import-CSCertificate](Import-CSCertificate.md)
Imports a linked certificate to the valid store location.
### [Import-CSCertificate](Import-CSCertificate.md)
Imports a linked certificate to the valid store location.
### [New-CredentialStoreItem](New-CredentialStoreItem.md) ### [New-CredentialStoreItem](New-CredentialStoreItem.md)
{{Manually Enter New-CredentialStoreItem Description Here}} Adds a credential store item containing host, user and password to the given store.
### [New-CSCertAttribute](New-CSCertAttribute.md)
Creates required data for a certificate signing request.
### [New-CSCertificate](New-CSCertificate.md)
Creates a new PFX certificate for the CredentialStore encryption.
### [Remove-CredentialStoreItem](Remove-CredentialStoreItem.md) ### [Remove-CredentialStoreItem](Remove-CredentialStoreItem.md)
{{Manually Enter Remove-CredentialStoreItem Description Here}} Remove the given credentials from the credential store.
### [Set-CredentialStoreItem](Set-CredentialStoreItem.md) ### [Set-CredentialStoreItem](Set-CredentialStoreItem.md)
{{Manually Enter Set-CredentialStoreItem Description Here}} Changes the credentials for the given remote host in the store.
### [Test-CredentialStore](Test-CredentialStore.md) ### [Test-CredentialStore](Test-CredentialStore.md)
{{Manually Enter Test-CredentialStore Description Here}} Returns the credential store state.
### [Test-CredentialStoreItem](Test-CredentialStoreItem.md) ### [Test-CredentialStoreItem](Test-CredentialStoreItem.md)
{{Manually Enter Test-CredentialStoreItem Description Here}} Checks if the given RemoteHost identifier combination exists in the credential store.
### [Test-CSCertificate](Test-CSCertificate.md)
Tests if the linked certificate is store ein the specified cert stores.
### [Test-CSConnection](Test-CSConnection.md) ### [Test-CSConnection](Test-CSConnection.md)
{{Manually Enter Test-CSConnection Description Here}} Returns the connection state of a given type to the remote host.
### [Use-CSCertificate](Use-CSCertificate.md)
Links an existing PFX Certificate to a CredentialStore.

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Remove-CredentialStoreItem # Remove-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
@ -19,7 +12,7 @@ Remove-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [<CommonP
### Shared ### Shared
``` ```
Remove-CredentialStoreItem [-Path <String>] -RemoteHost <String> [-Identifier <String>] [-Shared] Remove-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Shared] [-Path <String>]
[<CommonParameters>] [<CommonParameters>]
``` ```
@ -28,12 +21,25 @@ Use this CMDLet to completely remove an credential store item.
## EXAMPLES ## EXAMPLES
### EXAMPLE 1 ### BEISPIEL 1
``` ```
Remove-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" Remove-CredentialStoreItem -RemoteHost "esx01.myside.local"
``` ```
Remove-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc ### BEISPIEL 2
```
Remove-CredentialStoreItem -Shared -RemoteHost "esx01.myside.local"
```
### BEISPIEL 3
```
Remove-CredentialStoreItem -Shared -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
```
### BEISPIEL 4
```
Remove-CredentialStoreItem -RemoteHost "esx01.myside.local" -Identifier svc
```
## PARAMETERS ## PARAMETERS
@ -64,7 +70,7 @@ Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -94,7 +100,7 @@ Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -102,23 +108,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
\`\`\` - File Name : Remove-CredentialStoreItem.ps1
File Name : Remove-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Set-CredentialStoreItem # Set-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
@ -14,29 +7,48 @@ Changes the credentials for the given remote host in the store.
### Private (Default) ### Private (Default)
``` ```
Set-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [<CommonParameters>] Set-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential <PSCredential>]
[<CommonParameters>]
``` ```
### Shared ### Shared
``` ```
Set-CredentialStoreItem [-Path <String>] -RemoteHost <String> [-Identifier <String>] [-Shared] Set-CredentialStoreItem -RemoteHost <String> [-Identifier <String>] [-Credential <PSCredential>] [-Shared]
[<CommonParameters>] [-Path <String>] [<CommonParameters>]
``` ```
## DESCRIPTION ## DESCRIPTION
{{Fill in the Description}} Use this function to update your already stored RemoteHost items.
## EXAMPLES ## EXAMPLES
### EXAMPLE 1 ### BEISPIEL 1
``` ```
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
``` ```
### BEISPIEL 2
```
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc
```
## PARAMETERS ## PARAMETERS
### -Credential
Provided the new credentials you want to update inside the RemoteHost item.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```
### -Identifier ### -Identifier
Defaults to "". Defaults to "".
Specify a string, which separates two CredentialStoreItems for the Specify a string, which separates two CredentialStoreItems for the
@ -64,7 +76,7 @@ Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -94,7 +106,7 @@ Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -102,23 +114,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
\`\`\` - File Name : Set-CredentialStoreItem.ps1
File Name : Set-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -0,0 +1,56 @@
# Test-CSCertificate
## SYNOPSIS
Tests if the linked certificate is store ein the specified cert stores.
## SYNTAX
```
Test-CSCertificate [-Type] <String> [<CommonParameters>]
```
## DESCRIPTION
Test-CSCertificate should be an easy high level test for the linked certificate.
## EXAMPLES
### BEISPIEL 1
```
Test-CSCertificate -Type 'Shared'
```
## PARAMETERS
### -Type
Select between 'Private' or 'Shared'.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [bool]
## NOTES
- File Name : Test-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Test-CSConnection # Test-CSConnection
## SYNOPSIS ## SYNOPSIS
@ -21,9 +14,9 @@ Use this script to check a connection which was established with the \`Connect-T
## EXAMPLES ## EXAMPLES
### EXAMPLE 1 ### BEISPIEL 1
``` ```
.\Test-CMConnection -RemoteHost "r0-i01-vcr01.p0r.kivbf-cloud.net" -Type VMware Test-CMConnection -RemoteHost "vcr01.internal.net" -Type VMware
``` ```
## PARAMETERS ## PARAMETERS
@ -61,21 +54,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [Boolean] ### [bool]
## NOTES ## NOTES
File Name : Test-CSConnection.ps1 - File Name : Test-CSConnection.ps1
Author : Marco Blessing - marco.blessing@googlemail.com - Author : Marco Blessing - marco.blessing@googlemail.com
Requires : - Requires :
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Test-CredentialStore # Test-CredentialStore
## SYNOPSIS ## SYNOPSIS
@ -29,12 +22,10 @@ the file exists.
## EXAMPLES ## EXAMPLES
### Example 1 ### BEISPIEL 1
```powershell ```
PS C:\> {{ Add example code here }} Test-CredentialStore -eq $true
``` ```
{{ Add example description here }}
## PARAMETERS ## PARAMETERS
@ -48,7 +39,7 @@ Aliases:
Required: False Required: False
Position: Named Position: Named
Default value: "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData Default value: None
Accept pipeline input: False Accept pipeline input: False
Accept wildcard characters: False Accept wildcard characters: False
``` ```
@ -63,7 +54,7 @@ Type: SwitchParameter
Parameter Sets: Shared Parameter Sets: Shared
Aliases: Aliases:
Required: False Required: True
Position: Named Position: Named
Default value: False Default value: False
Accept pipeline input: False Accept pipeline input: False
@ -71,19 +62,16 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
## OUTPUTS ## OUTPUTS
## NOTES ## NOTES
\`\`\` - File Name : Test-CredentialStore.ps1
File Name : Test-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

View File

@ -1,10 +1,3 @@
---
external help file: PSCredentialStore-help.xml
Module Name: PSCredentialStore
online version: https://github.com/OCram85/PSCredentialStore
schema: 2.0.0
---
# Test-CredentialStoreItem # Test-CredentialStoreItem
## SYNOPSIS ## SYNOPSIS
@ -30,7 +23,7 @@ you try to interact with it.
## EXAMPLES ## EXAMPLES
### EXAMPLE 1 ### BEISPIEL 1
``` ```
If (Test-CredentialStoreItem -RemoteHost "Default") { If (Test-CredentialStoreItem -RemoteHost "Default") {
``` ```
@ -110,23 +103,18 @@ Accept wildcard characters: False
``` ```
### CommonParameters ### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS ## INPUTS
### [None] ### [None]
## OUTPUTS ## OUTPUTS
### [None] ### [None]
## NOTES ## NOTES
\`\`\` - File Name : Test-CredentialStoreItem.ps1
File Name : Test-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
\`\`\`
## RELATED LINKS ## RELATED LINKS

107
docs/Use-CSCertificate.md Normal file
View File

@ -0,0 +1,107 @@
# Use-CSCertificate
## SYNOPSIS
Links an existing PFX Certificate to a CredentialStore.
## SYNTAX
### Private (Default)
```
Use-CSCertificate -Path <String> [-UseCertStore] [<CommonParameters>]
```
### Shared
```
Use-CSCertificate -Path <String> [-CredentialStore <String>] [-Shared] [-UseCertStore] [<CommonParameters>]
```
## DESCRIPTION
Linking a certificate is needed if you plan to use the same CredentialStore in cross platform scenarios.
## EXAMPLES
### BEISPIEL 1
```
Use-CSCertificate -Path 'C:\cert.pfx'
```
## PARAMETERS
### -CredentialStore
Specify a custom path for a shared credential store.
```yaml
Type: String
Parameter Sets: Shared
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path
Specify the path to the PFX Certificate you want to link for usage.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Shared
Use the credential store in shared mode.
```yaml
Type: SwitchParameter
Parameter Sets: Shared
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -UseCertStore
Use the given certificate and import it into the corresponding certificate store.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### [None]
## OUTPUTS
### [None]
## NOTES
File Name : Use-CSCertificate.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
## RELATED LINKS
[https://github.com/OCram85/PSCredentialStore](https://github.com/OCram85/PSCredentialStore)

View File

@ -1,4 +1,4 @@
# PSCredentialStore # PSCredentialStore
## about_PSCredentialStore ## about_PSCredentialStore
@ -7,24 +7,30 @@ PSCredentialStore enables managing multiple PSCredential objects.
# LONG DESCRIPTION # LONG DESCRIPTION
The PSCredentialStore is an simple credential manager for PSCredentials. It stores multiple credential objects in a The PSCredentialStore is a simple credential manager for `PSCredential` objects. It stores PSCredentials in a simple json
simple json file. You can choose between a private and shared store. The private one exists in your profile and can file. You can choose between a private and shared credential store. The private one exists in your profile and can
ony accessed by your account on the same machine. The shared store enables you to use different credentials for your ony accessed by your account on the same machine. The shared store enables you to use different credentials for your
script without exposing them as plain text. scripts without exposing them as plain text.
**The shared store isn't 100% secure and I don't recommend using it in production!**
PSCredentialStore was developed to simplify the delegation of complex powershell scripts. In this case you often PSCredentialStore was developed to simplify the delegation of complex powershell scripts. In this case you often
need to store credentials for non interactive usage like in scheduled tasks. need to store credentials for non interactive usage like in scheduled tasks.
To get started read the [about_PSCredentialStore](/src/en-US/about_PSCredential.help.txt) page. Starting with version `1.0.0` PSCredential uses Pfx certificates fo encryption. You can use Pfx certificate files
or certificates stored in the certificate store.
For more details read the [about_PSCredentialStore](/docs/about_PSCredentialStore.md) page on github or via CLI with
`Get-Help about_PSCredentialStore`.
## Requirements
- PowerShell >= `5.1`
- .NET Framework >= `4.6` or .NET Core >= `1.0`
## Installation ## Installation
## PowerShellGallery.com (Recommended Way) ## PowerShellGallery.com (Recommended Way)
* Make sure you use PowerShell 4.0 or higher with `$PSVersionTable`. * Make sure you use PowerShell 5.1 or higher with `$PSVersionTable`.
* Use the builtin PackageManagement and install with: `Install-Module PSCredentialStore` * Use the builtin PackageManagement and install with: `Install-Module PSCredentialStore`
* Done. Start exploring the Module with `Import-Module PSCredentialStore ; Get-Command -Module PSCredentialStore` * Done. Start exploring the Module with `Import-Module PSCredentialStore ; Get-Command -Module PSCredentialStore`
@ -36,19 +42,28 @@ To get started read the [about_PSCredentialStore](/src/en-US/about_PSCredential.
* Don't forget to change the NTFS permission flag in the context menu. * Don't forget to change the NTFS permission flag in the context menu.
* Start with `Import-Module PSCredentialStore` * Start with `Import-Module PSCredentialStore`
**1.** First we need a blank CredentialStore. You can decide between a *private* or *shared* store. The private **1.** First we need a blank credential store. You can decide between a *private* or *shared* store. The private
Credential Store can only be accessed with your profile on the machine you created it. Credential Store can only be accessed with your profile on the machine you created it.
Starting with version `1.0.0` you can decide the storage type of your fresh created certificate. As default
PSCredentialStore creates a new pfx certificate file beside the credential store itself. Optionally you can provide
the parameter `-UseCertStore`. This imports the new certificate in the user or machine certificate store as well.
```powershell ```powershell
# Private Credential Store # Private credential store
New-CredentialStore New-CredentialStore
# Shared Credential Store # Private credential store with certificate store usage
New-CredentialStore -UseCertStore
# Shared credential rtore
New-CredentialStore -Shared New-CredentialStore -Shared
#Shared CredentialStore in custom Location #Shared credential store in custom Location
New-CredentialStore -Shared -Path 'C:\CredentialStore.json' New-CredentialStore -Shared -Path 'C:\CredentialStore.json'
``` ```
**2.** Now you can manage your CredentialStoreItems: **2.** Now you can manage your CredentialStoreItems:
```powershell ```powershell
# This will prompt for credentials and stores it in a private store # This will prompt for credentials and stores it in a private store

View File

@ -1,3 +1,3 @@
{ {
"Version": "1.2.0", "Version": "2.0.0",
"Creation": "2016-06-14 08:41:10" "Creation": "2016-06-14 08:41:10"

View File

@ -1 +0,0 @@
!<21><><EFBFBD>p<EFBFBD><07><>H4<48><34><EFBFBD>"=w<><77>S<EFBFBD>2

Binary file not shown.

BIN
resources/cs/PSCredentialStore.pfx (Stored with Git LFS) Normal file

Binary file not shown.

View File

@ -0,0 +1,74 @@
function Get-CSCertificate {
<#
.SYNOPSIS
Returns the current used valid PfX certificate.
.DESCRIPTION
Use this function to get the available pfx certificate respecting the config hierarchy.
.PARAMETER Type
Select the current credential store type.
.PARAMETER Thumbprint
Provide the credentials thumbprint for the search.
.INPUTS
[None]
.OUTPUTS
[System.Security.Cryptography.X509Certificates.X509Certificate2]
.EXAMPLE
Get-CSCertificate -Type 'Shared' -Thumbprint '12334456'
.NOTES
- File Name : Get-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidateSet('Private', 'Shared')]
[string]$Type,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Thumbprint
)
begin {
}
process {
if ($Type -eq 'Private') {
Get-CSPfXCertificate -Thumbprint $Thumbprint -StoreName 'My' -StoreLocation 'CurrentUser'
}
elseif ($Type -eq 'Shared') {
if ( $isLinux) {
$cert = Get-CSPfxCertificate -Thumbprint $Thumbprint -StoreName 'My' -StoreLocation 'CurrentUser'
if ($null -eq $cert) {
Get-CSPfxCertificate -Thumbprint $Thumbprint -StoreName 'Root' -StoreLocation 'LocalMachine'
}
else {
Write-Output $cert
}
}
elseif ( (! $isLinux) -or ($isWindows) ) {
$cert = Get-CSPfxCertificate -Thumbprint $Thumbprint -StoreName 'My' -StoreLocation 'LocalMachine'
if ($null -eq $cert) {
Get-CSPfxCertificate -Thumbprint $Thumbprint -StoreName 'Root' -StoreLocation 'LocalMachine'
}
else {
Write-Output $cert
}
}
}
}
end {
}
}

View File

@ -0,0 +1,72 @@
function Import-CSCertificate {
<#
.SYNOPSIS
Imports a linked certificate to the valid store location.
.DESCRIPTION
Import-CSCertificate takes a pfx certificate file and imports it to the supposed certificate store for
private and shared credential stores.
.PARAMETER Type
Select between the a private and shared credential store.
.PARAMETER Path
Provide a valid path to pfx certificate file.
.INPUTS
[None]
.OUTPUTS
[None]
.EXAMPLE
Import-CSCertificate -Type 'Private' -Path (Join-Path -Path $Env:APPDATA -ChildItem 'PfxCertificate.pfx')
.NOTES
- File Name : Import-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidateSet('Private', 'Shared')]
[string]$Type,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.IO.FileInfo]$Path
)
begin {
if (! (Test-Path -Path $Path)) {
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.Exception]::new(
('File {0} not found!') -f $Path
)
}
Write-Error @ErrorParams
}
}
process {
# Import to CurrentUser\My store for windows and linux
if ($Type -eq 'Private') {
Import-CSPfxCertificate -Path $Path -StoreName 'My' -StoreLocation 'CurrentUser' -OpenFlags 'ReadWrite'
}
elseif ( (! $isLinux ) -and ($Type -eq 'Shared') ) {
Import-CSPfxCertificate -Path $Path -StoreName 'My' -StoreLocation 'LocalMachine' -OpenFlags 'ReadWrite'
}
elseif ( ($isLinux) -and ($Type -eq 'Shared') ) {
Import-CSPfxCertificate -Path $Path -StoreName 'My' -StoreLocation 'CurrentUser' -OpenFlags 'ReadWrite'
}
}
end {
}
}

View File

@ -0,0 +1,99 @@
function New-CSCertAttribute {
<#
.SYNOPSIS
Creates required data for a certificate signing request.
.DESCRIPTION
Defines the certificate related properties for an upcoming New-PfxCertificate execution.
.PARAMETER Country
County code like EN, DE, IT, FR...
.PARAMETER State
Certificate state value.
.PARAMETER City
Certificate city value.
.PARAMETER Organization
Certificate organization value.
.PARAMETER OrganizationalUnitName
Certificate OrganizationalUnitName value.
.PARAMETER CommonName
The certificate common name.
.PARAMETER Days
The validation time itself.
.INPUTS
[None]
.OUTPUTS
[PSCredentialStore.Certificate.CSRDetails]
.EXAMPLE
New-CSCertAttribute -Country 'DE' -State 'BW' -City 'Karlsruhe' -Organization 'AwesomeIT' -OrganizationalUnitName '' -CommonName 'MyPrivateCert'
.NOTES
- File Name : New-CSCertAttribute.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType('PSCredentialStore.Certificate.Attribute')]
param(
[Parameter(Mandatory = $true)]
[ValidateLength(2, 2)]
[ValidateNotNull()]
[string]$Country,
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[string]$State,
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[string]$City,
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[string]$Organization,
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[string]$OrganizationalUnitName,
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[string]$CommonName,
[Parameter(Mandatory = $false)]
[ValidateNotNull()]
[int]$Days = 365
)
begin {
}
process {
return [PSCustomObject]@{
PSTypeName = 'PSCredentialStore.Certificate.Attribute'
Subject = [PSCustomObject]@{
PSTypeName = 'PSCredentialStore.Certificate.Attribute.Subject'
Country = $Country
State = $State
City = $City
Organization = $Organization
OrganizationalUnitName = $OrganizationalUnitName
CommonName = $CommonName
}
Days = $Days
}
}
end {
}
}

View File

@ -0,0 +1,142 @@
function New-CSCertificate {
<#
.SYNOPSIS
Creates a new PFX certificate for the CredentialStore encryption.
.DESCRIPTION
Use this function to create a custom self signed certificate used by the PSCredentialStore module.
.PARAMETER CRTAttribute
Provide certificate related attributes provided by function New-CRTAttribute.
.PARAMETER KeyName
Provide a custom full path and name for the private key. The file extension has to be `*.key`.
.PARAMETER CertName
Provide a custom full path and name for the PFX certificate file. The file extension has to be `*.pfx`
.INPUTS
[PSCredentialStore.Certificate.Attribute]
.OUTPUTS
[None]
.EXAMPLE
New-CSCertificate -CRTAttribute $CRTAttribute -KeyName './myprivate.key' -CertName './mycert.pfx'
.NOTES
- File Name : New-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding(SupportsShouldProcess = $true)]
[OutputType()]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[PSTypeName('PSCredentialStore.Certificate.Attribute')]$CRTAttribute,
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]$KeyName = './private.key',
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]$CertName = './certificate.pfx'
)
begin {
$ModuleBase = Get-ModuleBase
if ($isLinux -or $isMacOS) {
try {
$openssl = Get-Command -Name 'openssl' -ErrorAction Stop
}
catch {
$_.Exception.Message | Write-Error
$ErrorParams = @{
Message = 'Can not find the openssl binary!'
ErrorAction = 'Stop'
Exception = [System.IO.FileNotFoundException]::new()
}
Write-Error @ErrorParams
}
}
elseif (($PSVersionTable.PSEdition -eq 'Desktop' -and $PSVersionTable.PSVersion.Major -lt 6) -or ($IsWindows -eq $true)) {
$openssl = Join-Path -Path $ModuleBase -ChildPath '/Vendor/libressl255/openssl.exe'
}
$Env:OPENSSL_CONF = Join-Path $ModuleBase -ChildPath '/openssl.conf'
}
process {
$SubjPattern = "/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}"
$SubjValues = @(
$CRTAttribute.Subject.Country,
$CRTAttribute.Subject.State,
$CRTAttribute.Subject.City,
$CRTAttribute.Subject.Organization,
$CRTAttribute.Subject.OrganizationalUnitName,
$CRTAttribute.Subject.CommonName
)
$Subj = $SubjPattern -f $SubjValues
$PEMCertName = $CertName -replace '.pfx', '.crt'
$ExpPattern = '& ''{0}'' req -x509 -sha256 -nodes -days {1} -newkey rsa:2048 -keyout {2} -out {3} -subj "{4}" *>$null'
$ExpValues = @(
$openssl,
$CRTAttribute.Days
$KeyName,
$PEMCertName,
$Subj
)
$PEMExp = $ExpPattern -f $ExpValues
Write-Verbose -Message ( 'Expr string is: {0}' -f $PEMExp)
# Edit the Error action for the openSLL command to make the redirect *>$null work.
# There is always a stderr and stdout stream!
$EAP = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
Invoke-Expression -Command $PEMExp
$ErrorActionPreference = $EAP
# manually testing the openssl command results
if (! (Test-Path -Path $KeyName)) {
$ErrorParams = @{
Message = 'Could not create the private key ${0}' -f $KeyName
ErrorAction = 'Stop'
Exception = [System.UnauthorizedAccessException]::new()
}
Write-Error @ErrorParams
}
if (! (Test-Path -Path $PEMCertName)) {
$ErrorParams = @{
Message = 'Could not create the PEM certificate ${0}' -f $PEMCertName
ErrorAction = 'Stop'
Exception = [System.Exception]::new()
}
Write-Error @ErrorParams
}
$PfxPattern = '& ''{0}'' pkcs12 -export -out {1} -inkey {2} -in {3} -passout pass:'
$PfxValues = @(
$openssl,
$CertName,
$KeyName,
($CertName -replace '.pfx', '.crt')
)
$PfxExp = $PfxPattern -f $PfxValues
Write-Verbose -Message ( 'PfxExp string is: {0}' -f $PfxExp)
Invoke-Expression -Command $PfxExp
# Remove private key and crt file. Always ask user
Remove-Item -Path $KeyName
Remove-Item -Path ($CertName -replace '.pfx', '.crt')
}
end {
Remove-Item Env:\OPENSSL_CONF -Confirm:$False -Force -ErrorAction SilentlyContinue
}
}

View File

@ -0,0 +1,76 @@
function Test-CSCertificate {
<#
.SYNOPSIS
Tests if the linked certificate is store ein the specified cert stores.
.DESCRIPTION
Test-CSCertificate should be an easy high level test for the linked certificate.
.PARAMETER Type
Select between 'Private' or 'Shared'.
.INPUTS
[None]
.OUTPUTS
[bool]
.EXAMPLE
Test-CSCertificate -Type 'Shared'
.NOTES
- File Name : Test-CSCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidateSet('Private', 'Shared')]
[string]$Type
)
begin {
if ($Type -eq 'Private') {
$CS = Get-CredentialStore
}
elseif ($Type -eq 'Shared') {
$CS = Get-CredentialStore -Shared
}
if ($null -ne $CS.PfxCertificate) {
Write-Warning 'There is a Pfx certificate file linked in the store. Certificates saved in the Cert store will be ignored!'
}
}
process {
if ($Type -eq 'Private') {
$cert = Get-CSPfXCertificate -Thumbprint $CS.Thumbprint -StoreName 'My' -StoreLocation 'CurrentUser'
}
elseif ($Type -eq 'Shared') {
if ( $isLinux) {
$cert = Get-CSPfxCertificate -Thumbprint $CS.Thumbprint -StoreName 'My' -StoreLocation 'CurrentUser'
if ($null -eq $cert) {
$cert = Get-CSPfxCertificate -Thumbprint $CS.Thumbprint -StoreName 'Root' -StoreLocation 'LocalMachine'
}
}
elseif ( (! $isLinux) -or ($isWindows) ) {
$cert = Get-CSPfxCertificate -Thumbprint $CS.Thumbprint -StoreName 'My' -StoreLocation 'LocalMachine'
if ($null -eq $cert) {
$cert = Get-CSPfxCertificate -Thumbprint $CS.Thumbprint -StoreName 'Root' -StoreLocation 'LocalMachine'
}
}
}
if ($null -eq $cert) {
return $false
}
else {
return $true
}
}
end {
}
}

View File

@ -0,0 +1,121 @@
function Use-CSCertificate {
<#
.SYNOPSIS
Links an existing PFX Certificate to a CredentialStore.
.DESCRIPTION
Linking a certificate is needed if you plan to use the same CredentialStore in cross platform scenarios.
.PARAMETER Path
Specify the path to the PFX Certificate you want to link for usage.
.PARAMETER CredentialStore
Specify a custom path for a shared credential store.
.PARAMETER Shared
Use the credential store in shared mode.
.PARAMETER UseCertStore
Use the given certificate and import it into the corresponding certificate store.
.INPUTS
[None]
.OUTPUTS
[None]
.EXAMPLE
Use-CSCertificate -Path 'C:\cert.pfx'
.NOTES
File Name : Use-CSCertificate.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding(DefaultParameterSetName = "Private")]
[OutputType()]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
param(
[Parameter(Mandatory = $true, ParameterSetName = "Private")]
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[ValidateNotNullOrEmpty()]
[string]$Path,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[ValidateNotNullOrEmpty()]
[string]$CredentialStore,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Switch]$UseCertStore
)
begin { }
process {
try {
# We need to resolve the path to make sure it has the correct platform specific syntax.
# And it should also exist.
$validPath = Resolve-Path -Path $Path -ErrorAction Stop
$PfxCertificate = Get-PfxCertificate -FilePath $validPath -ErrorAction Stop
}
catch {
$_.Exception.Error | Write-Error
$ErrorParams = @{
Message = 'The given PFX certificate does not exist!'
ErrorAction = 'Stop'
}
Write-Error @ErrorParams
}
try {
if ($PSCmdlet.ParameterSetName -eq "Private") {
$StorePath = Get-DefaultCredentialStorePath
$CS = Get-CredentialStore
}
elseif ($PSCmdlet.ParameterSetName -eq "Shared" ) {
if (!($PSBoundParameters.ContainsKey('CredentialStore'))) {
$StorePath = Get-DefaultCredentialStorePath -Shared
$CS = Get-CredentialStore -Shared
}
else {
$StorePath = $CredentialStore
$CS = Get-CredentialStore -Shared -Path $CredentialStore
}
}
}
catch {
$_.Exception.Error | Write-Error
$ErrorParams = @{
Message = 'The given CredentialStore does not exist!'
ErrorAction = 'Stop'
}
Write-Error @ErrorParams
}
# Lets first check if the thumbprint matches
if (($CS.Thumbprint -notmatch $PfxCertificate.Thumbprint) -and ($CS.Thumbprint.Length -ne 0)) {
Write-Warning @"
You are trying to map an unknown certificate.
Make sure you used the same AES keys for encrypting!
"@
}
if ($UseCertStore) {
Import-CSCertificate -Type $PSCmdlet.ParameterSetName -Path $Path
$CS.Thumbprint = $PfxCertificate.Thumbprint
$CS.PfxCertificate = $null
}
else {
$CS.PfxCertificate = $validPath.Path
}
$CS | ConvertTo-Json -Depth 5 | Out-File -FilePath $StorePath -Force -Encoding utf8
}
end { }
}

View File

@ -1,45 +0,0 @@
function Get-ChallengeFile {
<#
.SYNOPSIS
Reads the challenge file as binary content.
.DESCRIPTION
Use this function to tread a challenge file. Returns a [Byte[]] Array.
.PARAMETER Path
Specify a file to read.
.INPUTS
[None]
.OUTPUTS
[Byte[]]
.EXAMPLE
.\Get-RandomKey -Path "C:\TMP\Challenge.bin"
.NOTES
```
File Name : Get-ChallengeFile.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
```
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string]$Path = "{0}\PSCredentialStore\Challenge.bin" -f $env:ProgramData
)
if (Test-Path $Path) {
try {
[io.file]::ReadAllBytes($Path)
}
catch {
Write-Error ("Could not read file {0}." -f $Path) -ErrorAction Stop
}
}
}

View File

@ -1,72 +0,0 @@
Function Set-ChallengeFile() {
<#
.SYNOPSIS
Writes the given key into the challenge file
.DESCRIPTION
You can use the file content for ConvertTo-SecureString operations.
.PARAMETER Path
The file you wish to create.
.PARAMETER KeySize
Specify the key size for the encryption key.
.PARAMETER Force
Use this switch to override an older file version.
.INPUTS
[None]
.OUTPUTS
[None]
.EXAMPLE
.\Set-ChallengeFile -Path "C:\TMP\myfile.json" -Force
.NOTES
File Name : Set-ChallengeFile.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string]$Path = "{0}\PSCredentialStore\Challenge.bin" -f $env:ProgramData,
[Parameter(Mandatory = $false)]
[ValidateSet(16, 24, 32)]
[string]$KeySize = "24",
[switch]$Force
)
if ((Test-Path -Path $Path)) {
if ($Force -eq $true) {
Remove-Item -Path $Path -Confirm:$false -Force
}
else {
Write-Error "The given file already exists!. Use the -Force switch to override it." -ErrorAction Stop
}
}
$PSCredentialStoreDataDir = Split-Path -Path $Path -Parent
if (-not (Test-Path $PSCredentialStoreDataDir)) {
try {
New-Item -ItemType Directory -Path $PSCredentialStoreDataDir
}
catch {
Write-Error ("Could not create the parent data dir {0}" -f $PSCredentialDataDir) -ErrorAction Stop
}
}
try {
$Keys = Get-RandomKey -Size $KeySize
[io.file]::WriteAllBytes($Path, $Keys)
}
catch {
$_.Exception | Format-List -Force | Out-String | Write-Error -ErrorAction Stop
}
}

View File

@ -1,48 +0,0 @@
function Test-ChallengeFile {
<#
.SYNOPSIS
Simple path check for challenge file needed by the CredentialStores.
.DESCRIPTION
This is supposed to be a internal function to check the existence for a challenge file.
.PARAMETER Path
Specify the path to the challenge file.
.INPUTS
[None]
.OUTPUTS
[Bool].
.EXAMPLE
If (Test-ChallengeFile) {
Write-Host "The file exists."
}
Else {
Write-Warning "Couldn't find the given file!"
}
.NOTES
File Name : Test-ChallengeFile.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[String]$Path = "{0}\PSCredentialStore\Challenge.bin" -f $env:ProgramData
)
if (Test-Path $Path) {
$true
}
else {
$false
}
}

View File

@ -29,6 +29,9 @@ function Connect-To {
Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which
can be decrypted across systems. can be decrypted across systems.
.PARAMETER PassThru
Returns the value from the underlying connection type function.
.INPUTS .INPUTS
[None] [None]
@ -57,9 +60,9 @@ function Connect-To {
Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS Connect-To -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
.NOTES .NOTES
File Name : Connect-To.ps1 - File Name : Connect-To.ps1
Author : Marco Blessing - marco.blessing@googlemail.com - Author : Marco Blessing - marco.blessing@googlemail.com
Requires : - Requires :
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -93,15 +96,30 @@ function Connect-To {
[Parameter(Mandatory = $False, ParameterSetName = "Private")] [Parameter(Mandatory = $False, ParameterSetName = "Private")]
[PSCredential]$Credentials, [PSCredential]$Credentials,
[Parameter(Mandatory = $true, ParameterSetNAme = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $False, ParameterSetName = "Shared")] [Parameter(Mandatory = $False, ParameterSetName = "Shared")]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData, [string]$Path,
[Parameter(Mandatory = $false, ParameterSetNAme = "Shared")] [Parameter(Mandatory = $False, ParameterSetName = "Private")]
[switch]$Shared [Parameter(Mandatory = $False, ParameterSetName = "Shared")]
[switch]$PassThru
) )
begin { begin {
# Set the CredentialStore for private, shared or custom mode.
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
}
elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
# First check the optional modules # First check the optional modules
if (-not (Resolve-Dependency -Name $Type)) { if (-not (Resolve-Dependency -Name $Type)) {
Write-Error -Message ("Could not resolve the optional dependencies defined for {0}" -f $Type) -ErrorAction 'Stop' Write-Error -Message ("Could not resolve the optional dependencies defined for {0}" -f $Type) -ErrorAction 'Stop'
@ -118,10 +136,6 @@ function Connect-To {
} }
process { process {
# Set the correct CredentialStore Path depending on the used ParameterSetName
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = "{0}\CredentialStore.json" -f $env:APPDATA
}
if (-not ($Credentials)) { if (-not ($Credentials)) {
# Load the credential from the CredentialStore. If the credential doesn't exist, we need to # Load the credential from the CredentialStore. If the credential doesn't exist, we need to
# return 1, so a calling if statement can handle the failure detection. # return 1, so a calling if statement can handle the failure detection.
@ -131,16 +145,16 @@ function Connect-To {
try { try {
if ($Identifier -ne "") { if ($Identifier -ne "") {
$RemoteHostIdentifier = "{0}/{1}" -f $Identifier, $RemoteHost $RemoteHostIdentifier = "{0}/{1}" -f $Identifier, $RemoteHost
$creds = Get-CredentialStoreItem -RemoteHost $RemoteHostIdentifier -Path $Path $creds = Get-CredentialStoreItem -Shared -RemoteHost $RemoteHostIdentifier -Path $Path
} }
else { else {
$creds = Get-CredentialStoreItem -RemoteHost $RemoteHost -Path $Path $creds = Get-CredentialStoreItem -Shared -RemoteHost $RemoteHost -Path $Path
} }
} }
catch { catch {
$MessageParams = @{ $MessageParams = @{
Message = "Unable to look up credential store item for RemoteHost {0}/Identifier {1}!" -f $RemoteHost, $Identifier Message = "Unable to look up credential store item for RemoteHost {0}/Identifier {1}!" -f $RemoteHost, $Identifier
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -152,7 +166,7 @@ function Connect-To {
if ($creds.UserName -eq "" -or $creds.Password.GetType().Name -ne "SecureString") { if ($creds.UserName -eq "" -or $creds.Password.GetType().Name -ne "SecureString") {
$MessageParams = @{ $MessageParams = @{
Message = "Please provide valid credentials for RemoteHost {0}!" -f $RemoteHost Message = "Please provide valid credentials for RemoteHost {0}!" -f $RemoteHost
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -167,7 +181,7 @@ function Connect-To {
catch { catch {
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -177,12 +191,13 @@ function Connect-To {
# First establish the FTP session # First establish the FTP session
$WinSCPConParams = @{ $WinSCPConParams = @{
Credential = $creds Credential = $creds
Hostname = $RemoteHost Hostname = $RemoteHost
Protocol = 'Ftp' Protocol = 'Ftp'
FtpMode = 'Passive' FtpMode = 'Passive'
} }
try { try {
$Global:WinSCPSession = New-WinSCPSession @WinSCPConParams $FTPSessionOption = New-WinSCPSessionOption @WinSCPConParams
$Global:WinSCPSession = New-WinSCPSession -SessionOption $FTPSessionOption
} }
catch { catch {
throw "Could not connect to {0} using {1} protocol!" -f $RemoteHost, $Type throw "Could not connect to {0} using {1} protocol!" -f $RemoteHost, $Type
@ -191,7 +206,7 @@ function Connect-To {
if (!($WinSCPSession.Opened)) { if (!($WinSCPSession.Opened)) {
# Check the connection state and find out if the session is still open. # Check the connection state and find out if the session is still open.
$MessageParams = @{ $MessageParams = @{
Message = "Connection to {0} using Type {1} was established. But now it seems to be lost!" -f $RemoteHost, $Type Message = "Connection to {0} using Type {1} was established. But now it seems to be lost!" -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -205,7 +220,7 @@ function Connect-To {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -219,7 +234,7 @@ function Connect-To {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -227,13 +242,19 @@ function Connect-To {
} }
"CisServer" { "CisServer" {
try { try {
Connect-CisServer -Server $RemoteHost -Credential $creds -ErrorAction Stop | Out-Null if ($PassThru.IsPresent) {
Connect-CisServer -Server $RemoteHost -Credential $creds -ErrorAction Stop
}
else {
Connect-CisServer -Server $RemoteHost -Credential $creds -ErrorAction Stop | Out-Null
}
} }
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -242,17 +263,17 @@ function Connect-To {
"ExchangeHTTP" { "ExchangeHTTP" {
try { try {
$ConnectionParams = @{ $ConnectionParams = @{
ConnectionURI = "http://{0}/powershell" -f $RemoteHost ConnectionURI = "http://{0}/powershell" -f $RemoteHost
ConfigurationName = 'Microsoft.Exchange' ConfigurationName = 'Microsoft.Exchange'
Credential = $creds Credential = $creds
ErrorAction = 'Stop' ErrorAction = 'Stop'
} }
$Global:PSExchangeRemote = New-PSSession @ConnectionParams $Global:PSExchangeRemote = New-PSSession @ConnectionParams
} }
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -261,17 +282,17 @@ function Connect-To {
"ExchangeHTTPS" { "ExchangeHTTPS" {
try { try {
$ConnectionParams = @{ $ConnectionParams = @{
ConnectionURI = "https://{0}/powershell" -f $RemoteHost ConnectionURI = "https://{0}/powershell" -f $RemoteHost
ConfigurationName = 'Microsoft.Exchange' ConfigurationName = 'Microsoft.Exchange'
Credential = $creds Credential = $creds
ErrorAction = 'Stop' ErrorAction = 'Stop'
} }
$Global:PSExchangeRemote = New-PSSession @ConnectionParams $Global:PSExchangeRemote = New-PSSession @ConnectionParams
} }
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -279,9 +300,9 @@ function Connect-To {
} }
"SCP" { "SCP" {
$WinSCPSessionParams = @{ $WinSCPSessionParams = @{
Credential = $creds Credential = $creds
Hostname = $RemoteHost Hostname = $RemoteHost
Protocol = 'Scp' Protocol = 'Scp'
GiveUpSecurityAndAcceptAnySshHostKey = $True GiveUpSecurityAndAcceptAnySshHostKey = $True
} }
try { try {
@ -292,7 +313,7 @@ function Connect-To {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -301,7 +322,7 @@ function Connect-To {
if (!($WinSCPSession.Opened)) { if (!($WinSCPSession.Opened)) {
# Check the connection state and find out if the session is still open. # Check the connection state and find out if the session is still open.
$MessageParams = @{ $MessageParams = @{
Message = "Connection to {0} using Type {1} was established. But now it seems to be lost!" -f $RemoteHost, $Type Message = "Connection to {0} using Type {1} was established. But now it seems to be lost!" -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -310,7 +331,7 @@ function Connect-To {
default { default {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to connect to {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams

View File

@ -51,9 +51,9 @@ function Disconnect-From {
Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS Disconnect-From -RemoteHost "exchange01.myside.local" -Type ExchangeHTTPS
.NOTES .NOTES
File Name : Disconnect-From.ps1 - File Name : Disconnect-From.ps1
Author : Marco Blessing - marco.blessing@googlemail.com - Author : Marco Blessing - marco.blessing@googlemail.com
Requires : - Requires :
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -95,7 +95,7 @@ function Disconnect-From {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -114,7 +114,7 @@ function Disconnect-From {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -127,7 +127,7 @@ function Disconnect-From {
} }
else { else {
$MessageParams = @{ $MessageParams = @{
Message = "There is no open WinSCP Session" Message = "There is no open WinSCP Session"
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -138,7 +138,7 @@ function Disconnect-From {
"NetAppFAS" { "NetAppFAS" {
try { try {
$MessageParams = @{ $MessageParams = @{
Message = "Setting {0} to `$null, which will disconnect NetAppFAS" -f $Global:CurrentNcController Message = "Setting {0} to `$null, which will disconnect NetAppFAS" -f $Global:CurrentNcController
ErrorAction = "Continue" ErrorAction = "Continue"
} }
Write-Verbose @MessageParams Write-Verbose @MessageParams
@ -148,7 +148,7 @@ function Disconnect-From {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -163,7 +163,7 @@ function Disconnect-From {
catch { catch {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -176,7 +176,7 @@ function Disconnect-From {
} }
catch { catch {
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -188,7 +188,7 @@ function Disconnect-From {
} }
else { else {
$MessageParams = @{ $MessageParams = @{
Message = "There is no open WinSCP Session" Message = "There is no open WinSCP Session"
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
@ -197,7 +197,7 @@ function Disconnect-From {
default { default {
# Write a error message to the log. # Write a error message to the log.
$MessageParams = @{ $MessageParams = @{
Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type Message = "Unable to disconnect from {0} using Type {1}." -f $RemoteHost, $Type
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams

View File

@ -17,22 +17,22 @@ function Test-CSConnection {
[None] [None]
.OUTPUTS .OUTPUTS
[Boolean] [bool]
.EXAMPLE .EXAMPLE
.\Test-CMConnection -RemoteHost "r0-i01-vcr01.p0r.kivbf-cloud.net" -Type VMware Test-CMConnection -RemoteHost "vcr01.internal.net" -Type VMware
.NOTES .NOTES
File Name : Test-CSConnection.ps1 - File Name : Test-CSConnection.ps1
Author : Marco Blessing - marco.blessing@googlemail.com - Author : Marco Blessing - marco.blessing@googlemail.com
Requires : - Requires :
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding()] [CmdletBinding()]
[OutputType([boolean])] [OutputType([bool])]
param( param(
[Parameter(Mandatory = $true)] [Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
@ -77,7 +77,7 @@ function Test-CSConnection {
'CiscoUcs' { 'CiscoUcs' {
$MsgParams = @{ $MsgParams = @{
ErrorAction = "Stop" ErrorAction = "Stop"
Message = "CiscoUCS connection test is not implemented yet!" Message = "CiscoUCS connection test is not implemented yet!"
} }
Write-Error @MsgParams Write-Error @MsgParams
return $false return $false
@ -86,7 +86,7 @@ function Test-CSConnection {
'FTP' { 'FTP' {
$MsgParams = @{ $MsgParams = @{
ErrorAction = "Stop" ErrorAction = "Stop"
Message = "FTP connection test is not implemented yet!" Message = "FTP connection test is not implemented yet!"
} }
Write-Error @MsgParams Write-Error @MsgParams
return $false return $false
@ -95,7 +95,7 @@ function Test-CSConnection {
'NetAppFAS' { 'NetAppFAS' {
$MsgParams = @{ $MsgParams = @{
ErrorAction = "Stop" ErrorAction = "Stop"
Message = "NetAppFAS connection test is not implemented yet!" Message = "NetAppFAS connection test is not implemented yet!"
} }
Write-Error @MsgParams Write-Error @MsgParams
return $false return $false
@ -105,7 +105,7 @@ function Test-CSConnection {
Default { Default {
$MsgParams = @{ $MsgParams = @{
ErrorAction = "Stop" ErrorAction = "Stop"
Message = "Panic: There is an invalid type value! This error should never be thrown." Message = "Panic: There is an invalid type value! This error should never be thrown."
} }
Write-Error @MsgParams Write-Error @MsgParams
return $false return $false

View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<ViewDefinitions>
<View>
<Name>PSCredentialStore.Store</Name>
<ViewSelectedBy>
<TypeName>PSCredentialStore.Store</TypeName>
</ViewSelectedBy>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<PropertyName>Version</PropertyName>
</ListItem>
<ListItem>
<PropertyName>Created</PropertyName>
</ListItem>
<ListItem>
<Label>PfxCertificate</Label>
<ScriptBlock>$_.PfxCertificate | Split-Path -Leaf</ScriptBlock>
</ListItem>
<ListItem>
<PropertyName>Thumbprint</PropertyName>
</ListItem>
<ListItem>
<PropertyName>Type</PropertyName>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
</ViewDefinitions>
</Configuration>

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<ViewDefinitions>
<View>
<Name>PSCredentialStore.Certificate.Attribute</Name>
<ViewSelectedBy>
<TypeName>PSCredentialStore.Certificate.Attribute</TypeName>
</ViewSelectedBy>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<PropertyName>Country</PropertyName>
</ListItem>
<ListItem>
<PropertyName>State</PropertyName>
</ListItem>
<ListItem>
<PropertyName>City</PropertyName>
</ListItem>
<ListItem>
<PropertyName>Organization</PropertyName>
</ListItem>
<ListItem>
<PropertyName>OrganizationalUnitName</PropertyName>
</ListItem>
<ListItem>
<PropertyName>CommonName</PropertyName>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
</ViewDefinitions>
</Configuration>

View File

@ -1,49 +0,0 @@
function Get-RandomKey {
<#
.SYNOPSIS
Returns a random key
.DESCRIPTION
You can use the key for further use with SecureStrings.
.PARAMETER Size
Define the key size. You can choose between 16, 24 and 32
.INPUTS
[None]
.OUTPUTS
Returns a Random key as [Byte[]] array.
.EXAMPLE
.\Get-RandomKey -Size 24
.NOTES
```
File Name : Get-RandomKey.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
```
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateSet(16, 24, 32)]
[string]$size
)
# Init the vars
[Byte[]]$Key = @()
$i = 0
while ($i -ne $size) {
$element = Get-Random -Minimum 0 -Maximum 255
Write-Debug ("The current element is {0}." -f $element)
$Key += $element
$i++
}
$Key
}

View File

@ -31,21 +31,17 @@ function Get-CredentialStoreItem {
$myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" $myCreds = Get-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.NOTES .NOTES
``` - File Name : Get-CredentialStoreItem.ps1
File Name : Get-CredentialStoreItem.ps1 - Author : Messing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
[OutputType([System.Management.Automation.PSCredential])] [OutputType([PSCredential])]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[Parameter(Mandatory = $true, ParameterSetName = "Private")] [Parameter(Mandatory = $true, ParameterSetName = "Private")]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
@ -56,55 +52,77 @@ function Get-CredentialStoreItem {
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$Identifier, [string]$Identifier,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared [ValidateNotNullOrEmpty()]
[string]$Path
) )
# First set a constand path for private CredentialStore mode. begin {
if ($PSCmdlet.ParameterSetName -eq "Private") { # Set the CredentialStore for private, shared or custom mode.
$Path = "{0}\CredentialStore.json" -f $env:APPDATA Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
}
elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
} }
if ($Identifier -ne "") { process {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost if ($Identifier -ne "") {
} $CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
else { }
$CredentialName = $RemoteHost else {
} $CredentialName = $RemoteHost
}
if (Test-CredentialStore -Path $Path) { if (Test-CredentialStore -Shared -Path $Path) {
$CS = Get-CredentialStore -Path $Path $CS = Get-CredentialStore -Shared -Path $Path
$CSMembers = Get-Member -InputObject $CS $CSMembers = Get-Member -InputObject $CS
# Let`s first check if the given remote host exists as object property # Let's first check if the given remote host exists as object property
if (($CSMembers.MemberType -eq "NoteProperty") -and ($CSMembers.Name -eq $CredentialName)) { if (($CSMembers.MemberType -eq "NoteProperty") -and ($CSMembers.Name -contains $CredentialName)) {
if ($CS.Type -eq "Private") { if ($null -eq $CS.PfxCertificate) {
$CSItem = [ordered]@{ $Cert = Get-CSCertificate -Type $CS.Type -Thumbprint $CS.Thumbprint
User = $CS.$CredentialName.User }
Password = ConvertTo-SecureString -String $CS.$CredentialName.Password else {
$Cert = Get-PfxCertificate -FilePath $CS.PfxCertificate -ErrorAction Stop
}
$DecryptedKey = $Cert.PrivateKey.Decrypt(
[Convert]::FromBase64String($CS.$CredentialName.EncryptedKey),
[System.Security.Cryptography.RSAEncryptionPadding]::Pkcs1
)
if (! $ExpandOutput.isPresent) {
[PSCredential]::new(
$CS.$CredentialName.User,
($CS.$CredentialName.Password | ConvertTo-SecureString -Key $DecryptedKey)
)
} }
} }
else { else {
$Key = Get-ChallengeFile $MsgParams = @{
$CSItem = [ordered]@{ ErrorAction = "Stop"
User = $CS.$CredentialName.User Message = "Could not find credentials for the given remote host: {0}" -f $RemoteHost
Password = ConvertTo-SecureString -String $CS.$CredentialName.Password -Key $Key
} }
Write-Error @MsgParams
} }
New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CSItem.User, $CSItem.Password
} }
else { else {
$MsgParams = @{ $MsgParams = @{
ErrorAction = "Stop" ErrorAction = "Stop"
Message = "Could not find credentials for the given remote host: {0}" -f $RemoteHost Message = "The given credential store ({0}) does not exist!" -f $Path
} }
Write-Error @MsgParams Write-Error @MsgParams
} }
} }
else {
$MsgParams = @{ end {
ErrorAction = "Stop"
Message = "The given credential store ({0}) does not exist!" -f $Path
}
Write-Error @MsgParams
} }
} }

View File

@ -21,6 +21,10 @@ function New-CredentialStoreItem {
.PARAMETER Credential .PARAMETER Credential
You can provide credentials optionally as pre existing pscredential object. You can provide credentials optionally as pre existing pscredential object.
.PARAMETER Shared
Define the CredentialStore where you want to add the new item. Default is always personal but can be
changed to shared, or even shared with custom path.
.INPUTS .INPUTS
[None] [None]
@ -31,20 +35,16 @@ function New-CredentialStoreItem {
New-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" New-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.NOTES .NOTES
``` - File Name : New-CredentialStoreItem.ps1
File Name : New-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[Parameter(Mandatory = $true, ParameterSetName = "Private")] [Parameter(Mandatory = $true, ParameterSetName = "Private")]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
@ -55,82 +55,108 @@ function New-CredentialStoreItem {
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$Identifier, [string]$Identifier,
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[pscredential]$Credential, [PSCredential]$Credential,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared [ValidateNotNullOrEmpty()]
[string]$Path
) )
# First set a constand path for private CredentialStore mode. begin {
if ($PSCmdlet.ParameterSetName -eq "Private") { # Set the CredentialStore for private, shared or custom mode.
$Path = "{0}\CredentialStore.json" -f $env:APPDATA Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
} if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
# Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Path $Path)) {
$MessageParams = @{
Message = "Could not add anything into the given CredentailStore."
ErrorAction = "Stop"
} }
Write-Error @MessageParams elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
} if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
# Read the file content based on the given ParameterSetName }
$CSContent = Get-CredentialStore -Path $Path
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
if (-not($Credential)) {
$Credential = Get-Credential -Message $CredentialName
}
if ($Credential.UserName) {
if ($CSContent.Type -eq "Shared") {
$Key = Get-ChallengeFile
$encypted = ConvertFrom-SecureString -SecureString $Credential.Password -Key $Key
} }
else { }
$encypted = ConvertFrom-SecureString -SecureString $Credential.Password
} process {
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) { # Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Shared -Path $Path)) {
$MessageParams = @{ $MessageParams = @{
Message = "The given host already exists. Nothing to do here." Exception = [System.IO.FileNotFoundException]::new(
'Could not add anything into the given CredentialStore.'
)
ErrorAction = "Stop"
} }
Write-Warning @MessageParams Write-Error @MessageParams
}
$CSContent = Get-CredentialStore -Shared -Path $Path
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
} }
else { else {
$CredentialHash = [ordered]@{ $CredentialName = $RemoteHost
User = $Credential.UserName }
Password = $encypted
Creation = $CurrentDate if (-not($Credential)) {
$Credential = Get-Credential -Message $CredentialName
}
if ($Credential.UserName) {
if ($null -eq $CSContent.PfxCertificate) {
$Cert = Get-CSCertificate -Type $CSContent.Type -Thumbprint $CSContent.Thumbprint
} }
Add-Member -InputObject $CSContent -Name $CredentialName -MemberType NoteProperty -Value $CredentialHash else {
try { $Cert = Get-PfxCertificate -FilePath $CSContent.PfxCertificate -ErrorAction Stop
ConvertTo-Json -InputObject $CSContent | Out-File -FilePath $Path
} }
catch [System.Exception] {
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) {
$MessageParams = @{ $MessageParams = @{
Message = "Couldn't add item into credential store!" Message = "The given host already exists. Nothing to do here."
ErrorAction = "Stop" }
Write-Warning @MessageParams
}
else {
$RSAKey = Get-RandomAESKey
$CredentialHash = [ordered]@{
User = $Credential.UserName
Password = ConvertFrom-SecureString -SecureString $Credential.Password -Key $RSAKey
Created = $CurrentDate
LastChange = $null
EncryptedKey = [Convert]::ToBase64String($Cert.PublicKey.Key.Encrypt($RSAKey, [System.Security.Cryptography.RSAEncryptionPadding]::Pkcs1))
}
Add-Member -InputObject $CSContent -Name $CredentialName -MemberType NoteProperty -Value $CredentialHash
try {
ConvertTo-Json -InputObject $CSContent | Out-File -FilePath $Path
}
catch {
$MessageParams = @{
Message = "Couldn't add item into credential store!"
ErrorAction = "Stop"
}
Write-Error @MessageParams
} }
Write-Error @MessageParams
} }
} }
} else {
else { $MessageParams = @{
$MessageParams = @{ Message = "Please Provide at least a valid user!"
Message = "Please Provide at least a valid user!" ErrorAction = "Stop"
ErrorAction = "Stop" }
Write-Error @MessageParams
} }
Write-Error @MessageParams
} }
end {
}
} }

View File

@ -27,15 +27,21 @@ function Remove-CredentialStoreItem {
[None] [None]
.EXAMPLE .EXAMPLE
Remove-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" Remove-CredentialStoreItem -RemoteHost "esx01.myside.local"
Remove-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc
.EXAMPLE
Remove-CredentialStoreItem -Shared -RemoteHost "esx01.myside.local"
.EXAMPLE
Remove-CredentialStoreItem -Shared -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.EXAMPLE
Remove-CredentialStoreItem -RemoteHost "esx01.myside.local" -Identifier svc
.NOTES .NOTES
``` - File Name : Remove-CredentialStoreItem.ps1
File Name : Remove-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -43,9 +49,6 @@ function Remove-CredentialStoreItem {
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Private")] [Parameter(Mandatory = $true, ParameterSetName = "Private")]
[Parameter(Mandatory = $true, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[string]$RemoteHost, [string]$RemoteHost,
@ -54,43 +57,62 @@ function Remove-CredentialStoreItem {
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Identifier, [string]$Identifier,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared [ValidateNotNullOrEmpty()]
[string]$Path
) )
# First set a constand path for private CredentialStore mode. begin {
if ($PSCmdlet.ParameterSetName -eq "Private") { # Set the CredentialStore for private, shared or custom mode.
$Path = "{0}\CredentialStore.json" -f $env:APPDATA Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
} if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
# Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Path $Path)) {
$MessageParams = @{
Message = "Could not add anything into the given CredentailStore."
ErrorAction = "Stop"
} }
Write-Error @MessageParams elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
} if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
# Read the file content based on the given ParameterSetName }
$CSContent = Get-CredentialStore -Path $Path
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) {
# We need to use the .NET Method because there is no easier way in PowerShell.
$CSContent.PSObject.Properties.Remove($CredentialName)
ConvertTo-Json -InputObject $CSContent | Out-File -FilePath $Path
}
else {
$MessageParams = @{
Message = "The given CredentailStoreItem does not exist."
} }
Write-Warning @MessageParams
} }
process {
# Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Shared -Path $Path)) {
$MessageParams = @{
Message = "Could not add anything into the given CredentialStore."
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
# Read the file content based on the given ParameterSetName
$CSContent = Get-CredentialStore -Shared -Path $Path
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype NoteProperty) {
# We need to use the .NET Method because there is no easier way in PowerShell.
$CSContent.PSObject.Properties.Remove($CredentialName)
ConvertTo-Json -InputObject $CSContent -Depth 5 | Out-File -FilePath $Path -Encoding utf8
}
else {
$MessageParams = @{
Message = "The given CredentialStoreItem does not exist."
}
Write-Warning @MessageParams
}
}
end {
}
} }

View File

@ -4,6 +4,7 @@ function Set-CredentialStoreItem {
Changes the credentials for the given remote host in the store. Changes the credentials for the given remote host in the store.
.DESCRIPTION .DESCRIPTION
Use this function to update your already stored RemoteHost items.
.PARAMETER Path .PARAMETER Path
Define the store in which your given host entry already exists. Define the store in which your given host entry already exists.
@ -19,6 +20,9 @@ function Set-CredentialStoreItem {
Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which
can be decrypted across systems. can be decrypted across systems.
.PARAMETER Credential
Provided the new credentials you want to update inside the RemoteHost item.
.INPUTS .INPUTS
[None] [None]
@ -27,14 +31,14 @@ function Set-CredentialStoreItem {
.EXAMPLE .EXAMPLE
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local"
.EXAMPLE
Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc Set-CredentialStoreItem -Path "C:\TMP\mystore.json" -RemoteHost "esx01.myside.local" -Identifier svc
.NOTES .NOTES
``` - File Name : Set-CredentialStoreItem.ps1
File Name : Set-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -42,9 +46,6 @@ function Set-CredentialStoreItem {
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $true, ParameterSetName = "Private")] [Parameter(Mandatory = $true, ParameterSetName = "Private")]
[Parameter(Mandatory = $true, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[string]$RemoteHost, [string]$RemoteHost,
@ -53,64 +54,89 @@ function Set-CredentialStoreItem {
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Identifier, [string]$Identifier,
[Parameter(Mandatory = $false, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[PSCredential]$Credential,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Shared [ValidateNotNullOrEmpty()]
[string]$Path
) )
# First set a constant path for private CredentialStore mode. begin {
if ($PSCmdlet.ParameterSetName -eq "Private") { # Set the CredentialStore for private, shared or custom mode.
$Path = "{0}\CredentialStore.json" -f $env:APPDATA Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
} if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
# Lets do a quick test on the given CredentialStore.
if (-not(Test-CredentialStore -Path $Path)) {
$MessageParams = @{
Message = "Could not add anything into the given CredentailStore."
ErrorAction = "Stop"
} }
Write-Error @MessageParams elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
} if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
# Read the file content based on the given ParameterSetName
$CSContent = Get-CredentialStore -Path $Path
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
$Creds = Get-Credential -Message $CredentialName
if ($Creds.UserName) {
if ($CSContent.Type -eq "Shared") {
$Key = Get-ChallengeFile
$encypted = ConvertFrom-SecureString -SecureString $Creds.Password -Key $Key
}
else {
$encypted = ConvertFrom-SecureString -SecureString $Creds.Password
}
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) {
$CSContent.$CredentialName.User = $Creds.UserName
$CSContent.$CredentialName.Password = $encypted
$CSContent.$CredentialName.Creation = $CurrentDate
ConvertTo-Json -InputObject $CSContent | Out-File -FilePath $Path
}
else {
$MessageParams = @{
Message = "The given CredentailStoreItem does not exist."
} }
Write-Warning @MessageParams
} }
} }
Else {
$MessageParams = @{ process {
Message = "Please Provide at least a valid user!" # Lets do a quick test on the given CredentialStore.
ErrorAction = "Stop" if (-not(Test-CredentialStore -Shared -Path $Path)) {
$MessageParams = @{
Message = "Could not add anything into the given CredentailStore."
ErrorAction = "Stop"
}
Write-Error @MessageParams
} }
Write-Error @MessageParams
# Read the file content based on the given ParameterSetName
$CSContent = Get-CredentialStore -Shared -Path $Path
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
if ($Identifier -ne "") {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
}
else {
$CredentialName = $RemoteHost
}
if (-not($Credential)) {
$Credential = Get-Credential -Message $CredentialName
}
if ($Credential.UserName) {
if ($null -eq $CSContent.PfxCertificate) {
$Cert = Get-CSCertificate -Type $CSContent.Type -Thumbprint $CSContent.Thumbprint
}
else {
$Cert = Get-PfxCertificate -FilePath $CSContent.PfxCertificate -ErrorAction Stop
}
if (Get-Member -InputObject $CSContent -Name $CredentialName -Membertype Properties) {
$RSAKey = Get-RandomAESKey
$CSContent.$CredentialName.User = $Credential.UserName
$CSContent.$CredentialName.Password = ConvertFrom-SecureString -SecureString $Credential.Password -Key $RSAKey
$CSContent.$CredentialName.LastChange = $CurrentDate
$CSContent.$CredentialName.EncryptedKey = [Convert]::ToBase64String(
$Cert.PublicKey.Key.Encrypt(
$RSAKey,
[System.Security.Cryptography.RSAEncryptionPadding]::Pkcs1
)
)
ConvertTo-Json -InputObject $CSContent -Depth 5 | Out-File -FilePath $Path -Encoding utf8
}
}
Else {
$MessageParams = @{
Message = "Please Provide at least a valid user!"
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
end {
} }
} }

View File

@ -1,4 +1,4 @@
function Test-CredentialStoreItem() { function Test-CredentialStoreItem {
<# <#
.SYNOPSIS .SYNOPSIS
Checks if the given RemoteHost identifier combination exists in the credential store. Checks if the given RemoteHost identifier combination exists in the credential store.
@ -37,11 +37,9 @@ function Test-CredentialStoreItem() {
} }
.NOTES .NOTES
``` - File Name : Test-CredentialStoreItem.ps1
File Name : Test-CredentialStoreItem.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -64,32 +62,48 @@ function Test-CredentialStoreItem() {
[switch]$Shared [switch]$Shared
) )
if ($PSCmdlet.ParameterSetName -eq "Private") { begin {
$Path = "{0}\CredentialStore.json" -f $env:APPDATA # Set the CredentialStore for private, shared or custom mode.
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
}
elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
} }
if ($Identifier -ne "") { process {
$CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost if ($Identifier -ne "") {
} $CredentialName = $RemoteHost = "{0}/{1}" -f $Identifier, $RemoteHost
else {
$CredentialName = $RemoteHost
}
if (Test-CredentialStore -Path $Path) {
$CS = Get-CredentialStore -Path $Path
$CSMembers = Get-Member -InputObject $CS
if (($CSMembers.MemberType -eq "NoteProperty") -and ($CSMembers.Name -eq $CredentialName)) {
return $true
} }
else { else {
return $false $CredentialName = $RemoteHost
}
if (Test-CredentialStore -Shared -Path $Path) {
$CS = Get-CredentialStore -Shared -Path $Path
$CSMembers = Get-Member -InputObject $CS
if (($CSMembers.MemberType -eq "NoteProperty") -and ($CSMembers.Name -contains $CredentialName)) {
return $true
}
else {
return $false
}
}
else {
$MsgParams = @{
ErrorAction = "Stop"
Message = "The given credential store ({0}) does not exist!" -f $Path
}
Write-Error @MsgParams
} }
} }
else {
$MsgParams = @{ end {
ErrorAction = "Stop"
Message = "The given credential store ({0}) does not exist!" -f $Path
}
Write-Error @MsgParams
} }
} }

View File

@ -1,45 +1,36 @@
#
# Module manifest for module 'PSCredentialStore'
#
# Generated by: OCram85
#
# Generated on: 27.07.2017
#
@{ @{
# Script module or binary module file associated with this manifest. # Script module or binary module file associated with this manifest.
RootModule = 'PSCredentialStore' RootModule = 'PSCredentialStore.psm1'
# Version number of this module. # Version number of this module.
# Do not touch the version number. It gets replaced in the build process. ModuleVersion = '0.0.9999'
ModuleVersion = '0.0.0.9999'
# Supported PSEditions # Supported PSEditions
# CompatiblePSEditions = @() CompatiblePSEditions = 'Desktop', 'Core'
# ID used to uniquely identify this module # ID used to uniquely identify this module
GUID = '6800e192-9df8-4e30-b253-eb2c799bbe84' GUID = '6800e192-9df8-4e30-b253-eb2c799bbe84'
# Author of this module # Author of this module
Author = 'OCram85' Author = 'OCram85'
# Company or vendor of this module # Company or vendor of this module
CompanyName = '' CompanyName = ''
# Copyright statement for this module # Copyright statement for this module
Copyright = '(c) 2017 OCram85. All rights reserved.' Copyright = '(c) 2019 OCram85. All rights reserved.'
# Description of the functionality provided by this module # Description of the functionality provided by this module
Description = 'A simple credential manager to store and reuse multiple credential objects.' Description = 'A simple credential manager to store and reuse multiple credential objects.'
# Minimum version of the Windows PowerShell engine required by this module # Minimum version of the PowerShell engine required by this module
PowerShellVersion = '4.0' PowerShellVersion = '5.1'
# Name of the Windows PowerShell host required by this module # Name of the PowerShell host required by this module
# PowerShellHostName = '' # PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module # Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = '' # PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
@ -64,38 +55,51 @@
# TypesToProcess = @() # TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module # Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @() FormatsToProcess = @(
'Formats/PSCredential.Store.Format.ps1xml',
'Formats/PSCredentialStore.Certificate.Attribute.ps1xml'
)
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @() # NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @( FunctionsToExport = @(
# Connection Group # Certificate
'Get-CSCertificate',
'Import-CSCertificate',
'New-CSCertAttribute',
'New-CSCertificate',
'Test-CSCertificate',
'Use-CSCertificate',
# Pfx Certificate
# 'Get-CSPfxCertificate',
# 'Import-CSPfxCertificate',
# 'Test-CSPfxCertificate',
# Connection
'Connect-To', 'Connect-To',
'Disconnect-From', 'Disconnect-From',
'Test-CSConnection', 'Test-CSConnection',
# Item Group # Item
'Get-CredentialStoreItem', 'Get-CredentialStoreItem',
'Set-CredentialStoreItem',
'New-CredentialStoreItem', 'New-CredentialStoreItem',
'Remove-CredentialStoreItem', 'Remove-CredentialStoreItem',
'Set-CredentialStoreItem',
'Test-CredentialStoreItem', 'Test-CredentialStoreItem',
# Store Group # Store
'Get-CredentialStore', 'Get-CredentialStore',
'New-CredentialStore', 'New-CredentialStore',
'Test-CredentialStore' 'Test-CredentialStore'
) )
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @() CmdletsToExport = @()
# Variables to export from this module # Variables to export from this module
VariablesToExport = '*' VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @() AliasesToExport = @()
# DSC resources to export from this module # DSC resources to export from this module
# DscResourcesToExport = @() # DscResourcesToExport = @()
@ -107,33 +111,40 @@
# FileList = @() # FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{ PrivateData = @{
PSData = @{ PSData = @{
# Tags applied to this module. These help with module discovery in online galleries. # Tags applied to this module. These help with module discovery in online galleries.
Tags = @('CredentialStore', Tags = 'CredentialStore', 'CredentialManager'
'CredentialManager'
)
# A URL to the license for this module. # A URL to the license for this module.
LicenseUri = 'https://github.com/OCram85/PSCredentialStore/blob/master/LICENSE' LicenseUri = 'https://github.com/OCram85/PSCredentialStore/blob/master/LICENSE'
# A URL to the main website for this project. # A URL to the main website for this project.
ProjectUri = 'https://github.com/OCram85/PSCredentialStore' ProjectUri = 'https://github.com/OCram85/PSCredentialStore'
# A URL to an icon representing this module. # A URL to an icon representing this module.
# IconUri = '' IconUri = 'https://raw.githubusercontent.com/OCram85/PSCredentialStore/master/assets/logo256.png'
# ReleaseNotes of this module # ReleaseNotes of this module
ReleaseNotes = 'This is a pre-release version!. Do not use in production!' ReleaseNotes = 'See https://github.com/OCram85/PSCredentialStore/releases page for details.'
# Prerelease string of this module
#Prerelease = 'preview'
# Flag to indicate whether the module requires explicit user acceptance for install/update
# RequireLicenseAcceptance = $false
# External dependent modules of this module
# ExternalModuleDependencies = @()
} # End of PSData hashtable } # End of PSData hashtable
} # End of PrivateData hashtable } # End of PrivateData hashtable
# HelpInfo URI of this module # HelpInfo URI of this module
HelpInfoURI = 'https://github.com/OCram85/PSCredentialStore' HelpInfoURI = 'https://github.com/OCram85/PSCredentialStore'
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = '' # DefaultCommandPrefix = ''

View File

@ -1,10 +1,18 @@
$Items = (Get-ChildItem -Path ("{0}\*.ps1" -f $PSScriptRoot ) -Recurse ).FullName | Where-Object { #region module-definition
#endregion module-definition
Set-Variable -Name "CSVersion" -Value "2.0.0" -Option Constant -Scope 'Script' -ErrorAction Stop
#region dot-sourcing
# dot-sourcing all module functions. The export is handled via manifest file.
$Items = (Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath '*.ps1') -Recurse ).FullName | Where-Object {
$_ -notmatch "(Classes|Init)" $_ -notmatch "(Classes|Init)"
} }
ForEach ($Item in $Items) { foreach ($Item in $Items) {
# Write-Verbose ("dot sourcing file {0}" -f $Item) # Write-Verbose ("dot sourcing file {0}" -f $Item)
. $Item . $Item
} }
#endregion dot-sourcing
# Exports are now controlled by module manifest
# Export-ModuleMember -Function *

View File

@ -0,0 +1,81 @@
function Get-CSPfxCertificate {
<#
.SYNOPSIS
Returns the certificate object given by thumbprint.
.DESCRIPTION
You can use this function to get a stored certificate. Search for the object by its unique thumbprint.
.PARAMETER Thumbprint
Provide one or more thumbprints.
.PARAMETER StoreName
Select the store name in which you want to search the certificates.
.PARAMETER StoreLocation
Select between the both available locations CurrentUser odr LocalMachine.
.INPUTS
[string]
.OUTPUTS
[System.Security.Cryptography.X509Certificates.X509Certificate2[]]
.EXAMPLE
Get-CSPfxCertificate -Thumbprint '12345678' -StoreName 'My' -StoreLocation 'CurrentUser'
.NOTES
- File Name : Get-CSPfxCertificate.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[string[]]$Thumbprint,
[Parameter(Mandatory = $false)]
[ValidateSet(
'AddressBook',
'AuthRoot',
'CertificateAuthority',
'Disallowed',
'My',
'Root',
'TrustedPeople',
'TrustedPublisher'
)]
[string]$StoreName = 'My',
[Parameter(Mandatory = $false)]
[ValidateSet(
'CurrentUser',
'LocalMachine'
)]
[string]$StoreLocation = 'CurrentUser'
)
begin {
$Store = [System.Security.Cryptography.X509Certificates.X509Store]::New($StoreName, $StoreLocation)
try {
$Store.Open('ReadOnly')
}
catch {
$_.Exception.Message | Write-Error -ErrorAction Stop
}
}
process {
foreach ($Thumb in $Thumbprint) {
Write-Output $Store.Certificates | Where-Object { $_.Thumbprint -eq $Thumb }
}
}
end {
$Store.Close()
}
}

View File

@ -0,0 +1,61 @@
function Get-DefaultCredentialStorePath {
<#
.SYNOPSIS
Returns the default CredentialStore path based on the current OS.
.DESCRIPTION
This is a low level helper function.
.INPUTS
[None]
.OUTPUTS
[string]
.EXAMPLE
$Path = Get-DefaultCredentialStorePath
.NOTES
- File Name : Get-DefaultCredentialStorePath.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory = $false)]
[switch]$Shared
)
begin { }
process {
if ($Shared.IsPresent) {
if ($IsLinux) {
return Join-Path -Path '/var/opt' -ChildPath 'PSCredentialStore/CredentialStore.json'
}
if ($IsMacOS) {
return Join-Path -Path '/var/opt' -ChildPath 'PSCredentialStore/CredentialStore.json'
}
elseif (($isWindows) -or ($PSVersionTable.PSVersion.Major -lt 6) -or ($PSVersionTable.PSEdition -eq 'Desktop')) {
return Join-Path -Path $env:ProgramData -ChildPath 'PSCredentialStore/CredentialStore.json'
}
}
else {
if ($IsLinux) {
return Join-Path -Path $Env:HOME -ChildPath 'CredentialStore.json'
}
if ($IsMacOS) {
return Join-Path -Path $Env:HOME -ChildPath 'CredentialStore.json'
}
elseif (($isWindows) -or ($PSVersionTable.PSVersion.Major -lt 6) -or ($PSVersionTable.PSEdition -eq 'Desktop')) {
return Join-Path -Path $env:AppData -ChildPath 'CredentialStore.json'
}
}
}
end { }
}

View File

@ -11,9 +11,9 @@ function Get-ModuleBase {
Returns the base path as string Returns the base path as string
.NOTES .NOTES
File Name : Get-ModuleBase.ps1 - File Name : Get-ModuleBase.ps1
Author : Marco Blessing - marco.blessing@googlemail.com - Author : Marco Blessing - marco.blessing@googlemail.com
Requires : - Requires :
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -21,9 +21,9 @@ function Get-ModuleBase {
[CmdletBinding()] [CmdletBinding()]
[OutputType()] [OutputType()]
param() param()
begin {} begin { }
process { process {
return $MyInvocation.MyCommand.Module.ModuleBase return $MyInvocation.MyCommand.Module.ModuleBase
} }
end {} end { }
} }

View File

@ -0,0 +1,44 @@
function Get-RandomAESKey {
<#
.SYNOPSIS
Generate a new 32-byte AES key.
.DESCRIPTION
Uses the System.Security.Cryptography namespace for random aes key generation.
.INPUTS
[None]
.OUTPUTS
[byte[]]
.EXAMPLE
.\Get-RandomAESKey
.NOTES
- File Name : Get-RandomAESKey.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([byte[]])]
param()
begin { }
process {
$key = [byte[]]::new(32)
$rng = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()
$rng.GetBytes($key)
Write-Output $key
if ($null -ne $key) {
[array]::Clear($key, 0, $key.Length)
}
}
end { }
}

View File

@ -0,0 +1,44 @@
function Get-TempDir {
<#
.SYNOPSIS
Returns the valid temp dir of the current OS
.DESCRIPTION
Returns the valid temp dir of the current OS.
.INPUTS
[None]
.OUTPUTS
[string]
.EXAMPLE
Get-TempDir
.NOTES
- File Name : Get-TempDir.ps1
- Author : Marco Blessing - marco.blessing@googlemail.com
- Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([string])]
param()
begin {
}
process {
if ($IsLinux) {
return (Resolve-Path -Path '/tmp/').Path
}
if ($IsMacOS) {
return (Resolve-Path -Path '/tmp/').Path
}
elseif (($isWindows) -or ($PSVersionTable.PSVersion.Major -lt 6) -or ($PSVersionTable.PSEdition -eq 'Desktop')) {
return (Resolve-Path -Path $env:TEMP).Path
}
}
end {
}
}

View File

@ -0,0 +1,112 @@
function Import-CSPfxCertificate {
<#
.SYNOPSIS
Adds a given pfx certificate file to current user's personal certificate store.
.DESCRIPTION
This function is used to import existing pfx certificate files. The Import-PFXCertificate cmdlet from the
PKI module imports the certificate into a deprecated store. Thus you can't read the private key afterwards or
using it for decrypting data.
.PARAMETER Path
Path to an existing *.pfx certificate file.
.PARAMETER StoreName
Additionally you change change the store where you want the certificate into.
.INPUTS
[None]
.OUTPUTS
[None]
.EXAMPLE
Import-CSPfxCertificate -Path (Join-Path -Path $Env:APPDATA -ChildPath '/PSCredentialStore.pfx')
.NOTES
File Name : Import-CSPfxCertificate.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Path,
[Parameter(Mandatory = $false)]
[ValidateSet(
'AddressBook',
'AuthRoot',
'CertificateAuthority',
'Disallowed',
'My',
'Root',
'TrustedPeople',
'TrustedPublisher'
)]
[string]$StoreName = 'My',
[Parameter(Mandatory = $false)]
[ValidateSet(
'CurrentUser',
'LocalMachine'
)]
[string]$StoreLocation = 'CurrentUser',
[Parameter(Mandatory = $false)]
[ValidateSet(
'ReadOnly',
'ReadWrite',
'MaxAllowed',
'OpenExistingOnly',
'IncludeArchived'
)]
[string]$OpenFlags = 'ReadWrite'
)
begin {
$Store = [System.Security.Cryptography.X509Certificates.X509Store]::new($StoreName, $StoreLocation)
try {
$Store.Open($OpenFlags)
}
catch {
$_.Exception.Message | Write-Error -ErrorAction Stop
}
}
process {
try {
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new(
$Path,
$null,
(
[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable -bor
[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet
)
)
if (Test-CSPfxCertificate -Thumbprint $cert.Thumbprint) {
Write-Warning -Message ('The certificate with thumbprint {0} is already present!' -f $cert.Thumbprint)
}
else {
$Store.Add($cert)
}
}
catch {
$_.Exception.Message | Write-Error -ErrorAction Stop
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.Exception]::new(
'Could not read or add the pfx certificate!'
)
}
Write-Error @ErrorParams
}
}
end {
$Store.Close()
}
}

View File

@ -40,11 +40,9 @@ function Resolve-Dependency {
} }
.NOTES .NOTES
``` - File Name : ResolveDependency.ps1
File Name : ResolveDependency.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -69,7 +67,12 @@ function Resolve-Dependency {
} }
process { process {
$SelectedDependency = $Dependency.Optional | Where-Object {$_.Name -match $Name} $SelectedDependency = $Dependency.Optional | Where-Object { $_.Name -match $Name }
# return true if there is no dependency defined
if ($null -eq $SelectedDependency) {
return $true
}
$res = @() $res = @()
foreach ($Module in $SelectedDependency.Modules) { foreach ($Module in $SelectedDependency.Modules) {
$res += Test-Module -Name $Module $res += Test-Module -Name $Module

View File

@ -0,0 +1,86 @@
function Test-CSPfxCertificate {
<#
.SYNOPSIS
Tests if the given certificate exists in a store.
.DESCRIPTION
Use this function to ensure if a certificate is already imported into a given store.
.PARAMETER Thumbprint
Provide one or more thumbprints.
.PARAMETER StoreName
Select the store name in which you want to search the certificates.
.PARAMETER StoreLocation
Select between the both available locations CurrentUser odr LocalMachine.
.INPUTS
[None]
.OUTPUTS
[bool]
.EXAMPLE
Test-CSPfxCertificate -Thumbprint '12345678' -StoreName 'My' -StoreLocation 'CurrentUser'
.NOTES
File Name : Test-CSPfxCertificate.ps1
Author : Marco Blessing - marco.blessing@googlemail.com
Requires :
.LINK
https://github.com/OCram85/PSCredentialStore
#>
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[string]$Thumbprint,
[Parameter(Mandatory = $false)]
[ValidateSet(
'AddressBook',
'AuthRoot',
'CertificateAuthority',
'Disallowed',
'My',
'Root',
'TrustedPeople',
'TrustedPublisher'
)]
[string]$StoreName = 'My',
[Parameter(Mandatory = $false)]
[ValidateSet(
'CurrentUser',
'LocalMachine'
)]
[string]$StoreLocation = 'CurrentUser'
)
begin {
$Store = [System.Security.Cryptography.X509Certificates.X509Store]::New($StoreName, $StoreLocation)
try {
$Store.Open('ReadOnly')
}
catch {
$_.Exception.Message | Write-Error -ErrorAction Stop
}
}
process {
$Cert = $Store.Certificates | Where-Object { $_.Thumbprint -eq $Thumbprint }
if ($null -eq $Cert) {
return $false
}
else {
return $true
}
}
end {
$Store.Close()
}
}

View File

@ -34,11 +34,9 @@ function Test-Module {
.\Test-Dependency -Name 'VMware.PowerCLI' -Type 'Module' -StopIfFails .\Test-Dependency -Name 'VMware.PowerCLI' -Type 'Module' -StopIfFails
.NOTES .NOTES
``` - File Name : Test-Module.ps1
File Name : Get-RandomKey.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
@ -50,10 +48,6 @@ function Test-Module {
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$Name, [string]$Name,
[Parameter(Mandatory = $false)]
[ValidateSet('Module', 'PSSnapin', 'Custom')]
[string]$Type = 'Module',
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$MessagePattern = @" [string]$MessagePattern = @"
@ -62,45 +56,22 @@ Could not find the required {0} called {1}. Please install the required {0} to r
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[switch]$StopIfFails [switch]$StopIfFails
) )
begin { begin { }
}
process { process {
$Message = $MessagePattern -f $Type, $Name $Message = $MessagePattern -f $Type, $Name
Write-Debug $Message Write-Debug $Message
switch ($Type) {
'Module' {
if (Get-Module -Name $Name -ListAvailable) {
return $true
}
else {
if ($StopIfFails) {
Write-Error -Message $Message -ErrorAction Stop -Category NotInstalled
}
return $false
}
}
'PSSnapin' { if (Get-Module -Name $Name -ListAvailable) {
if (Get-PSSnapin -Name $Name -Registered) { return $true
return $true }
} else {
else { if ($StopIfFails) {
if ($StopIfFails) { Write-Error -Message $Message -ErrorAction Stop -Category NotInstalled
Write-Error -Message $Message -ErrorAction Stop -Category NotInstalled
return $false
}
}
}
'Custom' {
Throw 'Custom tests are not implemented yet!'
} }
return $false
} }
} }
end { end { }
}
} }

View File

@ -25,46 +25,62 @@ function Get-CredentialStore {
$CSContent = Get-CredentialStore -Path "C:\TMP\mystore.json" $CSContent = Get-CredentialStore -Path "C:\TMP\mystore.json"
.NOTES .NOTES
``` - File Name : Get-CredentialStore.ps1
File Name : Get-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
[OutputType("PSCredentialStore.Store")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [string]$Path,
[Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared [switch]$Shared
) )
if ($PSCmdlet.ParameterSetName -eq 'Private') { begin { }
$Path = "{0}\CredentialStore.json" -f $env:APPDATA
}
if (Test-CredentialStore -Path $Path) { process {
try { # Set the CredentialStore for private, shared or custom mode.
$FileContent = Get-Content -Path $Path -Raw Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
ConvertFrom-Json $FileContent if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
} }
catch [System.Exception] { elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
if (Test-CredentialStore -Path $Path -Shared) {
try {
$FileContent = Get-Content -Path $Path -Raw
$CS = ConvertFrom-Json $FileContent
$CS.PSObject.TypeNames.Insert(0, "PSCredentialStore.Store")
return $CS
}
catch [System.Exception] {
$MessageParams = @{
Message = "Unknown CredentialStore format. Invalid JSON file."
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
}
else {
$MessageParams = @{ $MessageParams = @{
Message = "Unknown CredentialStore format. Invalid JSON file." Message = "Could not find the CredentialStore."
ErrorAction = "Stop" ErrorAction = "Stop"
} }
Write-Error @MessageParams Write-Error @MessageParams
} }
} }
else {
$MessageParams = @{ end { }
Message = "Could not find the CredentialStore."
ErrorAction = "Stop"
}
Write-Error @MessageParams
}
} }

View File

@ -18,11 +18,21 @@ function New-CredentialStore {
.PARAMETER Force .PARAMETER Force
Use this switch to reset an existing store. The complete content will be wiped. Use this switch to reset an existing store. The complete content will be wiped.
.PARAMETER SkipPFXCertCreation
You can skip the pfx certificate creation process. This makes sense if you have a previously created cert or want to
import a cert in cross-platform environments.
.Parameter UseCertStore
Instead of using a plain pfx file beside your CredentialStore file you can import it into the user or machine
certificate store. In this case the system itself secures the cert and you don't hat to set custom NTFS
permissions so secure your shared certificate.
.INPUTS .INPUTS
[None] [None]
.OUTPUTS .OUTPUTS
[None] ['PSCredentialStore.Store'] Returns the recently created CredentialStore object if the -PassThru parameter
was given.
.EXAMPLE .EXAMPLE
New-CredentialStore New-CredentialStore
@ -41,72 +51,208 @@ function New-CredentialStore {
# Creates a new shared CredentialStore in the given location. # Creates a new shared CredentialStore in the given location.
.NOTES .NOTES
``` - File Name : New-CredentialStore.ps1
File Name : New-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = "Private")]
[OutputType("PSCredentialStore.Store")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared, [switch]$Shared,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData, [System.IO.FileInfo]$Path,
[Parameter(Mandatory = $false, ParameterSetName = "Private")] [Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[switch]$Force [Switch]$Force,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Switch]$PassThru,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Switch]$SkipPFXCertCreation,
[Parameter(Mandatory = $false, ParameterSetName = "Private")]
[Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[Switch]$UseCertStore
) )
# Lets get the current Date in a human readable format. begin {
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S" # Lets get the current Date in a human readable format.
$CurrentDate = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
# Set latest Credential Store version # Set latest Credential Store version
Set-Variable -Name "CSVersion" -Value "1.2.0" -Option Constant # Set-Variable -Name "CSVersion" -Value "2.0.0" -Option Constant -Scope
# Set the CredentialStore path for private mode. # test if the path input is a valid file path
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName) if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('Path')) {
if ($PSCmdlet.ParameterSetName -eq "Private") { if ($Path.Attributes -contains 'Directory') {
$Path = "{0}\CredentialStore.json" -f $Env:APPDATA $ErrorParams = @{
} ErrorAction = 'Stop'
Exception = [System.IO.InvalidDataException]::new(
# Test if in the given store already a CredentialStore exists. 'Please provide a full path containing the credential store file name with the .json extension!'
Write-Verbose "Test if there is already a credential store." )
if ((Test-CredentialStore -Path $Path) -and ($Force -ne $true)) { }
$MessageParam = @{ Write-Error @ErrorParams
Message = "The given file already exists. Use the 'Force' switch to override the existing store." }
ErrorAction = "Stop" elseif ( ($null -eq $Path.Extension) -or ($Path.Extension -ne '.json')) {
} $ErrorParams = @{
Write-Error @MessageParam ErrorAction = 'Stop'
} Exception = [System.IO.InvalidDataException]::new(
# We need to use the IDictionary to keep the property sorting in the object. 'Your provided path does not contain the required file extension .json !'
$ObjProperties = [ordered]@{ )
Version = $CSVersion }
Creation = $CurrentDate Write-Error @ErrorParams
} }
if ($PSCmdlet.ParameterSetName -eq "Shared") {
$ObjProperties.Type = "Shared"
# Check if a ChallengeFile already exists. We don't want to overide it.
# Otherwise previous created CredentialStores couln't be decrypted anymore.
if (-not (Test-ChallengeFile)) {
Set-ChallengeFile
} }
} }
else {
$ObjProperties.Type = "Private" process {
# Set the CredentialStore for private, shared or custom mode.
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if ($PSCmdlet.ParameterSetName -eq "Private") {
$Path = Get-DefaultCredentialStorePath
}
elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
if (!($PSBoundParameters.ContainsKey('Path'))) {
$Path = Get-DefaultCredentialStorePath -Shared
}
}
# Test if in the CredentialStore already exists.
Write-Verbose "Test if there is already a credential store."
if ((Test-Path -Path $Path) -and ($Force -ne $true)) {
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.InvalidOperationException]::new(
'The given file already exists. Use the -Force switch to override the existing store.'
)
}
Write-Error @ErrorParams
}
if (! $SkipPFXCertCreation.IsPresent) {
$CRTParams = @{
Country = 'DE'
State = 'PSCredentialStore'
City = 'PSCredentialStore'
Organization = 'PSCredentialStore'
OrganizationalUnitName = $PSCmdlet.ParameterSetName
CommonName = 'PSCredentialStore'
}
$CRTAttribute = New-CSCertAttribute @CRTParams
# If we are working with a ne shared store we have to create the location first.
# Otherwise openssl fails with unknown path
$StoreHome = Split-Path -Path $Path -Parent
if (! (Test-Path -Path $StoreHome)) {
New-Item -ItemType Directory -Path $StoreHome -ErrorAction Stop
}
$PfxParams = @{
CRTAttribute = $CRTAttribute
KeyName = Join-Path -Path $StoreHome -ChildPath 'private.key'
CertName = Join-Path -Path $StoreHome -ChildPath 'PSCredentialStore.pfx'
ErrorAction = 'Stop'
Confirm = $false
}
# test if there is already a cert
if ((Test-Path $PfxParams.CertName) -and (! $Force.IsPresent)) {
$ErrorParams = @{
Exception = [System.IO.InvalidDataException]::new(
'There is already a PfxCertificate for a private CredentialStore!'
)
ErrorAction = 'Stop'
}
Write-Error @ErrorParams
}
try {
New-CSCertificate @PfxParams
}
catch {
$_.Exception.Message | Write-Error
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.Exception]::new(
'Could not create the private PfXCertificate!'
)
}
Write-Error @ErrorParams
}
try {
$FreshCert = Get-PfxCertificate -FilePath $PfxParams.CertName -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
$_.Exception.Message | Write-Error
Write-Error -Message 'Could not read the new PfxCertificate.' -ErrorAction Stop
}
}
# We need to use the IDictionary to keep the property sorting in the object.
$ObjProperties = [ordered]@{
PSTypeName = 'PSCredentialStore.Store'
Version = $CSVersion
Created = $CurrentDate
PfxCertificate = $null
Thumbprint = $null
Type = $null
}
if ($PSCmdlet.ParameterSetName -eq "Shared") {
$ObjProperties.Type = "Shared"
}
else {
$ObjProperties.Type = "Private"
}
if (! $SkipPFXCertCreation.IsPresent) {
$ObjProperties.Thumbprint = $FreshCert.Thumbprint
if ($UseCertStore.IsPresent) {
Write-Verbose 'Importing new PFX certificate file...'
Import-CSCertificate -Type $ObjProperties.Type -Path $PfxParams.CertName
}
else {
$ObjProperties.PfxCertificate = $PfxParams.CertName
}
}
$CredentialStoreObj = [PSCustomObject]$ObjProperties
try {
$JSON = ConvertTo-Json -InputObject $CredentialStoreObj -ErrorAction Stop
$JSON | Out-File -FilePath $Path -ErrorAction Stop -Force
}
catch {
$_.Exception.Message | Write-Error
$ErrorParams = @{
ErrorAction = 'Stop'
Exception = [System.IO.IOException]::new(
'Unable to convert or write the CredentialStore'
)
}
Write-Error @ErrorParams
}
if ($PassThru.IsPresent) {
return $CredentialStoreObj
}
} }
# Create a new object for easy conversion into a json file
$CredentialStoreObj = New-Object -TypeName psobject -Property $ObjProperties end {
try {
ConvertTo-Json -InputObject $CredentialStoreObj | Out-File -FilePath $Path
}
catch [System.Exception] {
$_.Exception | Format-List -Force | Out-String | Write-Error -ErrorAction Stop
} }
} }

View File

@ -14,49 +14,54 @@ function Test-CredentialStore {
Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which Switch to shared mode with this param. This enforces the command to work with a shared CredentialStore which
can be decrypted across systems. can be decrypted across systems.
.EXAMPLE
Test-CredentialStore -eq $true
.NOTES .NOTES
``` - File Name : Test-CredentialStore.ps1
File Name : Test-CredentialStore.ps1 - Author : Marco Blessing - marco.blessing@googlemail.com
Author : Marco Blessing - marco.blessing@googlemail.com - Requires :
Requires :
```
.LINK .LINK
https://github.com/OCram85/PSCredentialStore https://github.com/OCram85/PSCredentialStore
#> #>
[CmdletBinding(DefaultParameterSetName = "Private")] [CmdletBinding(DefaultParameterSetName = "Private")]
param( param(
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $false, ParameterSetName = "Shared")]
[string]$Path = "{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData, [string]$Path,
[Parameter(Mandatory = $false, ParameterSetName = "Shared")] [Parameter(Mandatory = $true, ParameterSetName = "Shared")]
[switch]$Shared [switch]$Shared
) )
begin {
if ($PSCmdlet.ParameterSetName -eq "Private") { # Set latest Credential Store version
$Path = "{0}\CredentialStore.json" -f $Env:APPDATA #Set-Variable -Name "CSVersion" -Value "2.0.0" -Option Constant
} }
# Set latest Credential Store version process {
Set-Variable -Name "CSVersion" -Value "1.2.0" -Option Constant # Set the CredentialStore for private, shared or custom mode.
Write-Debug ("ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName)
if (Test-Path $Path) { if ($PSCmdlet.ParameterSetName -eq "Private") {
Write-Verbose "CredentialStore in given path found." $Path = Get-DefaultCredentialStorePath
# try tor read the store. Removed the Get-CredentialStore function to avoid recursive calls.
try {
$FileContent = Get-Content -Path $Path -Raw
$CSContent = ConvertFrom-Json $FileContent
} }
catch { elseif ($PSCmdlet.ParameterSetName -eq "Shared") {
Write-Warning "Could not read or convert the given CredentialStore." if (!($PSBoundParameters.ContainsKey('Path'))) {
Return $False $Path = Get-DefaultCredentialStorePath -Shared
}
} }
Return $True Write-Verbose -Message ("Path is: {0}" -f $Path)
if (Test-Path $Path) {
Write-Verbose "CredentialStore in given path found."
return $true
}
else {
Write-Verbose "The given CredentialStore does not exist!"
return $false
}
} }
Else {
Write-Verbose "The given CredentialStore does not exist!" end { }
Return $False
}
} }

BIN
src/Vendor/libressl255/LICENSE (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libcrypto-41.dll (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libcrypto-41.exp (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libcrypto-41.lib (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libcrypto-41.pdb (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libssl-43.dll (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libssl-43.exp (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libssl-43.lib (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libssl-43.pdb (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libtls-15.dll (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libtls-15.exp (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libtls-15.lib (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/libtls-15.pdb (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/ocspcheck.exe (Stored with Git LFS) vendored Normal file

Binary file not shown.

BIN
src/Vendor/libressl255/openssl.exe (Stored with Git LFS) vendored Normal file

Binary file not shown.

245
src/openssl.conf Normal file
View File

@ -0,0 +1,245 @@
#
# OpenSSL example configuration file.
# This is mostly being used for generation of certificate requests.
#
# This definition stops the following lines choking if HOME isn't
# defined.
HOME = .
RANDFILE = $ENV::HOME/.rnd
# Extra OBJECT IDENTIFIER info:
#oid_file = $ENV::HOME/.oid
oid_section = new_oids
# To use this configuration file with the "-extfile" option of the
# "openssl x509" utility, name here the section containing the
# X.509v3 extensions to use:
# extensions =
# (Alternatively, use a configuration file that has only
# X.509v3 extensions in its main [= default] section.)
[ new_oids ]
# We can add new OIDs in here for use by 'ca' and 'req'.
# Add a simple OID like this:
# testoid1=1.2.3.4
# Or use config file substitution like this:
# testoid2=${testoid1}.5.6
####################################################################
[ ca ]
default_ca = CA_default # The default ca section
####################################################################
[ CA_default ]
dir = ./demoCA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
new_certs_dir = $dir/newcerts # default place for new certs.
certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/cakey.pem # The private key
RANDFILE = $dir/private/.rand # private random number file
x509_extensions = usr_cert # The extentions to add to the cert
# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crl_extensions = crl_ext
default_days = 365 # how long to certify for
default_crl_days = 30 # how long before next CRL
default_md = md5 # which md to use.
preserve = no # keep passed DN ordering
# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy = policy_match
# For the CA policy
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
####################################################################
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca # The extentions to add to the self signed cert
# Passwords for private keys if not present they will be prompted for
# input_password = secret
# output_password = secret
# This sets a mask for permitted string types. There are several options.
# default: PrintableString, T61String, BMPString.
# pkix : PrintableString, BMPString.
# utf8only: only UTF8Strings.
# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
# MASK:XXXX a literal mask value.
# WARNING: current versions of Netscape crash on BMPStrings or UTF8Strings
# so use this option with caution!
string_mask = nombstr
# req_extensions = v3_req # The extensions to add to a certificate request
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = DE
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = BW
localityName = Locality Name (eg, city)
localityName_default = PSCredentialStore
0.organizationName = Organization Name (eg, company)
0.organizationName_default = PSCredentialStore
# we can do this but it is not needed normally :-)
#1.organizationName = Second Organization Name (eg, company)
#1.organizationName_default = World Wide Web Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
#organizationalUnitName_default = PSCRedentialStore
commonName = Common Name (eg, YOUR name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 40
# SET-ex3 = SET extension number 3
[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 0
challengePassword_max = 20
unstructuredName = An optional company name
[ usr_cert ]
# These extensions are added when 'ca' signs a request.
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints = CA:FALSE
# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.
# This is OK for an SSL server.
# nsCertType = server
# For an object signing certificate this would be used.
# nsCertType = objsign
# For normal client use this is typical
# nsCertType = client, email
# and for everything including object signing:
# nsCertType = client, email, objsign
# This is typical in keyUsage for a client certificate.
keyUsage = nonRepudiation, digitalSignature, keyEncipherment, codeSigning
# This will be displayed in Netscape's comment listbox.
nsComment = "OpenSSL Generated Certificate"
# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# Copy subject details
# issuerAltName=issuer:copy
#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment, codeSigning
[ v3_ca ]
# Extensions for a typical CA
# PKIX recommendation.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
# This is what PKIX recommends but some broken software chokes on critical
# extensions.
#basicConstraints = critical,CA:true
# So we do this instead.
basicConstraints = CA:true
# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
# keyUsage = cRLSign, keyCertSign
# Some might want this also
# nsCertType = sslCA, emailCA
# Include email address in subject alt name: another PKIX recommendation
# subjectAltName=email:copy
# Copy issuer details
# issuerAltName=issuer:copy
# DER hex encoding of an extension: beware experts only!
# obj=DER:02:03
# Where 'obj' is a standard or added object
# You can even override a supported extension:
# basicConstraints= critical, DER:30:03:01:01:FF
[ crl_ext ]
# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
# issuerAltName=issuer:copy
authorityKeyIdentifier = keyid:always,issuer:always

View File

@ -1,15 +1,17 @@
$RepoRoot = (Get-GitDirectory).replace('\.git', '') $RepoRoot = (Get-Item -Path (Get-GitDirectory) -Force).Parent | Select-Object -ExpandProperty 'FullName'
Write-Verbose -Message ('RepoRoot: {0}' -f $RepoRoot) -Verbose
$ManifestFilePath = Join-Path -Path $RepoRoot -ChildPath '/src/PSCredentialStore.psd1'
Write-Verbose -Message ("ManifestFilePath: {0}" -f $ManifestFilePath) -Verbose
Describe "Pre-Flight module tests" { Describe "Pre-Flight module tests" {
$ManifestFilePath = "{0}\src\PSCredentialstore.psd1" -f $RepoRoot
Context "Manifest file related" { Context "Manifest file related" {
It "Test the parsed file itsef" { It "Test the parsed file itself" {
{ Test-ModuleManifest -Path $ManifestFilePath } | Should -Not -Throw { Test-ModuleManifest -Path $ManifestFilePath -Verbose } | Should -Not -Throw
} }
} }
Context "Module consistency tests" { Context "Module consistency tests" {
IT "Importing should work" { It "Importing should work" {
{ Import-Module -Name $ManifestFilePath -Global -Force }| Should -Not -Throw { Import-Module -Name $ManifestFilePath -Global -Force -Verbose } | Should -Not -Throw
} }
} }
} }

View File

@ -0,0 +1,7 @@
Describe "New-CSCertAttribute" {
Context "Basis Tests" {
It "Test1: Should not throw " {
{ New-CSCertAttribute -Country 'DE' -State 'BW' -City 'KA' -Organization 'IT' -OrganizationalUnitName'' -CommonName 'Mycert' } | Should -Not -Throw
}
}
}

View File

@ -0,0 +1,15 @@
Describe "New-CSCertificate" {
Context "Basic Tests" {
It "Test1: Should not throw" {
$attribs = New-CSCertAttribute -Country 'DE' -State 'BW' -City 'KA' -Organization 'IT' -OrganizationalUnitName'' -CommonName 'Mycert'
$CertAttribs = @{
CRTAttribute = $attribs
KeyName = Join-Path -Path (Get-TempDir) -ChildPath '/foo.key'
CertName = Join-Path -Path (Get-TempDir) -ChildPath '/cert.pfx'
}
{ New-CSCertificate @CertAttribs } | Should -Not -Throw
}
}
}

View File

@ -1,53 +0,0 @@
#region HEADER
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
# $RepoRoot = (Get-Item -Path $here).Parent.Parent.FullName
$RepoRoot = (Get-GitDirectory).replace('\.git', '')
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$sut = $sut -replace "\d{2}`_", ''
$suthome = (Get-ChildItem -Path $RepoRoot -Exclude ".\tests\" -Filter $sut -Recurse).FullName
# Skip try loading the source file if it doesn't exists.
If ($suthome.Length -gt 0) {
. $suthome
}
Else {
Write-Warning ("Could not find source file {0}" -f $sut)
}
# load additional functions defined in the repository. Replace the expression <FunctionName>.
. (Get-ChildItem -Path $RepoRoot -Filter "Get-ModuleBase.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Test-Module.ps1" -Recurse).FullName
#endregion HEADER
Describe "Resolve-Dependency" {
Context "Basic syntax check" {
Mock Get-ModuleBase {return "{0}\resources" -f $PWD}
Mock Test-Module {return $true}
It "Test1: Should not throw" {
{ Resolve-Dependency -Name 'foobar2000' } | Should -Not -Throw
}
It "Test2: Output type should be bool" {
Resolve-Dependency -Name 'foobar2000' | Should -BeOfType bool
}
}
Context "Enforce Error" {
# Return incorrect module base to enforce there is no config file.
Mock Get-ModuleBase {return "C:\"}
It "Missing dependency file should not cause an error" {
{ Resolve-Dependency -Name 'awesome'} | Should -Not -Throw
}
It "Missing dependency file should return false" {
Resolve-Dependency -Name 'awesome' | Should -Be $false
}
}
Context "Testing input variations" {
Mock Get-ModuleBase {return "{0}\resources" -f $PWD}
It "Should return true if all given dependencies exist" {
Resolve-Dependency -Name 'Existing' | Should -Be $true
}
It "Mixed results should return false" {
Resolve-Dependency -Name 'PSGetMixed' | Should -Be $false
}
}
}

View File

@ -1,65 +0,0 @@
#region HEADER
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
# $RepoRoot = (Get-Item -Path $here).Parent.Parent.FullName
$RepoRoot = (Get-GitDirectory).replace('\.git', '')
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$sut = $sut -replace "\d{2}`_", ''
$suthome = (Get-ChildItem -Path $RepoRoot -Exclude ".\tests\" -Filter $sut -Recurse).FullName
# Skip try loading the source file if it doesn't exists.
If ($suthome.Length -gt 0) {
. $suthome
}
Else {
Write-Warning ("Could not find source file {0}" -f $sut)
}
# load additional functions defined in the repository. Replace the expression <FunctionName>.
#. (Get-ChildItem -Path $RepoRoot -Filter "Test-CredentialStore.ps1" -Recurse).FullName
#. (Get-ChildItem -Path $RepoRoot -Filter "New-CredentialStore.ps1" -Recurse).FullName
#. (Get-ChildItem -Path $RepoRoot -Filter "Get-CredentialStore.ps1" -Recurse).FullName
#. (Get-ChildItem -Path $RepoRoot -Filter "Get-CredentialStoreItem.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Test-ChallengeFile.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Get-ChallengeFile.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Set-ChallengeFile.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Get-RandomKey.ps1" -Recurse).FullName
#endregion HEADER
Describe "New-CredentialStoreItem" {
Context "Private Credential Store tests" {
It "Test1: Add entry to existing private store." {
If (-not (Test-CredentialStore)) {
New-CredentialStore
}
[String]$tmp = (65..90) + (97..122) | Get-Random -Count 5 | % {[char]$_}
$tmp = $tmp.Replace(' ', '')
$tmpUser = "MyUser"
$tmpPwd = "fooobarysdfsfs" | ConvertTo-SecureString -AsPlainText -Force
$creds = New-Object -TypeName PsCredential -ArgumentList $tmpUser, $tmpPwd
New-CredentialStoreItem -RemoteHost $tmp -Credential $creds
# Had to remove the `{ <exp> } | Shoud Not Throw` because the return would be empty.
$content = Get-CredentialStoreItem -RemoteHost $tmp
$content.UserName | Should Be "MyUser"
#Cleanup Temp entry
$CS = Get-CredentialStore
$CS.PSObject.Properties.Remove($tmp)
ConvertTo-Json -InputObject $CS | Out-File -FilePath ("{0}\CredentialStore.json" -f $env:AppData)
}
}
Context "Test with new shared Credential Store" {
It "Test2: Create new RemoteHost entry" {
# prepare test environment
$tmpCS = 'C:\CredentialStore.json'
New-CredentialStore -Shared -Path $tmpCS
$UserName = "myuser"
$Password = ConvertTo-SecureString -String "mypasswd" -AsPlainText -Force
$mycreds = New-Object -TypeName PSCredential -ArgumentList $UserName, $Password
$RemoteHost = "foobar"
{ New-CredentialStoreItem -Path $tmpCS -RemoteHost $RemoteHost -Credential $mycreds -Shared } | Should Not Throw
$tmpCS = Get-Content -Path $tmpCS -Raw | ConvertFrom-Json
$res = Get-Member -InputObject $tmpCS -Name $RemoteHost -Membertype Properties
$res.Name | Should Be $RemoteHost
}
}
}

View File

@ -0,0 +1,109 @@
Describe "New-CredentialStoreItem" {
Context "Private Credential Store tests" {
It "Test1: Add entry to existing private store." {
# Creat a fresh CredentialStore first
New-CredentialStore -Force
[String]$tmp = (65..90) + (97..122) | Get-Random -Count 5 | ForEach-Object { [char]$_ }
$tmp = $tmp.Replace(' ', '')
$tmpUser = "MyUser"
$tmpPwd = "fooobarysdfsfs" | ConvertTo-SecureString -AsPlainText -Force
$creds = [PSCredential]::new($tmpUser, $tmpPwd)
New-CredentialStoreItem -RemoteHost $tmp -Credential $creds
# Had to remove the `{ <exp> } | Shoud Not Throw` because the return would be empty.
$content = Get-CredentialStoreItem -RemoteHost $tmp
$content.UserName | Should -Be "MyUser"
#Cleanup Temp entry
$CS = Get-CredentialStore
$CS.PSObject.Properties.Remove($tmp)
ConvertTo-Json -InputObject $CS | Out-File -FilePath (Get-DefaultCredentialStorePath)
}
}
Context "Test with new shared Credential Store" {
It "Test2: Create new RemoteHost entry" {
# prepare test environment
$tmpCS = Join-Path -Path (Get-TempDir) -ChildPath '/CredentialStore.json'
New-CredentialStore -Shared -Path $tmpCS -Force
$UserName = "myuser"
$Password = ConvertTo-SecureString -String "mypasswd" -AsPlainText -Force
$mycreds = [PSCredential]::new($UserName, $Password)
$RemoteHost = "foobar"
{ New-CredentialStoreItem -Shared -Path $tmpCS -RemoteHost $RemoteHost -Credential $mycreds } | Should -Not -Throw
$tmpCS = Get-Content -Path $tmpCS -Raw | ConvertFrom-Json
$res = Get-Member -InputObject $tmpCS -Name $RemoteHost -Membertype Properties
$res.Name | Should -Be $RemoteHost
}
It "Adds Item with identifier to shared store" {
$tmpCS = Join-Path -Path (Get-TempDir) -ChildPath '/CredentialStore.json'
New-CredentialStore -Shared -Path $tmpCS -Force
$UserName = "myuser"
$Password = ConvertTo-SecureString -String "mypasswd" -AsPlainText -Force
$mycreds = [PSCredential]::new($UserName, $Password)
$RemoteHost = "foobar2"
New-CredentialStoreItem -Shared -Path $tmpCS -RemoteHost $RemoteHost -Credential $mycreds -Identifier 'Foo'
$writtenItem = Get-CredentialStoreItem -Shared -Path $tmpCS -RemoteHost $RemoteHost -Identifier 'Foo'
($writtenItem.UserName -eq $UserName) -and ($writtenItem.Password.Length -gt 0) | Should -Be $true
}
}
Context "Test optional parameter lookup" {
It "Test missing Credential" {
function global:Get-Credential ([string]$Message) {
$UserName = 'testuser'
$Password = ConvertTo-SecureString -String "mypasswd" -AsPlainText -Force
return [PSCredential]::new($UserName, $Password)
}
$tmpCS = Join-Path -Path (Get-TempDir) -ChildPath '/CredentialStore.json'
New-CredentialStoreItem -Path $tmpCs -Shared -RemoteHost 'foobar3'
$writtenItem = Get-CredentialStoreItem -Path $tmpCS -Shared -RemoteHost 'foobar3'
$writtenItem.UserName | Should -Be "testuser"
Remove-Item -Path 'Function:\Get-Credential'
}
}
Context "General Exception handling" {
Mock Test-CredentialStore { return $false }
It "Missing CredentialStore should throw" {
{ New-CredentialStoreItem -Shared -Path 'C:\missingStore.json' -RemoteHost 'notrelevant' } | Should -Throw "Could not add anything"
}
}
Context "Testing pipeline paramter" {
It "Add the item with credential value from pipe" {
$UserName = 'pipeUser'
$Password = ConvertTo-SecureString -String "pipePasswd" -AsPlainText -Force
{ [PSCredential]::new($UserName, $Password) | New-CredentialStoreItem -RemoteHost 'PipeHost' } | Should -Not -Throw
}
It "Testing written item" {
(Get-CredentialStoreItem -RemoteHost 'PipeHost').UserName | Should -Be 'pipeUser'
}
}
Context "Testing items with certficiate store" {
It "Create item in new store with cert store link" {
New-CredentialStore -UseCertStore -Force
$Path = Get-DefaultCredentialStorePath
$StoreHome = Split-Path -Path $Path -Parent
$CertFile = Join-Path -Path $StoreHome -ChildPath 'PSCredentialStore.pfx'
$Cert = Get-PfxCertificate -FilePath $CertFile
$myStore = [System.Security.Cryptography.X509Certificates.X509Store]::new('My')
$myStore.Open("ReadWrite")
$myStore.Add($Cert)
$MyStore.Close()
$UserName = 'testuser'
$Password = ConvertTo-SecureString -String "mypasswd" -AsPlainText -Force
[PSCredential]::new($UserName, $Password) | New-CredentialStoreItem -RemoteHost 'foobarcerts'
$writtenItem = Get-CredentialStoreItem -RemoteHost 'foobarcerts'
$writtenItem.UserName | Should -Be "testuser"
$writtenItem.GetNetworkCredential().Password | Should -Be 'mypasswd'
}
}
}

View File

@ -0,0 +1,10 @@
Describe "Test-CSPfxCertificate" {
Context "Basic Tests" {
It "Should not Throw" {
{ Test-CSPfxCertificate -Thumbprint '12345' -StoreName My -StoreLocation CurrentUser } | Should -Not -Throw
}
It "Should return false" {
Test-CSPfxCertificate -Thumbprint '12345' -StoreName My -StoreLocation CurrentUser | Should -Be $false
}
}
}

View File

@ -0,0 +1,49 @@
Describe "Get-DefaultCredentialStorePath" {
Context "Basic syntax test" {
It "Test1: Should not throw" {
{ Get-DefaultCredentialStorePath } | Should -Not -Throw
}
}
Context "Private Type" {
It "Should return correct paths" {
$Path = Get-DefaultCredentialStorePath
#Write-Verbose -Message ('Delivered path is: {0}' -f $Path) -Verbose
if ($Env:APPVEYOR) {
$PathRef = Join-Path -Path $Env:APPDATA -ChildPath 'CredentialStore.json'
$Path | Should -Be $PathRef
}
elseif ($ENV:TRAVIS) {
if ($IsLinux) {
$PathRef = Join-Path -Path $Env:HOME -ChildPath 'CredentialStore.json'
$Path | Should -Be $PathRef
}
elseif ($IsMacOS) {
$PathRef = Join-Path -Path $Env:HOME -ChildPath 'CredentialStore.json'
$Path | Should -Be $PathRef
}
}
}
}
Context "Shared Type" {
It "Should return correct paths" {
$Path = Get-DefaultCredentialStorePath -Shared
#Write-Verbose -Message ('Delivered path is: {0}' -f $Path) -Verbose
if ($Env:APPVEYOR) {
$PathRef = Join-Path -Path $env:ProgramData -ChildPath 'PSCredentialStore/CredentialStore.json'
$Path | Should -Be $PathRef
}
elseif ($ENV:TRAVIS) {
if ($IsLinux) {
$PathRef = Join-Path -Path '/var/opt' -ChildPath 'PSCredentialStore/CredentialStore.json'
$Path | Should -Be $PathRef
}
elseif ($IsMacOS) {
$PathRef = Join-Path -Path '/var/opt' -ChildPath 'PSCredentialStore/CredentialStore.json'
$Path | Should -Be $PathRef
}
}
}
}
}

View File

@ -0,0 +1,7 @@
Describe "Get-ModuleBase" {
Context "Basic syntax check" {
It "Test1: Should not throw" {
{ Get-ModuleBase } | Should -Not -Throw
}
}
}

View File

@ -0,0 +1,13 @@
Describe "Get-RandomKey" {
Context "Basic input tests" {
It "Test1: Should not throw " {
{Get-RandomAESKey} | Should -Not -Throw
}
}
Context "Basic syntax check" {
It "Test2: Should return a key with a length of 32 bytes" {
$Key = Get-RandomAESKey
$Key.length | Should -Be 32
}
}
}

View File

@ -0,0 +1,27 @@
Describe "Get-TempDir" {
Context "Basic tests" {
It "Should not throw" {
{Get-TempDir} | Should -Not -Throw
}
It "Should return the correct os tmp path" {
$Path = Get-TempDir
if ($ENV:TRAVIS) {
if ($IsLinux) {
$RefPath = (Resolve-Path -Path '/tmp/').Path
$Path | Should -Be $RefPath
}
if ($IsMacOS) {
$RefPath = (Resolve-Path -Path '/tmp/').Path
$Path | Should -Be $RefPath
}
}
if ($Env:APPVEYOR) {
if (($isWindows) -or ($PSVersionTable.PSVersion.Major -lt 6) -or ($PSVersionTable.PSEdition -eq 'Desktop')) {
$RefPath = (Resolve-Path -Path $env:TEMP).Path
$Path | Should -Be $RefPath
}
}
}
}
}

View File

@ -0,0 +1,35 @@
Describe "Resolve-Dependency" {
Context "Basic syntax check" {
Mock Get-ModuleBase {return (Join-Path -Path $PWD -ChildPath '/resources')}
Mock Test-Module {return $true}
It "Test1: Should not throw" {
{ Resolve-Dependency -Name 'foobar2000' } | Should -Not -Throw
}
It "Test2: Output type should be bool" {
Resolve-Dependency -Name 'foobar2000' | Should -BeOfType bool
}
}
Context "Enforce Error" {
# Return incorrect module base to enforce there is no config file.
Mock Get-ModuleBase {
if ($IsWindows) {return "C:\"}
elseif ($isLinux) {return "/"}
}
It "Missing dependency file should not cause an error" {
{ Resolve-Dependency -Name 'awesome'} | Should -Not -Throw
}
It "Missing dependency file should return true" {
Resolve-Dependency -Name 'awesome' | Should -Be $true
}
}
Context "Testing input variations" {
Mock Get-ModuleBase {return (Join-Path -Path $PWD -ChildPath '/resources')}
It "Should return true if all given dependencies exist" {
Resolve-Dependency -Name 'Existing' | Should -Be $true
}
It "Mixed results should return false" {
Resolve-Dependency -Name 'PSGetMixed' | Should -Be $false
}
}
}

View File

@ -0,0 +1,26 @@
Describe "Test-ModuleName" {
Context "Basic input tests" {
It "Testing standard module should not throw" {
{ Test-Module -Name 'PowerShellGet' } | Should -Not -Throw
}
It "Existing module should return true" {
Test-Module -Name 'PowerShellGet' | Should -Be $true
}
}
Context "Working with modules" {
It "Loading first module should not throw " {
$Mod = Get-Module -ListAvailable | Select-Object -First 1
{ Test-Module -Name $Mod.Name } | Should -Not -Throw
}
It "Loading first module should return true" {
$Snap = Get-Module -ListAvailable | Select-Object -First 1
Test-Module -Name $Snap.Name | Should -Be $true
}
It "Not existing module should return false" {
Test-Module -Name 'foobar2000' | Should -Be $false
}
It "StopifFails switch should thrown an error" {
{Test-Module -Name 'foobar2000' -StopIfFails }| Should -Throw
}
}
}

View File

@ -1,37 +0,0 @@
#region HEADER
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
# $RepoRoot = (Get-Item -Path $here).Parent.Parent.FullName
$RepoRoot = (Get-GitDirectory).replace('\.git', '')
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$sut = $sut -replace "\d{2}`_", ''
$suthome = (Get-ChildItem -Path $RepoRoot -Exclude ".\tests\" -Filter $sut -Recurse).FullName
# Skip try loading the source file if it doesn't exists.
If ($suthome.Length -gt 0) {
. $suthome
}
Else {
Write-Warning ("Could not find source file {0}" -f $sut)
}
# load additional functions defined in the repository. Replace the expression <FunctionName>.
#. (Get-ChildItem -Path $RepoRoot -Filter "Test-CredentialStore.ps1" -Recurse).FullName
#endregion HEADER
Describe "Get-CredentialStore" {
Context "Basic logic tests" {
$TestCredentialStore = Resolve-Path -Path ("{0}\resources\cs\CredentialStore.json" -f $RepoRoot)
It "Test1: Read CS without params" {
If (Test-Path -Path ("{0}\CredentialStore.json" -f $env:APPDATA)) {
{Get-CredentialStore} | Should Not Throw
}
Else {
Write-Warning "Default private Credential Store not found. Skipping..."
}
}
It "Test2: Read Credential Store with testing data" {
{Get-CredentialStore -Path $TestCredentialStore} | Should Not Throw
}
}
}

View File

@ -1,114 +0,0 @@
#region HEADER
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
# $RepoRoot = (Get-Item -Path $here).Parent.Parent.FullName
$RepoRoot = (Get-GitDirectory).replace('\.git', '')
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$sut = $sut -replace "\d{2}`_", ''
$suthome = (Get-ChildItem -Path $RepoRoot -Exclude ".\tests\" -Filter $sut -Recurse).FullName
# Skip try loading the source file if it doesn't exists.
If ($suthome.Length -gt 0) {
. $suthome
}
Else {
Write-Warning ("Could not find source file {0}" -f $sut)
}
# load additional functions defined in the repository. Replace the expression <FunctionName>.
#. (Get-ChildItem -Path $RepoRoot -Filter "Test-CredentialStore.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Test-ChallengeFile.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Set-ChallengeFile.ps1" -Recurse).FullName
. (Get-ChildItem -Path $RepoRoot -Filter "Get-RandomKey.ps1" -Recurse).FullName
#endregion HEADER
# Backup existing credential stores
$VerbosePreference = "Continue"
Write-Verbose "Backup private Credential Store..."
$CSPath = ("{0}\CredentialStore.json" -f $env:APPDATA)
$BackupFile = "{0}.back" -f $CSPath
If (Test-Path -Path $CSPath) {
Move-Item -Path $CSPath -Destination $BackupFile
}
Write-Verbose "Backup shared CredentialStore..."
$CSShared = ("{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData)
$BackupSharedFile = "{0}.back" -f $CSShared
If (Test-Path -Path $CSShared) {
Move-Item -Path $CSShared -Destination $BackupSharedFile
}
Write-Verbose "Remove old CredentialStore in Temp dir"
$CSTemp = "{0}\CredentialStore.json" -f $Env:TEMP
If (Test-Path -Path $CSTemp) {
Remove-Item -Path $CSTemp
}
$VerbosePreference = "SilentlyContinue"
Describe "New-CredentialStore" {
Context "Private CS tests" {
$pCS = Join-Path -Path $env:APPDATA -ChildPath "CredentialStore.json"
It "Test1: Create new private CredentialStore" {
New-CredentialStore
$result = Test-Path -Path $pCS
$CS = Get-Content -Path $pCS -Raw | ConvertFrom-Json
($result -eq $True) -and ($CS.Type -eq "Private") | Should Be $True
}
It "Test2: Try to override private Store" {
{New-CredentialStore} | Should Throw
}
It "Test3: Reset existing Credential Store" {
$now = Get-Date
$CS = Get-Content -Path $pCS -Raw | ConvertFrom-Json
$CSCreation = [DateTime]$CS.Creation
New-CredentialStore -Force
$now -gt $csCreation | Should Be $True
}
}
Context "Shared CS tests" {
$pCS = Join-Path -Path $env:ProgramData -ChildPath "PSCredentialStore\CredentialStore.json"
It "Test1: Create a new Shared Credential Store" {
New-CredentialStore -Shared
Test-Path -Path ("{0}\PSCredentialStore\CredentialStore.json" -f $env:ProgramData) | Should Be $True
}
It "Test2: Try to override existing shared CS" {
{New-CredentialStore -Shared} | Should Throw
}
It "Test3: Reset shared CredentialStore" {
$now = Get-Date
$CS = Get-Content -Path $pCS -Raw | ConvertFrom-Json
$CSCreation = [DateTime]$CS.Creation
New-CredentialStore -Force -Shared
$now -gt $csCreation | Should Be $True
}
}
Context "Custom Shared CS tests" {
$pCS = Join-Path -Path $env:TEMP -ChildPath "CredentialStore.json"
It "Test1: Create new custom shared" {
{New-CredentialStore -Path $pCS -Shared} | Should Not Throw
}
It "Test2: Try to override exiting one" {
{New-CredentialStore -Path $pCS -Shared} | Should Throw
}
It "Test3: Reset existing custom CredentialStore" {
{New-CredentialStore -Path $pCS -Shared -Force} | Should Not Throw
}
}
}
# Cleanup test stores and restore existing ones.
$VerbosePreference = "Continue"
Write-Verbose "Restoring private CredentialStore"
If (Test-Path -Path $BackupFile) {
If (Test-Path -Path $CSPath) {
Remove-Item -Path $CSPath
Move-Item -Path $BackupFile -Destination $CSPath
}
}
Write-Verbose "Restoring shared CredentialStore"
If (Test-Path -Path $BackupSharedFile) {
If (Test-Path -Path $CSShared) {
Remove-Item -Path $CSShared
Move-Item -Path $BackupSharedFile -Destination $CSShared
}
}
$VerbosePreference = "SilentlyContinue"

View File

@ -1,40 +0,0 @@
#region HEADER
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
# $RepoRoot = (Get-Item -Path $here).Parent.Parent.FullName
$RepoRoot = (Get-GitDirectory).replace('\.git', '')
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$sut = $sut -replace "\d{2}`_", ''
$suthome = (Get-ChildItem -Path $RepoRoot -Exclude ".\tests\" -Filter $sut -Recurse).FullName
# Skip try loading the source file if it doesn't exists.
If ($suthome.Length -gt 0) {
. $suthome
}
Else {
Write-Warning ("Could not find source file {0}" -f $sut)
}
# load additional functions defined in the repository. Replace the expression <FunctionName>.
# . (Get-ChildItem -Path $RepoRoot -Filter "<Function-Name>.ps1" -Recurse).FullName
#endregion HEADER
Describe "Test-CredentialStore" {
Context "Basic logic tests" {
$TestCredentialStore = Resolve-Path -Path ("{0}\resources\cs\CredentialStore.json" -f $RepoRoot)
It "Test1: Should Not Throw" {
{ Test-CredentialStore -Path $TestCredentialStore } | Should Not Throw
}
It "Test2: Read valid CredentialStore" {
$res = Test-CredentialStore -Path $TestCredentialStore
$res | Should Be $True
}
It "Test3: Read a broken CredentialStore" {
$BrokenCS = Resolve-Path -Path ("{0}\resources\cs\Broken_CS.json" -f $RepoRoot)
$oWarningPreference = $WarningPreference
$WarningPreference = 'SilentlyContinue'
$res = Test-CredentialStore -Path $BrokenCS
$res | Should Be $False
$WarningPreference = $oWarningPreference
}
}
}

View File

@ -0,0 +1,117 @@
# Backup existing credential stores
$VerbosePreference = "Continue"
Write-Verbose "Backup private Credential Store..."
$CSPath = Get-DefaultCredentialStorePath
$BackupFile = "{0}.back" -f $CSPath
If (Test-Path -Path $CSPath) {
Move-Item -Path $CSPath -Destination $BackupFile
}
Write-Verbose "Backup shared CredentialStore..."
$CSShared = Get-DefaultCredentialStorePath -Shared
$BackupSharedFile = "{0}.back" -f $CSShared
If (Test-Path -Path $CSShared) {
Move-Item -Path $CSShared -Destination $BackupSharedFile
}
Write-Verbose "Remove old CredentialStore in Temp dir"
$CSTemp = Join-Path -Path (Get-TempDir) -ChildPath '/CredentialStore.json'
If (Test-Path -Path $CSTemp) {
Remove-Item -Path $CSTemp
}
$VerbosePreference = "SilentlyContinue"
Describe "New-CredentialStore" {
Context "Private CS tests" {
$pCS = Get-DefaultCredentialStorePath
It "Test1: Create new private CredentialStore" {
{ New-CredentialStore -Confirm:$false } | Should -Not -Throw
$result = Test-Path -Path $pCS
$CS = Get-Content -Path $pCS -Raw | ConvertFrom-Json
($result -eq $true) -and ($CS.Type -eq "Private") | Should -Be $true
}
It "Test2: Try to override private Store" {
{ New-CredentialStore -Confirm:$false } | Should -Throw
}
It "Test3: Reset existing Credential Store" {
$now = Get-Date
$CS = Get-Content -Path $pCS -Raw | ConvertFrom-Json
$CSCreation = [DateTime]$CS.Created
New-CredentialStore -Confirm:$false -Force
$now -gt $csCreation | Should -Be $true
}
}
Context "Shared CS tests" {
$sCS = Get-DefaultCredentialStorePath -Shared
It "Test1: Create a new Shared Credential Store" {
{ New-CredentialStore -Confirm:$false -Shared } | Should -Not -Throw
Test-Path -Path $sCS | Should -Be $true
}
It "Test2: Try to override existing shared CS" {
{ New-CredentialStore -Shared -Confirm:$false } | Should -Throw
}
It "Test3: Reset shared CredentialStore" {
$now = Get-Date
$CS = Get-Content -Path $sCS -Raw | ConvertFrom-Json
$CSCreation = [DateTime]$CS.Created
New-CredentialStore -Force -Shared -Confirm:$false
$now -gt $csCreation | Should -Be $true
}
}
Context "Custom Shared CS tests" {
$cCS = Join-Path -Path (Get-TempDir) -ChildPath "CredentialStore.json"
It "Test1: Create new custom shared" {
{ New-CredentialStore -Path $cCS -Shared -Confirm:$false } | Should -Not -Throw
}
It "Test2: Try to override exiting one" {
{ New-CredentialStore -Path $cCS -Shared -Confirm:$false } | Should -Throw
}
It "Test3: Reset existing custom CredentialStore" {
{ New-CredentialStore -Path $cCS -Shared -Force -Confirm:$false } | Should -Not -Throw
}
}
Context "Test exception handling" {
Mock Out-File { throw "foobar exception" }
It "JSON Conversion should fail and throw" {
{ New-CredentialStore -Path (Join-Path -Path (Get-TempDir) -ChildPath '/dummy.json') -Shared -Confirm:$false } | Should -Throw
}
}
Context "Tests for Windows certificate store" {
It "Create new private store and skip certificate linking" {
{ New-CredentialStore -UseCertStore -Force } | Should -Not -Throw
$CS = Get-CredentialStore
$CS.PfxCertificate | Should -Be $null
$CS.Thumbprint | Should -Not -Be $null
$res = Test-CSCertificate -Type Private
#Write-Verbose -Message ('res: {0}' -f $res) -Verbose
$res | Should -Be $true
}
It "Create new shared store and skipt certificate linking" {
{ New-CredentialStore -Shared -UseCertStore -Force } | Should -Not -Throw
$CS = Get-CredentialStore -Shared
$CS.PfxCertificate | Should -Be $null
$CS.Thumbprint | Should -Not -Be $null
$res = Test-CSCertificate -Type Shared
#Write-Verbose -Message ('res: {0}' -f $res) -Verbose
$res | Should -Be $true
}
}
}
# Cleanup test stores and restore existing ones.
$VerbosePreference = "Continue"
Write-Verbose "Restoring private CredentialStore"
If (Test-Path -Path $BackupFile) {
If (Test-Path -Path $CSPath) {
Remove-Item -Path $CSPath
Move-Item -Path $BackupFile -Destination $CSPath
}
}
Write-Verbose "Restoring shared CredentialStore"
If (Test-Path -Path $BackupSharedFile) {
If (Test-Path -Path $CSShared) {
Remove-Item -Path $CSShared
Move-Item -Path $BackupSharedFile -Destination $CSShared
}
}
$VerbosePreference = "SilentlyContinue"

View File

@ -0,0 +1,36 @@
$RepoRoot = (Get-Item -Path (Get-GitDirectory) -Force).Parent | Select-Object -ExpandProperty 'FullName'
Describe "Test-CredentialStore" {
Context "Basic logic tests" {
$TestCredentialStore = Join-Path -Path $RepoRoot -ChildPath '/resources/cs/CredentialStore.json'
It "Test1: Should Not Throw" {
{ Test-CredentialStore -Shared -Path $TestCredentialStore } | Should -Not -Throw
}
It "Test2: Read valid CredentialStore" {
$res = Test-CredentialStore -Shared -Path $TestCredentialStore
$res | Should -Be $true
}
It "Test3: Read a broken CredentialStore" {
$BrokenCS = Join-Path -Path $RepoRoot -ChildPath '{0}/resources/cs/Broken_CS.json'
$oWarningPreference = $WarningPreference
$WarningPreference = 'SilentlyContinue'
$res = Test-CredentialStore -Shared -Path $BrokenCS
$res | Should -Be $false
$WarningPreference = $oWarningPreference
}
It "Test4: Not existing path should return false" {
if ($isWindows -or ($PSVersionTable.PSVersion.Major -eq 5)) {
Test-CredentialStore -Shared -Path 'C:\foobar\CredentialStore.json' | Should -Be $false
}
elseif ($isWindows -or $IsMacOS) {
Test-CredentialStore -Shared -Path '/var/opt/foo.json' | Should -Be $false
}
}
It "Test5: testing private CredentialStore path" {
if (Test-Path -Path (Get-DefaultCredentialStorePath)) {
Remove-Item -Path (Get-DefaultCredentialStorePath)
}
Test-CredentialStore | Should -Be $false
}
}
}

View File

@ -0,0 +1,32 @@
$RepoRoot = (Get-Item -Path (Get-GitDirectory) -Force).Parent | Select-Object -ExpandProperty 'FullName'
Describe "Get-CredentialStore" {
Context "Basic logic tests" {
$TestCredentialStore = Join-Path -Path $RepoRoot -ChildPath 'resources/cs/CredentialStore.json'
$TestPfxCert = Join-Path -Path $RepoRoot -ChildPath 'resources/cs/PSCredentialStore.pfx'
'TestCredentialStore: {0}' -f $TestCredentialStore
It "Test1: Read CS without params" {
if (! (Test-Path -Path (Get-DefaultCredentialStorePath)) ) {
{ New-CredentialStore -Force } | Should -Not -Throw
}
{ Get-CredentialStore } | Should -Not -Throw
}
It "Test2: Read Credential Store with testing data" {
{ Use-CSCertificate -Shared -CredentialStore $TestCredentialStore -Path $TestPfxCert } | Should -Not -Throw
{ Get-CredentialStore -Shared -Path $TestCredentialStore } | Should -Not -Throw
}
It "Test3: Not existing path should return false" {
{ Get-CredentialStore -Shared -Path './CredentialStore.json' } | Should -Throw "Could not find the CredentialStore."
}
}
Context "Testing invalid json data" {
#Mock Test-CredentialStore {return $true}
#Mock Get-Content {return '"foo":"bar",'}
$BrokenCS = Join-Path -Path $RepoRoot -ChildPath 'resources/cs/Broken_CS.json'
Write-Verbose -Message ('BrokenCS Path: {0}' -f $BrokenCS) -Verbose
It "Should throw with invalid CredentialStore" {
{ Get-CredentialStore -Path -Shared $BrokenCS } | Should -Throw
}
}
}

View File

@ -7,7 +7,7 @@
- Module name - Module name
#> #>
$CALLSIGN = 'PSCredentialStore' $CALLSIGN = 'PSCredentialStore'
Write-Host ("Callsign is: {0}" -f $CALLSIGN) -ForegroundColor Yellow Write-Host ("Callsign is: {0}" -f $CALLSIGN) -ForegroundColor Black -BackgroundColor Yellow
Function Invoke-InstallDependencies() { Function Invoke-InstallDependencies() {
@ -16,18 +16,19 @@ Function Invoke-InstallDependencies() {
Process { Process {
Try { Try {
Get-PackageProvider -ListAvailable
Install-PackageProvider -Name NuGet -RequiredVersion '2.8.5.208' -Force -Verbose Install-PackageProvider -Name NuGet -RequiredVersion '2.8.5.208' -Force -Verbose
Import-PackageProvider -Name NuGet -RequiredVersion '2.8.5.208' -Force Import-PackageProvider -Name NuGet -RequiredVersion '2.8.5.208' -Force
Install-Module -Name 'Pester' -Scope CurrentUser -RequiredVersion '4.0.8' -Force -SkipPublisherCheck -AllowClobber Install-Module -Name 'Pester' -Scope CurrentUser -RequiredVersion '4.4.2' -Force -SkipPublisherCheck -AllowClobber
Install-Module -Name 'posh-git' -Scope CurrentUser -RequiredVersion '0.7.1' -Force -SkipPublisherCheck -AllowClobber Install-Module -Name 'posh-git' -Scope CurrentUser -RequiredVersion '1.0.0-beta2' -Force -SkipPublisherCheck -AllowClobber -AllowPrerelease
Install-Module -Name 'PSCoverage' -Scope CurrentUser -Force -SkipPublisherCheck -AllowClobber Install-Module -Name 'PSCoverage' -Scope CurrentUser -Force -SkipPublisherCheck -AllowClobber -RequiredVersion '1.0.78'
Import-Module -Name 'Pester', 'posh-git', 'PSCoverage' Import-Module -Name 'Pester', 'posh-git' , 'PSCoverage'
} }
Catch { Catch {
$MsgParams = @{ $MsgParams = @{
Message = 'Could not install the required dependencies!' Message = 'Could not install the required dependencies!'
Category = 'Error' Category = 'Error'
Details = $_.Exception.Message Details = $_.Exception.Message
} }
Add-AppveyorMessage @MsgParams Add-AppveyorMessage @MsgParams
Throw $MsgParams.Message Throw $MsgParams.Message
@ -39,21 +40,21 @@ Function Invoke-AppVeyorBumpVersion() {
[CmdletBinding()] [CmdletBinding()]
Param() Param()
Write-Host "Listing Env Vars for debugging:" -ForegroundColor Yellow Write-Host "Listing Env Vars for debugging:" -ForegroundColor Black -BackgroundColor Yellow
# Filter Results to prevent exposing secure vars. # Filter Results to prevent exposing secure vars.
Get-ChildItem -Path "Env:*" | Where-Object { $_.name -notmatch "(NuGetToken|CoverallsToken)"} | Sort-Object -Property Name | Format-Table Get-ChildItem -Path "Env:*" | Where-Object { $_.name -notmatch "(NuGetToken|CoverallsToken)"} | Sort-Object -Property Name | Format-Table
Try { Try {
$ModManifest = Get-Content -Path (".\src\{0}.psd1" -f $CALLSIGN) $ModManifest = Get-Content -Path (".\src\{0}.psd1" -f $CALLSIGN)
$BumpedManifest = $ModManifest -replace '0.0.0.9999', $Env:APPVEYOR_BUILD_VERSION $BumpedManifest = $ModManifest -replace '0.0.9999', $Env:APPVEYOR_BUILD_VERSION
Remove-Item -Path (".\src\{0}.psd1" -f $CALLSIGN) Remove-Item -Path (".\src\{0}.psd1" -f $CALLSIGN)
Out-File -FilePath (".\src\{0}.psd1" -f $CALLSIGN) -InputObject $BumpedManifest -NoClobber -Encoding utf8 -Force Out-File -FilePath (".\src\{0}.psd1" -f $CALLSIGN) -InputObject $BumpedManifest -NoClobber -Encoding utf8 -Force
} }
Catch { Catch {
$MsgParams = @{ $MsgParams = @{
Message = 'Could not bump current version into module manifest.' Message = 'Could not bump current version into module manifest.'
Category = 'Error' Category = 'Error'
Details = $_.Exception.Message Details = $_.Exception.Message
} }
Add-AppveyorMessage @MsgParams Add-AppveyorMessage @MsgParams
Throw $MsgParams.Message Throw $MsgParams.Message
@ -62,27 +63,29 @@ Function Invoke-AppVeyorBumpVersion() {
Function Invoke-AppVeyorBuild() { Function Invoke-AppVeyorBuild() {
[CmdletBinding()] [CmdletBinding()]
[OutputType([PsCustomObject])]
Param() Param()
$MsgParams = @{ $MsgParams = @{
Message = 'Creating build artifacts' Message = 'Creating build artifacts'
Category = 'Information' Category = 'Information'
Details = 'Extracting source files and compressing them into zip file.' Details = 'Extracting source files and compressing them into zip file.'
} }
Add-AppveyorMessage @MsgParams Add-AppveyorMessage @MsgParams
$CompParams = @{ $CompParams = @{
Path = "{0}\src\*" -f $env:APPVEYOR_BUILD_FOLDER Path = "{0}\src\*" -f $env:APPVEYOR_BUILD_FOLDER
DestinationPath = "{0}\bin\{1}.zip" -f $env:APPVEYOR_BUILD_FOLDER, $CALLSIGN DestinationPath = "{0}\bin\{1}.zip" -f $env:APPVEYOR_BUILD_FOLDER, $CALLSIGN
Update = $True Update = $True
Verbose = $True Verbose = $True
} }
Compress-Archive @CompParams Compress-Archive @CompParams
$MsgParams = @{ $MsgParams = @{
Message = 'Pushing artifacts' Message = 'Pushing artifacts'
Category = 'Information' Category = 'Information'
Details = 'Pushing artifacts to AppVeyor store.' Details = 'Pushing artifacts to AppVeyor store.'
} }
Add-AppveyorMessage @MsgParams Add-AppveyorMessage @MsgParams
Push-AppveyorArtifact (".\bin\{0}.zip" -f $CALLSIGN) $ArtifactPath = Join-Path -Path '.' -ChildPath ('bin/{0}.zip' -f $CALLSIGN)
Push-AppveyorArtifact $ArtifactPath
} }
Function Invoke-AppVeyorTests() { Function Invoke-AppVeyorTests() {
@ -90,60 +93,85 @@ Function Invoke-AppVeyorTests() {
Param() Param()
$MsgParams = @{ $MsgParams = @{
Message = 'Starting Pester tests' Message = 'Starting Pester tests'
Category = 'Information' Category = 'Information'
Details = 'Now running all test found in .\tests\ dir.' Details = 'Now running all test found in .\tests\ dir.'
} }
Add-AppveyorMessage @MsgParams Add-AppveyorMessage @MsgParams
$testresults = Invoke-Pester -Path ( Get-ChildItem -Path ".\tests\*.Tests.ps1" -Recurse | Sort-Object -Property Name ) -ExcludeTag 'Disabled' -PassThru
ForEach ($Item in $testresults.TestResult) { try {
Write-Host '===== Preload internal private functions =====' -ForegroundColor Black -BackgroundColor Yellow
$Privates = Get-ChildItem -Path (Join-Path -Path $Env:APPVEYOR_BUILD_FOLDER -ChildPath '/src/Private/*') -Include "*.ps1" -Recurse
foreach ($File in $Privates) {
if (Test-Path -Path $File.FullName) {
. $File.FullName
Write-Verbose -Message ('Private function dot-sourced: {0}' -f $File.FullName) -Verbose
}
else {
Write-Warning -Message ('Could not find file: {0} !' -f $File.FullName)
}
}
}
catch {
$_.Exception.Message | Write-Error
throw 'Could not load required private functions!'
}
#$testresults = Invoke-Pester -Path ( Get-ChildItem -Path ".\tests\*.Tests.ps1" -Recurse | Sort-Object -Property Name ) -ExcludeTag 'Disabled' -PassThru
$srcFiles = Get-ChildItem -Path ".\src\*.ps1" -Recurse | Sort-Object -Property 'Name' | Select-Object -ExpandProperty 'FullName'
$testFiles = Get-ChildItem -Path ".\tests\*.Tests.ps1" -Recurse | Sort-Object -Property 'Name' | Select-Object -ExpandProperty 'FullName'
$TestResults = Invoke-Pester -Path $testFiles -CodeCoverage $srcFiles -PassThru
ForEach ($Item in $TestResults.TestResult) {
Switch ($Item.Result) { Switch ($Item.Result) {
"Passed" { "Passed" {
$TestParams = @{ $TestParams = @{
Name = "{0}: {1}" -f $Item.Context, $Item.Name Name = "{0}: {1}" -f $Item.Context, $Item.Name
Framework = "NUnit" Framework = "NUnit"
Filename = $Item.Describe Filename = $Item.Describe
Outcome = "Passed" Outcome = "Passed"
Duration = $Item.Time.Milliseconds Duration = $Item.Time.Milliseconds
} }
Add-AppveyorTest @TestParams Add-AppveyorTest @TestParams
} }
"Failed" { "Failed" {
$TestParams = @{ $TestParams = @{
Name = "{0}: {1}" -f $Item.Context, $Item.Name Name = "{0}: {1}" -f $Item.Context, $Item.Name
Framework = "NUnit" Framework = "NUnit"
Filename = $Item.Describe Filename = $Item.Describe
Outcome = "Failed" Outcome = "Failed"
Duration = $Item.Time.Milliseconds Duration = $Item.Time.Milliseconds
ErrorMessage = $Item.FailureMessage ErrorMessage = $Item.FailureMessage
ErrorStackTrace = $Item.StackTrace ErrorStackTrace = $Item.StackTrace
} }
Add-AppveyorTest @TestParams Add-AppveyorTest @TestParams
} }
Default { Default {
$TestParams = @{ $TestParams = @{
Name = "{0}: {1}" -f $Item.Context, $Item.Name Name = "{0}: {1}" -f $Item.Context, $Item.Name
Framework = "NUnit" Framework = "NUnit"
Filename = $Item.Describe Filename = $Item.Describe
Outcome = "None" Outcome = "None"
Duration = $Item.Time.Milliseconds Duration = $Item.Time.Milliseconds
ErrorMessage = $Item.FailureMessage ErrorMessage = $Item.FailureMessage
ErrorStackTrace = $Item.StackTrace ErrorStackTrace = $Item.StackTrace
} }
Add-AppveyorTest @TestParams Add-AppveyorTest @TestParams
} }
} }
} }
If ($testresults.FailedCount -gt 0) { If ($TestResults.FailedCount -gt 0) {
$MsgParams = @{ $MsgParams = @{
Message = 'Pester Tests failed.' Message = 'Pester Tests failed.'
Category = 'Error' Category = 'Error'
Details = "$($testresults.FailedCount) tests failed." Details = "$($TestResults.FailedCount) tests failed."
} }
Add-AppveyorMessage @MsgParams Add-AppveyorMessage @MsgParams
Throw $MsgParams.Message Throw $MsgParams.Message
} }
return $TestResults.CodeCoverage
} }
Function Invoke-CoverageReport() { Function Invoke-CoverageReport() {
@ -151,14 +179,17 @@ Function Invoke-CoverageReport() {
Param( Param(
[Parameter(Mandatory = $False)] [Parameter(Mandatory = $False)]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[String]$RepoToken = $Env:CoverallsToken [String]$RepoToken = $Env:CoverallsToken,
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[PSCustomObject]$PesterCoverageReport
) )
Import-Module ('.\src\{0}.psm1' -f $CALLSIGN) -Verbose -Force #$CoverageReport | Format-Custom -Depth 5 | Out-String | Write-Verbose
$FileMap = New-PesterFileMap -SourceRoot '.\src' -PesterRoot '.\tests' $CoverageReport = New-CoverageReport -CodeCoverage $PesterCoverageReport -RepoToken $RepoToken
$CoverageReport = New-CoverageReport -PesterFileMap $FileMap -RepoToken $RepoToken
Write-Host "CoverageReport JSON:" -ForegroundColor Yellow Write-Host "CoverageReport JSON:" -ForegroundColor Yellow
$CoverageReport | Out-String | Write-Host #$CoverageReport | ConvertTo-Json -Depth 5 | Out-String | Write-Verbose
Publish-CoverageReport -CoverageReport $CoverageReport Publish-CoverageReport -CoverageReport $CoverageReport
} }
@ -171,37 +202,38 @@ Function Invoke-AppVeyorPSGallery() {
) )
Expand-Archive -Path (".\bin\{0}.zip" -f $CALLSIGN) -DestinationPath ("C:\Users\appveyor\Documents\WindowsPowerShell\Modules\{0}\" -f $CALLSIGN) -Verbose Expand-Archive -Path (".\bin\{0}.zip" -f $CALLSIGN) -DestinationPath ("C:\Users\appveyor\Documents\WindowsPowerShell\Modules\{0}\" -f $CALLSIGN) -Verbose
Import-Module -Name $CALLSIGN -Verbose -Force Import-Module -Name $CALLSIGN -Verbose -Force
Write-Host "Available Package Provider:" -ForegroundColor Yellow Write-Host "Available Package Provider:" -ForegroundColor Black -BackgroundColor Yellow
Get-PackageProvider -ListAvailable Get-PackageProvider -ListAvailable
Write-Host "Available Package Sources:" -ForegroundColor Yellow Write-Host "Available Package Sources:" -ForegroundColor Black -BackgroundColor Yellow
Get-PackageSource Get-PackageSource
Try { Try {
Write-Host "Try to get NuGet Provider:" -ForegroundColor Yellow Write-Host "Try to get NuGet Provider:" -ForegroundColor Black -BackgroundColor Yellow
Get-PackageProvider -Name NuGet -ErrorAction Stop Get-PackageProvider -Name NuGet -ErrorAction Stop
} }
Catch { Catch {
Write-Host "Installing NuGet..." -ForegroundColor Yellow Write-Host "Installing NuGet..." -ForegroundColor Black -BackgroundColor Yellow
Install-PackageProvider -Name NuGet -MinimumVersion '2.8.5.201' -Force -Verbose Install-PackageProvider -Name NuGet -MinimumVersion '2.8.5.201' -Force -Verbose
Import-PackageProvider NuGet -MinimumVersion '2.8.5.201' -Force Import-PackageProvider NuGet -MinimumVersion '2.8.5.201' -Force
} }
Try { Try {
If ($env:APPVEYOR_REPO_BRANCH -eq 'master') { If ($env:APPVEYOR_REPO_BRANCH -eq 'master') {
Write-Host "try to publish module" -ForegroundColor Yellow Write-Host "try to publish module" -ForegroundColor Black -BackgroundColor Yellow
Write-Host ("Callsign is: {0}" -f $CALLSIGN) -ForegroundColor Yellow Write-Host ("Callsign is: {0}" -f $CALLSIGN) -ForegroundColor Black -BackgroundColor Yellow
Publish-Module -Name $CALLSIGN -NuGetApiKey $env:NuGetToken -Verbose -Force Publish-Module -Name $CALLSIGN -NuGetApiKey $env:NuGetToken -Verbose -Force -AllowPrerelease
} }
Else { Else {
Write-Host "Skip publishing to PS Gallery because we are on $($env:APPVEYOR_REPO_BRANCH) branch." -ForegroundColor Yellow Write-Host "Skip publishing to PS Gallery because we are on $($env:APPVEYOR_REPO_BRANCH) branch." -ForegroundColor Black -BackgroundColor Yellow
# had to remove the publish-Module statement because it would publish although the -WhatIf is given. # had to remove the publish-Module statement because it would publish although the -WhatIf is given.
# Publish-Module -Name $CALLSIGN -NuGetApiKey $env:NuGetToken -Verbose -WhatIf # Publish-Module -Name $CALLSIGN -NuGetApiKey $env:NuGetToken -Verbose -WhatIf
} }
} }
Catch { Catch {
$MsgParams = @{ $MsgParams = @{
Message = 'Could not deploy module to PSGallery.' Message = 'Could not deploy module to PSGallery.'
Category = 'Error' Category = 'Error'
Details = $_.Exception.Message Details = $_.Exception.Message
} }
$_.Exception.Message | Write-Error
Add-AppveyorMessage @MsgParams Add-AppveyorMessage @MsgParams
Throw $MsgParams.Message Throw $MsgParams.Message
} }

Some files were not shown because too many files have changed in this diff Show More